code
stringlengths
73
34.1k
label
stringclasses
1 value
public Endpoint getOrCreateEndpoint(TestContext context) { if (endpoint != null) { return endpoint; } else if (StringUtils.hasText(endpointUri)) { endpoint = context.getEndpointFactory().create(endpointUri, context); return endpoint; } else { throw...
java
public boolean shouldExecute(String suiteName, String[] includedGroups) { String baseErrorMessage = "Suite container restrictions did not match %s - do not execute container '%s'"; if (StringUtils.hasText(suiteName) && !CollectionUtils.isEmpty(suiteNames) && ! suiteNames.contains(suiteN...
java
public CamelControlBusActionBuilder route(String id, String action) { super.action.setRouteId(id); super.action.setAction(action); return this; }
java
public CamelControlBusActionBuilder language(String language, String expression) { action.setLanguageType(language); action.setLanguageExpression(expression); return this; }
java
public void handleRequest(String request) { if (messageListener != null) { log.debug("Received Http request"); messageListener.onInboundMessage(new RawMessage(request), null); } else { if (log.isDebugEnabled()) { log.debug("Received Http request:" + NE...
java
public void handleResponse(String response) { if (messageListener != null) { log.debug("Sending Http response"); messageListener.onOutboundMessage(new RawMessage(response), null); } else { if (log.isDebugEnabled()) { log.debug("Sending Http response:" ...
java
private String getRequestContent(HttpServletRequest request) throws IOException { StringBuilder builder = new StringBuilder(); builder.append(request.getProtocol()); builder.append(" "); builder.append(request.getMethod()); builder.append(" "); builder.append(req...
java
private javax.jms.Message receive(String destinationName, String selector) { javax.jms.Message receivedJmsMessage; if (log.isDebugEnabled()) { log.debug("Receiving JMS message on destination: '" + destinationName + (StringUtils.hasText(selector) ? "(" + selector + ")" : "") + "'"); ...
java
private javax.jms.Message receive(Destination destination, String selector) { javax.jms.Message receivedJmsMessage; if (log.isDebugEnabled()) { log.debug("Receiving JMS message on destination: '" + endpointConfiguration.getDestinationName(destination) + (StringUtils.hasText(selector) ? "(" ...
java
public String convert(String messagePayload) { initialize(); // check if we already have XHTML message content if (messagePayload.contains(XHTML_DOCTYPE_DEFINITION)) { return messagePayload; } else { String xhtmlPayload; StringWriter xhtmlWriter = new...
java
public void initialize() { try { if (tidyInstance == null) { tidyInstance = new Tidy(); tidyInstance.setXHTML(true); tidyInstance.setShowWarnings(false); tidyInstance.setQuiet(true); tidyInstance.setEscapeCdata(true); ...
java
public void start() { if (kafkaServer != null) { log.warn("Found instance of Kafka server - avoid duplicate Kafka server startup"); return; } File logDir = createLogDir(); zookeeper = createZookeeperServer(logDir); serverFactory = createServerFactory(); ...
java
public void stop() { if (kafkaServer != null) { try { if (kafkaServer.brokerState().currentState() != (NotRunning.state())) { kafkaServer.shutdown(); kafkaServer.awaitShutdown(); } } catch (Exception e) { ...
java
protected ZooKeeperServer createZookeeperServer(File logDir) { try { return new ZooKeeperServer(logDir, logDir, 2000); } catch (IOException e) { throw new CitrusRuntimeException("Failed to create embedded zookeeper server", e); } }
java
protected File createLogDir() { File logDir = Optional.ofNullable(logDirPath) .map(Paths::get) .map(Path::toFile) .orElse(new File(System.getProperty("java.io.tmpdir"))); if (!logDir.exists()) { ...
java
protected ServerCnxnFactory createServerFactory() { try { ServerCnxnFactory serverFactory = new NIOServerCnxnFactory(); serverFactory.configure(new InetSocketAddress(zookeeperPort), 5000); return serverFactory; } catch (IOException e) { throw new CitrusRun...
java
protected void createKafkaTopics(Set<String> topics) { Map<String, Object> adminConfigs = new HashMap<>(); adminConfigs.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:" + kafkaServerPort); try (AdminClient admin = AdminClient.create(adminConfigs)) { List<NewTopic> newTopi...
java
protected Properties createBrokerProperties(String zooKeeperConnect, int kafkaServerPort, File logDir) { Properties props = new Properties(); props.put(KafkaConfig.BrokerIdProp(), "0"); props.put(KafkaConfig.ZkConnectProp(), zooKeeperConnect); props.put(KafkaConfig.ZkConnectionTimeoutMs...
java
public void doWithMessage(WebServiceMessage responseMessage) throws IOException, TransformerException { // convert and set response for later access via getResponse(): response = endpointConfiguration.getMessageConverter().convertInbound(responseMessage, endpointConfiguration, context); }
java
public void saveReplyDestination(Message receivedMessage, TestContext context) { if (receivedMessage.getHeader(CitrusVertxMessageHeaders.VERTX_REPLY_ADDRESS) != null) { String correlationKeyName = endpointConfiguration.getCorrelator().getCorrelationKeyName(getName()); String correlationK...
java
private ZooKeeper createZooKeeperClient() throws IOException { ZooClientConfig config = getZookeeperClientConfig(); return new ZooKeeper(config.getUrl(), config.getTimeout(), getConnectionWatcher()); }
java
public ZooKeeper getZooKeeperClient() { if (zookeeper == null) { try { zookeeper = createZooKeeperClient(); int retryAttempts = 5; while(!zookeeper.getState().isConnected() && retryAttempts > 0) { LOG.debug("connecting..."); ...
java
private void loadEndpointComponentProperties() { try { endpointComponentProperties = PropertiesLoaderUtils.loadProperties(new ClassPathResource("com/consol/citrus/endpoint/endpoint.components")); } catch (IOException e) { log.warn("Unable to laod default endpoint components from ...
java
private void loadEndpointParserProperties() { try { endpointParserProperties = PropertiesLoaderUtils.loadProperties(new ClassPathResource("com/consol/citrus/endpoint/endpoint.parser")); } catch (IOException e) { log.warn("Unable to laod default endpoint annotation parsers from re...
java
public void setAction(String action) { try { this.action = new URI(action); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid action uri", e); } }
java
public void setTo(String to) { try { this.to = new URI(to); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid to uri", e); } }
java
public void setMessageId(String messageId) { try { this.messageId = new URI(messageId); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid messageId uri", e); } }
java
public void setFrom(String from) { try { this.from = new EndpointReference(new URI(from)); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid from uri", e); } }
java
public void setReplyTo(String replyTo) { try { this.replyTo = new EndpointReference(new URI(replyTo)); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid replyTo uri", e); } }
java
public void setFaultTo(String faultTo) { try { this.faultTo = new EndpointReference(new URI(faultTo)); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid faultTo uri", e); } }
java
private void createHtmlDoc() throws PrompterException { HtmlDocConfiguration configuration = new HtmlDocConfiguration(); String heading = prompter.prompt("Enter overview title:", configuration.getHeading()); String columns = prompter.prompt("Enter number of columns in overview:", configuration....
java
private void createExcelDoc() throws PrompterException { ExcelDocConfiguration configuration = new ExcelDocConfiguration(); String company = prompter.prompt("Enter company:", configuration.getCompany()); String author = prompter.prompt("Enter author:", configuration.getAuthor()); String ...
java
public static String changeDate(String date, String dateOffset, String dateFormat, TestContext context) { return new ChangeDateFunction().execute(Arrays.asList(date, dateOffset, dateFormat), context); }
java
public static String createCDataSection(String content, TestContext context) { return new CreateCDataSectionFunction().execute(Collections.singletonList(content), context); }
java
public static String digestAuthHeader(String username, String password, String realm, String noncekey, String method, String uri, String opaque, String algorithm, TestContext context) { return new DigestAuthHeaderFunction().execute(Arrays.asList(username, password, realm, noncekey, method, uri, opaque, algorith...
java
public static String randomUUID(TestContext context) { return new RandomUUIDFunction().execute(Collections.<String>emptyList(), context); }
java
public static String escapeXml(String content, TestContext context) { return new EscapeXmlFunction().execute(Collections.singletonList(content), context); }
java
public static String readFile(String filePath, TestContext context) { return new ReadFileResourceFunction().execute(Collections.singletonList(filePath), context); }
java
public static void parseJsonPathElements(Element validateElement, Map<String, Object> validateJsonPathExpressions) { List<?> jsonPathElements = DomUtils.getChildElementsByTagName(validateElement, "json-path"); if (jsonPathElements.size() > 0) { for (Iterator<?> jsonPathIterator = jsonPathEle...
java
public static String readToString(Resource resource, Charset charset) throws IOException { if (simulationMode) { if (resource instanceof ClassPathResource) { return ((ClassPathResource) resource).getPath(); } else if (resource instanceof FileSystemResource) { ...
java
public static String readToString(InputStream inputStream, Charset charset) throws IOException { return new String(FileCopyUtils.copyToByteArray(inputStream), charset); }
java
public static void writeToFile(InputStream inputStream, File file) { try (InputStreamReader inputStreamReader = new InputStreamReader(inputStream)) { writeToFile(FileCopyUtils.copyToString(inputStreamReader), file, getDefaultCharset()); } catch (IOException e) { throw new CitrusR...
java
public static void writeToFile(String content, File file, Charset charset) { if (log.isDebugEnabled()) { log.debug(String.format("Writing file resource: '%s' (encoding is '%s')", file.getName(), charset.displayName())); } if (!file.getParentFile().exists()) { if (!file.g...
java
public static List<File> findFiles(final String startDir, final Set<String> fileNamePatterns) { /* file names to be returned */ final List<File> files = new ArrayList<File>(); /* Stack to hold potential sub directories */ final Stack<File> dirs = new Stack<File>(); /* start dire...
java
@SuppressWarnings("unchecked") public static ClientServerEndpointBuilder<DockerClientBuilder, DockerClientBuilder> docker() { return new ClientServerEndpointBuilder(new DockerClientBuilder(), new DockerClientBuilder()) { @Override public EndpointBuilder<? extends Endpoint> server() {...
java
@SuppressWarnings("unchecked") public static ClientServerEndpointBuilder<KubernetesClientBuilder, KubernetesClientBuilder> kubernetes() { return new ClientServerEndpointBuilder(new KubernetesClientBuilder(), new KubernetesClientBuilder()) { @Override public EndpointBuilder<? extends ...
java
@Override protected void validateFaultDetailString(String receivedDetailString, String controlDetailString, TestContext context, ValidationContext validationContext) throws ValidationException { XmlMessageValidationContext xmlMessageValidationContext; if (validationContext inst...
java
public void start() { if (!isStarted()) { if (getEndpointConfiguration().getWebDriver() != null) { webDriver = getEndpointConfiguration().getWebDriver(); } else if (StringUtils.hasText(getEndpointConfiguration().getRemoteServerUrl())) { webDriver = createR...
java
public void stop() { if (isStarted()) { log.info("Stopping browser " + webDriver.getCurrentUrl()); try { log.info("Trying to close the browser " + webDriver + " ..."); webDriver.quit(); } catch (UnreachableBrowserException e) { ...
java
public String storeFile(Resource file) { try { File newFile = new File(temporaryStorage.toFile(), file.getFilename()); log.info("Store file " + file + " to " + newFile); FileUtils.copyFile(file.getFile(), newFile); return newFile.getCanonicalPath(); } c...
java
public String getStoredFile(String filename) { try { File stored = new File(temporaryStorage.toFile(), filename); if (!stored.exists()) { throw new CitrusRuntimeException("Failed to access stored file: " + stored.getCanonicalPath()); } return sto...
java
private WebDriver createLocalWebDriver(String browserType) { switch (browserType) { case BrowserType.FIREFOX: FirefoxProfile firefoxProfile = getEndpointConfiguration().getFirefoxProfile(); /* set custom download folder */ firefoxProfile.setPreference...
java
private RemoteWebDriver createRemoteWebDriver(String browserType, String serverAddress) { try { switch (browserType) { case BrowserType.FIREFOX: DesiredCapabilities defaultsFF = DesiredCapabilities.firefox(); defaultsFF.setCapability(FirefoxDri...
java
private Path createTemporaryStorage() { try { Path tempDir = Files.createTempDirectory("selenium"); tempDir.toFile().deleteOnExit(); log.info("Download storage location is: " + tempDir.toString()); return tempDir; } catch (IOException e) { thr...
java
protected void sendClientRequest(HttpMessage request) { BuilderSupport<HttpActionBuilder> action = builder -> { HttpClientActionBuilder.HttpClientSendActionBuilder sendBuilder = builder.client(httpClient).send(); HttpClientRequestActionBuilder requestBuilder; if (request.get...
java
protected void receiveClientResponse(HttpMessage response) { runner.http(action -> { HttpClientResponseActionBuilder responseBuilder = action.client(httpClient).receive() .response(response.getStatusCode()) .message(response); for (Map.Entry<String, Strin...
java
protected void receiveServerRequest(HttpMessage request) { BuilderSupport<HttpActionBuilder> action = builder -> { HttpServerActionBuilder.HttpServerReceiveActionBuilder receiveBuilder = builder.server(httpServer).receive(); HttpServerRequestActionBuilder requestBuilder; if ...
java
Cookie[] convertCookies(HttpEntity<?> httpEntity) { final List<Cookie> cookies = new LinkedList<>(); List<String> inboundCookies = httpEntity.getHeaders().get(HttpHeaders.SET_COOKIE); if (inboundCookies != null) { for (String cookieString : inboundCookies) { Cookie c...
java
String getCookieString(Cookie cookie) { StringBuilder builder = new StringBuilder(); builder.append(cookie.getName()); builder.append("="); builder.append(cookie.getValue()); if (cookie.getVersion() > 0) { builder.append(";" + VERSION + "=").append(cookie.getVersion...
java
private Cookie convertCookieString(String cookieString) { Cookie cookie = new Cookie(getCookieParam(NAME, cookieString), getCookieParam(VALUE, cookieString)); if (cookieString.contains(COMMENT)) { cookie.setComment(getCookieParam(COMMENT, cookieString)); } if (cookieString....
java
private String getCookieParam(String param, String cookieString) { if (param.equals(NAME)) { return cookieString.substring(0, cookieString.indexOf('=')); } if (param.equals(VALUE)) { if (cookieString.contains(";")) { return cookieString.substring(cookieSt...
java
protected void parseEndpointConfiguration(BeanDefinitionBuilder endpointConfigurationBuilder, Element element, ParserContext parserContext) { BeanDefinitionParserUtils.setPropertyValue(endpointConfigurationBuilder, element.getAttribute("timeout"), "timeout"); }
java
public InputActionBuilder answers(String... answers) { if (answers.length == 0) { throw new CitrusRuntimeException("Please specify proper answer possibilities for input action"); } StringBuilder validAnswers = new StringBuilder(); for (String answer : answers) { validAnswers.append...
java
public void beforeSuite(String suiteName, String ... testGroups) { testSuiteListener.onStart(); if (!CollectionUtils.isEmpty(beforeSuite)) { for (SequenceBeforeSuite sequenceBeforeSuite : beforeSuite) { try { if (sequenceBeforeSuite.shouldExecute(suiteNam...
java
public void afterSuite(String suiteName, String ... testGroups) { testSuiteListener.onFinish(); if (!CollectionUtils.isEmpty(afterSuite)) { for (SequenceAfterSuite sequenceAfterSuite : afterSuite) { try { if (sequenceAfterSuite.shouldExecute(suiteName, te...
java
public JmxMessage attribute(String name, Object value) { return attribute(name, value, value.getClass()); }
java
public JmxMessage attribute(String name, Object value, Class<?> valueType) { if (mbeanInvocation == null) { throw new CitrusRuntimeException("Invalid access to attribute for JMX message"); } ManagedBeanInvocation.Attribute attribute = new ManagedBeanInvocation.Attribute(); a...
java
public JmxMessage operation(String name) { if (mbeanInvocation == null) { throw new CitrusRuntimeException("Invalid access to operation for JMX message"); } ManagedBeanInvocation.Operation operation = new ManagedBeanInvocation.Operation(); operation.setName(name); mb...
java
public JmxMessage parameter(Object arg, Class<?> argType) { if (mbeanInvocation == null) { throw new CitrusRuntimeException("Invalid access to operation parameter for JMX message"); } if (mbeanInvocation.getOperation() == null) { throw new CitrusRuntimeException("Invalid...
java
public Message dispatchMessage(Message request, String mappingKey) { return mappingStrategy.getEndpointAdapter(mappingKey).handleMessage(request); }
java
protected void enrichEndpointConfiguration(EndpointConfiguration endpointConfiguration, Map<String, String> parameters, TestContext context) { for (Map.Entry<String, String> parameterEntry : parameters.entrySet()) { Field field = ReflectionUtils.findField(endpointConfiguration.getClass(), parameterE...
java
protected Map<String, String> getEndpointConfigurationParameters(Map<String, String> parameters, Class<? extends EndpointConfiguration> endpointConfigurationType) { Map<String, String> params = new HashMap<String, String>(); for (Map....
java
protected String getParameterString(Map<String, String> parameters, Class<? extends EndpointConfiguration> endpointConfigurationType) { StringBuilder paramString = new StringBuilder(); for (Map.Entry<String, String> parameterEntry : parameters.entrySet()) { ...
java
private com.github.dockerjava.api.DockerClient createDockerClient() { return DockerClientImpl.getInstance(getDockerClientConfig()) .withDockerCmdExecFactory(new JerseyDockerCmdExecFactory()); }
java
public com.github.dockerjava.api.DockerClient getDockerClient() { if (dockerClient == null) { dockerClient = createDockerClient(); } return dockerClient; }
java
private void purgeQueue(String queueName, Session session) throws JMSException { purgeDestination(getDestination(session, queueName), session, queueName); }
java
private void purgeQueue(Queue queue, Session session) throws JMSException { purgeDestination(queue, session, queue.getQueueName()); }
java
private void purgeDestination(Destination destination, Session session, String destinationName) throws JMSException { if (log.isDebugEnabled()) { log.debug("Try to purge destination " + destinationName); } int messagesPurged = 0; MessageConsumer messageConsumer = session.cre...
java
private Destination getDestination(Session session, String queueName) throws JMSException { return new DynamicDestinationResolver().resolveDestinationName(session, queueName, false); }
java
protected Connection createConnection() throws JMSException { if (connectionFactory instanceof QueueConnectionFactory) { return ((QueueConnectionFactory) connectionFactory).createQueueConnection(); } return connectionFactory.createConnection(); }
java
protected Session createSession(Connection connection) throws JMSException { if (connection instanceof QueueConnection) { return ((QueueConnection) connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE); } return connection.createSession(false, Session.AUTO_ACKNOWLEDGE); ...
java
public SecurityHandler getObject() throws Exception { ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler(); securityHandler.setAuthenticator(authenticator); securityHandler.setRealmName(realm); for (Entry<String, Constraint> constraint : constraints.entrySet()) { ...
java
public void afterPropertiesSet() throws Exception { if (loginService == null) { loginService = new SimpleLoginService(); ((SimpleLoginService) loginService).setName(realm); } }
java
private void writeFtpReply(FtpSession session, FtpMessage response) { try { CommandResultType commandResult = response.getPayload(CommandResultType.class); FtpReply reply = new DefaultFtpReply(Integer.valueOf(commandResult.getReplyCode()), commandResult.getReplyString()); se...
java
public static List<String> getParameterList(String parameterString) { List<String> parameterList = new ArrayList<>(); StringTokenizer tok = new StringTokenizer(parameterString, ","); while (tok.hasMoreElements()) { String param = tok.nextToken().trim(); parameterList.add...
java
protected void executeActions(TestContext context) { context.setVariable(indexName, String.valueOf(index)); for (TestAction action: actions) { setActiveAction(action); action.execute(context); } }
java
protected boolean checkCondition(TestContext context) { if (conditionExpression != null) { return conditionExpression.evaluate(index, context); } // replace dynamic content with each iteration String conditionString = condition; if (conditionString.indexOf(Citrus.VAR...
java
private ObjectFactory getObjectFactory() throws IllegalAccessException { if (Env.INSTANCE.get(ObjectFactory.class.getName()).equals(CitrusObjectFactory.class.getName())) { return CitrusObjectFactory.instance(); } else if (Env.INSTANCE.get(ObjectFactory.class.getName()).equals(CitrusSpringObj...
java
public static void initializeCitrus(ApplicationContext applicationContext) { if (citrus != null) { if (!citrus.getApplicationContext().equals(applicationContext)) { log.warn("Citrus instance has already been initialized - creating new instance and shutting down current instance"); ...
java
protected void executeStatements(TestContext context) { for (String stmt : statements) { try { final String toExecute; if (stmt.trim().endsWith(";")) { toExecute = context.replaceDynamicContentInString(stmt.trim().substring(0, stmt.trim().length(...
java
private void dispatch(final ProcessingMessage message) throws ProcessingException { final LogLevel level = message.getLogLevel(); if (level.compareTo(exceptionThreshold) >= 0) throw message.asException(); if (level.compareTo(currentLevel) > 0) currentLevel = level; ...
java
private void addRequestCachingFilter() { FilterMapping filterMapping = new FilterMapping(); filterMapping.setFilterName("request-caching-filter"); filterMapping.setPathSpec("/*"); FilterHolder filterHolder = new FilterHolder(new RequestCachingServletFilter()); filterHolder.setNa...
java
private void addGzipFilter() { FilterMapping filterMapping = new FilterMapping(); filterMapping.setFilterName("gzip-filter"); filterMapping.setPathSpec("/*"); FilterHolder filterHolder = new FilterHolder(new GzipServletFilter()); filterHolder.setName("gzip-filter"); serv...
java
private boolean containsNode(NodeList findings, Node node) { for (int i = 0; i < findings.getLength(); i++) { if (findings.item(i).equals(node)) { return true; } } return false; }
java
private NamespaceContext buildNamespaceContext(Node node) { SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext(); Map<String, String> namespaces = XMLUtils.lookupNamespaces(node.getOwnerDocument()); // add default namespace mappings namespaces.putAll(namespaceCon...
java
public Delete delete(String path) { Delete command = new Delete(); command.path(path); command.version(DEFAULT_VERSION); action.setCommand(command); return command; }
java
public GetData get(String path) { GetData command = new GetData(); command.path(path); action.setCommand(command); return command; }
java
public SetData set(String path, String data) { SetData command = new SetData(); command.path(path); command.data(data); command.version(0); action.setCommand(command); return command; }
java
public boolean handleRequest(MessageContext messageContext) throws WebServiceClientException { try { logRequest("Sending SOAP request", messageContext, false); } catch (SoapEnvelopeException e) { log.warn("Unable to write SOAP request to logger", e); } catch (TransformerE...
java
public boolean handleResponse(MessageContext messageContext) throws WebServiceClientException { try { logResponse("Received SOAP response", messageContext, true); } catch (SoapEnvelopeException e) { log.warn("Unable to write SOAP response to logger", e); } catch (Transfor...
java