Best Citrus code snippet using com.consol.citrus.dsl.runner.DefaultTestRunner.initialize
Source:GoogleSheetsApiTestServer.java
1/*2 * Licensed to the Apache Software Foundation (ASF) under one or more3 * contributor license agreements. See the NOTICE file distributed with4 * this work for additional information regarding copyright ownership.5 * The ASF licenses this file to You under the Apache License, Version 2.06 * (the "License"); you may not use this file except in compliance with7 * the License. You may obtain a copy of the License at8 *9 * http://www.apache.org/licenses/LICENSE-2.010 *11 * Unless required by applicable law or agreed to in writing, software12 * distributed under the License is distributed on an "AS IS" BASIS,13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14 * See the License for the specific language governing permissions and15 * limitations under the License.16 */17package org.apache.camel.component.google.sheets.server;18import java.io.IOException;19import java.nio.file.Path;20import java.util.Arrays;21import java.util.Collections;22import java.util.HashMap;23import java.util.LinkedHashMap;24import java.util.Map;25import java.util.Optional;26import java.util.zip.GZIPInputStream;27import javax.servlet.Filter;28import javax.servlet.FilterChain;29import javax.servlet.ReadListener;30import javax.servlet.ServletException;31import javax.servlet.ServletInputStream;32import javax.servlet.ServletRequest;33import javax.servlet.http.HttpServletRequest;34import javax.servlet.http.HttpServletRequestWrapper;35import javax.servlet.http.HttpServletResponse;36import com.consol.citrus.Citrus;37import com.consol.citrus.dsl.runner.DefaultTestRunner;38import com.consol.citrus.dsl.runner.TestRunner;39import com.consol.citrus.exceptions.CitrusRuntimeException;40import com.consol.citrus.http.server.HttpServer;41import com.consol.citrus.http.server.HttpServerBuilder;42import com.consol.citrus.http.servlet.GzipHttpServletResponseWrapper;43import com.consol.citrus.http.servlet.RequestCachingServletFilter;44import org.eclipse.jetty.server.HttpConfiguration;45import org.eclipse.jetty.server.HttpConnectionFactory;46import org.eclipse.jetty.server.SecureRequestCustomizer;47import org.eclipse.jetty.server.ServerConnector;48import org.eclipse.jetty.server.SslConnectionFactory;49import org.eclipse.jetty.util.ssl.SslContextFactory;50import org.springframework.http.HttpHeaders;51import org.springframework.security.core.authority.SimpleGrantedAuthority;52import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;53import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;54import org.springframework.security.oauth2.provider.AuthorizationRequest;55import org.springframework.security.oauth2.provider.ClientDetails;56import org.springframework.security.oauth2.provider.OAuth2Authentication;57import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager;58import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter;59import org.springframework.security.oauth2.provider.client.BaseClientDetails;60import org.springframework.security.oauth2.provider.client.InMemoryClientDetailsService;61import org.springframework.security.oauth2.provider.token.DefaultTokenServices;62import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;63import org.springframework.web.filter.OncePerRequestFilter;64public final class GoogleSheetsApiTestServer {65 private static Citrus citrus = Citrus.newInstance();66 private final HttpServer httpServer;67 private TestRunner runner;68 /**69 * Prevent direct instantiation.70 */71 private GoogleSheetsApiTestServer(HttpServer httpServer) {72 this.httpServer = httpServer;73 }74 /**75 * Initialize new test run.76 */77 public void init() {78 runner = new DefaultTestRunner(citrus.getApplicationContext(), citrus.createTestContext());79 }80 /**81 * Stop and reset current test run if any.82 */83 public void reset() {84 if (runner != null) {85 runner.purgeEndpoints(action -> action.endpoint(httpServer));86 runner.stop();87 }88 }89 /**90 * Obtains the httpServer.91 * 92 * @return93 */94 public HttpServer getHttpServer() {95 return httpServer;96 }97 public void afterPropertiesSet() throws Exception {98 httpServer.afterPropertiesSet();99 }100 public TestRunner getRunner() {101 return runner;102 }103 /**104 * Builder builds server instance from given http server builder adding more setting options in fluent builder105 * pattern style.106 */107 public static class Builder {108 private final HttpServerBuilder serverBuilder;109 private Path keyStorePath;110 private String keyStorePassword;111 private int securePort = 8443;112 private String basePath = "";113 private String clientId;114 private String clientSecret;115 private String accessToken;116 private String refreshToken;117 public Builder(HttpServerBuilder serverBuilder) {118 this.serverBuilder = serverBuilder;119 }120 public Builder securePort(int securePort) {121 this.securePort = securePort;122 return this;123 }124 public Builder keyStorePath(Path keyStorePath) {125 this.keyStorePath = keyStorePath;126 return this;127 }128 public Builder keyStorePassword(String keyStorePass) {129 this.keyStorePassword = keyStorePass;130 return this;131 }132 public Builder basePath(String basePath) {133 this.basePath = basePath;134 return this;135 }136 public Builder clientId(String clientId) {137 this.clientId = clientId;138 return this;139 }140 public Builder clientSecret(String clientSecret) {141 this.clientSecret = clientSecret;142 return this;143 }144 public Builder accessToken(String accessToken) {145 this.accessToken = accessToken;146 return this;147 }148 public Builder refreshToken(String refreshToken) {149 this.refreshToken = refreshToken;150 return this;151 }152 public GoogleSheetsApiTestServer build() throws Exception {153 SslContextFactory sslContextFactory = new SslContextFactory(true);154 sslContextFactory.setKeyStorePath(keyStorePath.toAbsolutePath().toString());155 sslContextFactory.setKeyStorePassword(keyStorePassword);156 HttpConfiguration parent = new HttpConfiguration();157 parent.setSecureScheme("https");158 parent.setSecurePort(securePort);159 HttpConfiguration httpConfiguration = new HttpConfiguration(parent);160 httpConfiguration.setCustomizers(Collections.singletonList(new SecureRequestCustomizer()));161 ServerConnector sslConnector = new ServerConnector(162 new org.eclipse.jetty.server.Server(), new SslConnectionFactory(sslContextFactory, "http/1.1"),163 new HttpConnectionFactory(httpConfiguration));164 sslConnector.setPort(securePort);165 serverBuilder.connector(sslConnector);166 Map<String, Filter> filterMap = new LinkedHashMap<>();167 filterMap.put("request-caching-filter", new RequestCachingServletFilter());168 filterMap.put("gzip-filter", new GzipServletFilter());169 filterMap.put("oauth2-filter", oauth2Filter());170 Map<String, String> filterMapings = new LinkedHashMap<>();171 filterMapings.put("oauth2-filter", "/" + Optional.ofNullable(basePath).map(path -> path + "/*").orElse("*"));172 serverBuilder.filterMappings(filterMapings);173 serverBuilder.filters(filterMap);174 serverBuilder.applicationContext(citrus.getApplicationContext());175 GoogleSheetsApiTestServer server = new GoogleSheetsApiTestServer(serverBuilder.build());176 server.afterPropertiesSet();177 return server;178 }179 private Filter oauth2Filter() {180 BaseClientDetails clientDetails = new BaseClientDetails();181 clientDetails.setClientId(clientId);182 clientDetails.setClientSecret(clientSecret);183 clientDetails.setAccessTokenValiditySeconds(3000);184 clientDetails.setAutoApproveScopes(Arrays.asList("read", "write"));185 clientDetails.setScope(Arrays.asList("read", "write"));186 clientDetails.setAuthorities(Arrays.asList(new SimpleGrantedAuthority("client_credentials"),187 new SimpleGrantedAuthority("authorization_code"),188 new SimpleGrantedAuthority("password"), new SimpleGrantedAuthority("refresh_token")));189 OAuth2AuthenticationProcessingFilter filter = new OAuth2AuthenticationProcessingFilter();190 OAuth2AuthenticationManager oauth2AuthenticationManager = new OAuth2AuthenticationManager();191 InMemoryClientDetailsService clientDetailsService = new InMemoryClientDetailsService();192 Map<String, ClientDetails> clientDetailsStore = new HashMap<>();193 clientDetailsStore.put(clientId, clientDetails);194 clientDetailsService.setClientDetailsStore(clientDetailsStore);195 oauth2AuthenticationManager.setClientDetailsService(clientDetailsService);196 InMemoryTokenStore tokenStore = new InMemoryTokenStore();197 AuthorizationRequest authorizationRequest = new AuthorizationRequest();198 authorizationRequest.setClientId(clientDetails.getClientId());199 authorizationRequest.setAuthorities(clientDetails.getAuthorities());200 authorizationRequest.setApproved(true);201 OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), null);202 tokenStore.storeAccessToken(new DefaultOAuth2AccessToken(accessToken), authentication);203 tokenStore.storeRefreshToken(new DefaultOAuth2RefreshToken(refreshToken), authentication);204 DefaultTokenServices tokenServices = new DefaultTokenServices();205 tokenServices.setTokenStore(tokenStore);206 tokenServices.setClientDetailsService(clientDetailsService);207 tokenServices.setSupportRefreshToken(true);208 oauth2AuthenticationManager.setTokenServices(tokenServices);209 filter.setAuthenticationManager(oauth2AuthenticationManager);210 return filter;211 }212 }213 private static class GzipServletFilter extends OncePerRequestFilter {214 @Override215 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)216 throws ServletException, IOException {217 HttpServletRequest filteredRequest = request;218 HttpServletResponse filteredResponse = response;219 String contentEncoding = request.getHeader(HttpHeaders.CONTENT_ENCODING);220 if (contentEncoding != null && contentEncoding.contains("gzip")) {221 filteredRequest = new GzipHttpServletRequestWrapper(request);222 }223 String acceptEncoding = request.getHeader(HttpHeaders.ACCEPT_ENCODING);224 if (acceptEncoding != null && acceptEncoding.contains("gzip")) {225 filteredResponse = new GzipHttpServletResponseWrapper(response);226 }227 filterChain.doFilter(filteredRequest, filteredResponse);228 if (filteredResponse instanceof GzipHttpServletResponseWrapper) {229 ((GzipHttpServletResponseWrapper) filteredResponse).finish();230 }231 }232 }233 private static class GzipHttpServletRequestWrapper extends HttpServletRequestWrapper {234 /**235 * Constructs a request adaptor wrapping the given request.236 *237 * @param request238 * @throws IllegalArgumentException if the request is null239 */240 public GzipHttpServletRequestWrapper(HttpServletRequest request) {241 super(request);242 }243 @Override244 public ServletInputStream getInputStream() throws IOException {245 return new GzipServletInputStream(getRequest());246 }247 /**248 * Gzip enabled servlet input stream.249 */250 private static class GzipServletInputStream extends ServletInputStream {251 private final GZIPInputStream gzipStream;252 /**253 * Default constructor using wrapped input stream.254 *255 * @param request256 * @throws IOException257 */258 public GzipServletInputStream(ServletRequest request) throws IOException {259 gzipStream = new GZIPInputStream(request.getInputStream());260 }261 @Override262 public boolean isFinished() {263 try {264 return gzipStream.available() == 0;265 } catch (IOException e) {266 throw new CitrusRuntimeException("Failed to check gzip intput stream availability", e);267 }268 }269 @Override270 public boolean isReady() {271 return true;272 }273 @Override274 public void setReadListener(final ReadListener readListener) {275 throw new UnsupportedOperationException("Unsupported operation");276 }277 @Override278 public int read() {279 try {280 return gzipStream.read();281 } catch (IOException e) {282 throw new CitrusRuntimeException("Failed to read gzip input stream", e);283 }284 }285 @Override286 public int read(byte[] b) throws IOException {287 return gzipStream.read(b);288 }289 @Override290 public int read(byte[] b, int off, int len) throws IOException {291 return gzipStream.read(b, off, len);292 }293 }294 }295}...
initialize
Using AI Code Generation
1package com.consol.citrus.dsl.runner;2import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;3import org.testng.annotations.Test;4public class DefaultTestRunnerInitializeJavaITest extends TestNGCitrusTestRunner {5public void initializeTest() {6 initialize().variable("greeting", "Hello Citrus!");7 echo("${greeting}");8}9}10package com.consol.citrus.dsl.runner;11import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;12import org.testng.annotations.Test;13public class DefaultTestRunnerInitializeGroovyITest extends TestNGCitrusTestRunner {14public void initializeTest() {15 initialize(variables: [greeting: 'Hello Citrus!'])16 echo(greeting)17}18}
initialize
Using AI Code Generation
1DefaultTestRunner runner = new DefaultTestRunner();2runner.initialize();3DefaultTestRunner runner = new DefaultTestRunner();4runner.initialize();5com.consol.citrus.dsl.runner.DefaultTestRunner#initialize()6public void initialize()7com.consol.citrus.dsl.runner.DefaultTestRunner#initialize(java.lang.String)8public void initialize(String name)9com.consol.citrus.dsl.runner.DefaultTestRunner#initialize(java.lang.String,java.lang.String)10public void initialize(String name,11com.consol.citrus.dsl.runner.DefaultTestRunner#initialize(java.lang.String,java.lang.String,org.springframework.core.io.Resource)12public void initialize(String name,13com.consol.citrus.dsl.runner.DefaultTestRunner#initialize(java.lang.String,java.lang.String,org.springframework.core.io.Resource,java.lang.String)14public void initialize(String name,15com.consol.citrus.dsl.runner.DefaultTestRunner#initialize(java.lang.String,java.lang.String,org.springframework.core.io.Resource,java.lang.String,java.lang.String)16public void initialize(String name,17com.consol.citrus.dsl.runner.DefaultTestRunner#initialize(java.lang.String,java.lang.String,org.springframework.core.io.Resource,java.lang.String,java.lang.String,java.lang.String)18public void initialize(String name,19com.consol.citrus.dsl.runner.DefaultTestRunner#initialize(java.lang.String,java.lang.String,org.springframework.core.io.Resource,java.lang.String,java.lang.String,java.lang.String,java.lang.String)20public void initialize(String name,21com.consol.citrus.dsl.runner.DefaultTestRunner#initialize(java.lang.String,java.lang.String,org.springframework.core.io.Resource,java.lang.String,java.lang.String,java.lang.String,java.lang.String,java.lang
initialize
Using AI Code Generation
1public void test() {2 initialize();3 http(httpActionBuilder -> httpActionBuilder.client("httpClient")4 .send()5 .post("/citrus-ws-sample/services/HelloService")6 .contentType(MediaType.TEXT_XML_VALUE)7 "</soapenv:Envelope>"));8 receive(receiveActionBuilder -> receiveActionBuilder.endpoint("helloEndpoint")9 .messageType(MessageType.PLAINTEXT)10 "</soapenv:Envelope>"));
initialize
Using AI Code Generation
1public class SampleTest extends AbstractTestNGCitrusTest {2 public void sampleTest() {3 variable("name", "World");4 echo("Hello ${name}!");5 }6}7- echo: { message: "Hello World!" }
initialize
Using AI Code Generation
1public void test() {2 initialize().name("com.consol.citrus.dsl.runner.DefaultTestRunnerTest");3}4package com.consol.citrus.dsl.runner;5import com.consol.citrus.Citrus;6import com.consol.citrus.annotations.CitrusTest;7import com.consol.citrus.dsl.testng.TestNGCitrusTestRunner;8import com.consol.citrus.testng.CitrusParameters;9import org.testng.annotations.Test;10import static com.consol.citrus.actions.EchoAction.Builder.echo;11import static com.consol.citrus.container.Parallel.Builder.parallel;12import static com.consol.citrus.container.Sequence.Builder.sequential;13import static com.consol.citrus.dsl.builder.Builder.*;14import static com.consol.citrus.http.actions.HttpActionBuilder.http;15public class DefaultTestRunnerTest extends TestNGCitrusTestRunner {16 public void test() {17 variable("greeting", "Hello Citrus!");18 parallel().actions(19 sequential().actions(20 echo("Hello Citrus!"),21 echo("${greeting}")22 sequential().actions(23 http().client("httpClient").send().get("/"),24 http().client("httpClient").receive().response(HttpStatus.OK)25 );26 parallel().actions(27 sequential().actions(28 echo("Hello Citrus!"),29 echo("${greeting}")30 sequential().actions(31 http().client("httpClient").send().get("/"),32 http().client("httpClient").receive().response(HttpStatus.OK)33 );34 parallel().actions(35 sequential().actions(36 echo("Hello Citrus!"),37 echo("${greeting}")38 sequential().actions(39 http().client("httpClient").send().get("/"),40 http().client("httpClient").receive().response(HttpStatus.OK)41 );42 parallel().actions(43 sequential().actions(44 echo("Hello Citrus!"),45 echo("${greeting}")46 sequential().actions(47 http().client("httpClient").send().get("/"),48 http().client("httpClient").receive().response(HttpStatus.OK)49 );50 parallel().actions(51 sequential().actions(52 echo("Hello Citrus!"),53 echo("${greeting}")
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!