Java Code Examples for com.consol.citrus.util.FileUtils#readToString()

The following examples show how to use com.consol.citrus.util.FileUtils#readToString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Project.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
/**
 * Load settings from project info file.
 */
public void loadSettings() {
    try (FileInputStream fileInput = new FileInputStream(getProjectInfoFile())) {
        String projectInfo = FileUtils.readToString(fileInput);

        // support legacy build configuration
        projectInfo = projectInfo.replaceAll("com\\.consol\\.citrus\\.admin\\.model\\.build\\.maven\\.MavenBuildConfiguration", MavenBuildContext.class.getName());

        Project project = Jackson2ObjectMapperBuilder.json().build().readerFor(Project.class).readValue(projectInfo);

        setName(project.getName());
        setDescription(project.getDescription());
        setSettings(project.getSettings());
        setVersion(project.getVersion());
    } catch (IOException e) {
        throw new CitrusRuntimeException("Failed to read project settings file", e);
    }
}
 
Example 2
Source File: TestActionServiceTest.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddActionDefinitionNamespace() throws Exception {
    SendRequestModel sendRequestModel = new SendRequestModel();
    sendRequestModel.setClient("myClient");

    ClientRequestType getRequest = new ClientRequestType();
    getRequest.setBody(new ClientRequestType.Body());
    getRequest.getBody().setData("Hello");
    sendRequestModel.setGET(getRequest);

    File tempFile = createTempContextFile("test-add");

    testActionService.addTestAction(tempFile, project, 0, sendRequestModel);

    String result = FileUtils.readToString(new FileInputStream(tempFile));

    Assert.assertTrue(result.contains("<http:send-request client=\"myClient\">"), String.format("Failed to validate '%s'", result));
    Assert.assertTrue(result.contains("xmlns:http=\"http://www.citrusframework.org/schema/http/testcase\""), String.format("Failed to validate '%s'", result));
}
 
Example 3
Source File: SpringBeanServiceTest.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateBeanDefinition() throws Exception {
    File tempFile = createTempContextFile("citrus-context-update");

    SchemaModel helloSchema = new SchemaModelBuilder().withId("helloSchema").withLocation("newLocation").build();

    springBeanConfigService.updateBeanDefinition(tempFile, project, "helloSchema", helloSchema);

    String result = FileUtils.readToString(new FileInputStream(tempFile));

    Assert.assertTrue(result.contains("<citrus:schema id=\"helloSchema\" location=\"newLocation\"/>"), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<property name=\"helloSchema\" value=\"some\"/>"), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<!-- This is a comment -->"), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<![CDATA[" + System.lineSeparator() + "              some" + System.lineSeparator() + "            ]]>" + System.lineSeparator()), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<![CDATA[" + System.lineSeparator() + "              <some>" + System.lineSeparator() + "                <text>This is a CDATA text</text>" + System.lineSeparator()), "Failed to validate " + result);
}
 
Example 4
Source File: SpringBeanServiceTest.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveSpringBeanDefinitions() throws Exception {
    File tempFile = createTempContextFile("citrus-context-remove-bean");

    springBeanConfigService.removeBeanDefinitions(tempFile, project, SpringBean.class, "class", "com.consol.citrus.DeleteMe");

    String result = FileUtils.readToString(new FileInputStream(tempFile));

    Assert.assertTrue(result.contains("id=\"preserveMe\""), "Failed to validate " + result);
    Assert.assertTrue(result.contains("name=\"preserveMeName\""), "Failed to validate " + result);

    Assert.assertFalse(result.contains("<bean id=\"deleteMe\""), "Failed to validate " + result);
    Assert.assertFalse(result.contains("<bean name=\"deleteMeName\""), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<bean class=\"com.consol.citrus.SampleClass\""), "Failed to validate " + result);
    Assert.assertFalse(result.contains("<bean class=\"com.consol.citrus.DeleteMe\""), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<property name=\"class\" value=\"com.consol.citrus.DeleteMe\"/>"), "Failed to validate " + result);
}
 
Example 5
Source File: SpringBeanServiceTest.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveBeanDefinition() throws Exception {
    File tempFile = createTempContextFile("citrus-context-remove");

    springBeanConfigService.removeBeanDefinition(tempFile, project, "deleteMe");
    springBeanConfigService.removeBeanDefinition(tempFile, project, "deleteMeName");

    springBeanConfigService.removeBeanDefinition(tempFile, project, "helloSchema");

    String result = FileUtils.readToString(new FileInputStream(tempFile));

    Assert.assertTrue(result.contains("id=\"preserveMe\""), "Failed to validate " + result);
    Assert.assertTrue(result.contains("name=\"preserveMeName\""), "Failed to validate " + result);

    Assert.assertFalse(result.contains("<bean id=\"deleteMe\""), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<bean name=\"deleteMeName\""), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<property name=\"deleteMe\" value=\"some\"/>"), "Failed to validate " + result);
}
 
Example 6
Source File: TestCaseService.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
/**
 * Get total number of tests in project.
 * @param project
 * @return
 */
public long getTestCount(Project project) {
    long testCount = 0L;
    try {
        List<File> sourceFiles = FileUtils.findFiles(project.getJavaDirectory(), StringUtils.commaDelimitedListToSet(project.getSettings().getJavaFilePattern()));
        for (File sourceFile : sourceFiles) {
            String sourceCode = FileUtils.readToString(new FileSystemResource(sourceFile));

            testCount += StringUtils.countOccurrencesOf(sourceCode, "@CitrusTest");
            testCount += StringUtils.countOccurrencesOf(sourceCode, "@CitrusXmlTest");
        }
    } catch (IOException e) {
        log.warn("Failed to read Java source files - list of test cases for this project is incomplete", e);
    }

    return testCount;
}
 
Example 7
Source File: SpringBeanServiceTest.java    From citrus-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddBeanDefinition() throws Exception {
    SchemaModel xsdSchema1 = new SchemaModelBuilder().withId("1").withLocation("l1").build();
    SchemaModel xsdSchema2 = new SchemaModelBuilder().withId("2").withLocation("l2").build();

    SchemaRepositoryModel schemaRepository = new SchemaRepositoryModelBuilder().withId("x").addSchemaReference("1").addSchemaReference("2").build();

    SpringBean springBean = new SpringBean();
    springBean.setId("listener");
    springBean.setClazz(WebSocketPushEventsListener.class.getName());

    File tempFile = createTempContextFile("citrus-context-add");

    springBeanConfigService.addBeanDefinition(tempFile, project, xsdSchema1);
    springBeanConfigService.addBeanDefinition(tempFile, project, xsdSchema2);
    springBeanConfigService.addBeanDefinition(tempFile, project, schemaRepository);
    springBeanConfigService.addBeanDefinition(tempFile, project, springBean);

    String result = FileUtils.readToString(new FileInputStream(tempFile));

    Assert.assertTrue(result.contains("<citrus:schema id=\"1\" location=\"l1\"/>"), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<citrus:schema id=\"2\" location=\"l2\"/>"), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<citrus:schema-repository id=\"x\">"), "Failed to validate " + result);
    Assert.assertTrue(result.contains("<bean class=\"" + WebSocketPushEventsListener.class.getName() + "\" id=\"listener\"/>"), "Failed to validate " + result);
}
 
Example 8
Source File: CucumberJUnit4TestProvider.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Test> findTests(Project project, File sourceFile, String packageName, String className) {
    List<Test> tests = new ArrayList<>();

    try {
        String sourceCode = FileUtils.readToString(new FileSystemResource(sourceFile));
        Matcher matcher = Pattern.compile("@RunWith\\(Cucumber\\.class\\)").matcher(sourceCode);
        if (matcher.find()) {
            List<File> featureFiles = FileUtils.findFiles(project.getXmlDirectory() + packageName.replaceAll("\\.", File.separator), StringUtils.commaDelimitedListToSet("/**/*.feature"));

            for (File featureFile : featureFiles) {
                Test test = new Test();
                test.setType(TestType.CUCUMBER);
                test.setClassName(className);
                test.setPackageName(packageName);
                test.setMethodName(FilenameUtils.getBaseName(featureFile.getName()));

                test.setName(className + "." + test.getMethodName());

                tests.add(test);
            }
        }
    } catch (IOException e) {
        log.error("Failed to read test source file", e);
    }

    return tests;
}
 
Example 9
Source File: SpringBeanServiceTest.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddBeanDefinitionNamespace() throws Exception {
    JmsEndpointModel jmsEndpoint = new JmsEndpointModel();
    jmsEndpoint.setId("jmsEndpoint");
    jmsEndpoint.setDestinationName("jms.inbound.queue");

    File tempFile = createTempContextFile("citrus-context-add");

    springBeanConfigService.addBeanDefinition(tempFile, project, jmsEndpoint);

    String result = FileUtils.readToString(new FileInputStream(tempFile));

    Assert.assertTrue(result.contains("<citrus-jms:endpoint id=\"jmsEndpoint\" destination-name=\"jms.inbound.queue\"/>"), "Failed to validate " + result);
    Assert.assertTrue(result.contains("xmlns:citrus-jms=\"http://www.citrusframework.org/schema/jms/config\""), "Failed to validate " + result);
}
 
Example 10
Source File: SendMail_IT.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
@CitrusTest
public void testSendMail(@CitrusResource TestCaseRunner runner) throws IOException {
    cleanupDatabase(runner);

    runner.variable("first_name", "John");
    runner.variable("company", "Red Hat");
    runner.variable("email", "[email protected]");

    runner.given(http().client(webHookClient)
            .send()
            .post()
            .fork(true)
            .payload(getWebhookPayload()));

    String mailBody = FileUtils.readToString(new ClassPathResource("mail.txt", SendMail_IT.class));
    runner.when(receive().endpoint(mailServer)
                    .message(MailMessage.request()
                            .from("[email protected]")
                            .to("${email}")
                            .cc("")
                            .bcc("")
                            .subject("Welcome!")
                            .body(mailBody, "text/plain; charset=UTF-8")));

    runner.then(send().endpoint(mailServer)
                    .message(MailMessage.response(250, "OK")));

    runner.then(http().client(webHookClient)
            .receive()
            .response(HttpStatus.NO_CONTENT));

    verifyRecordsInDb(runner, 1, "New hire for ${first_name} from ${company}");
}
 
Example 11
Source File: TestNGAnnotationTestProvider.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Test> findTests(Project project, File sourceFile, String packageName, String className) {
    List<Test> tests = new ArrayList<>();

    try {
        String sourceCode = FileUtils.readToString(new FileSystemResource(sourceFile));

        Matcher matcher = Pattern.compile("[^/\\*]\\s@Test").matcher(sourceCode);
        while (matcher.find()) {
            String snippet = StringUtils.trimAllWhitespace(sourceCode.substring(matcher.start()));
            snippet = snippet.substring(0, snippet.indexOf("){"));

            if (snippet.contains(" class ") || snippet.contains("@CitrusTest") || snippet.contains("@CitrusXmlTest")) {
                continue;
            }

            Test test = new Test();
            test.setType(TestType.JAVA);
            test.setClassName(className);
            test.setPackageName(packageName);

            String methodName = snippet.substring(snippet.indexOf("publicvoid") + 10);
            methodName = methodName.substring(0, methodName.indexOf("("));
            test.setMethodName(methodName);
            test.setName(className + "." + methodName);
            tests.add(test);
        }
    } catch (IOException e) {
        log.error("Failed to read test source file", e);
    }

    return tests;
}
 
Example 12
Source File: TestNGTestReportLoader.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
/**
 * Reads test results file content.
 * @return
 * @throws IOException
 */
private String getTestResultsAsString(Project activeProject) throws IOException {
    Resource fileResource = getTestResultsFile(activeProject);
    try (InputStream fileIn = fileResource.getInputStream()) {
        return FileUtils.readToString(fileIn);
    }
}
 
Example 13
Source File: TestCaseService.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the source code for the given test.
 * @param filePath
 * @return
 */
public String getSourceCode(Project project, String filePath) {
    try {
        String sourcePath = project.getAbsolutePath(filePath);
        if (new File(sourcePath).exists()) {
            return FileUtils.readToString(new FileInputStream(sourcePath));
        } else {
            throw new ApplicationRuntimeException("Unable to find source code for path: " + sourcePath);
        }
    } catch (IOException e) {
        throw new ApplicationRuntimeException("Failed to load test case source code", e);
    }
}
 
Example 14
Source File: ProjectService.java    From citrus-admin with Apache License 2.0 5 votes vote down vote up
/**
 * Get the Citrus modules for this project based on the build dependencies.
 * @return
 */
public List<Module> getModules() {
    List<Module> modules = new ArrayList<>();
    Collection<String> allModules = new SpringBeanNamespacePrefixMapper().getNamespaceMappings().values();

    if (project.isMavenProject()) {
        try {
            String pomXml = FileUtils.readToString(new FileSystemResource(project.getMavenPomFile()));
            SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
            nsContext.bindNamespaceUri("mvn", "http://maven.apache.org/POM/4.0.0");

            Document pomDoc = XMLUtils.parseMessagePayload(pomXml);

            NodeList dependencies = XPathUtils.evaluateAsNodeList(pomDoc, "/mvn:project/mvn:dependencies/mvn:dependency/mvn:artifactId[starts-with(., 'citrus-')]", nsContext);

            for (int i = 0; i < dependencies.getLength(); i++) {
                String moduleName = DomUtils.getTextValue((Element) dependencies.item(i));

                if (moduleName.equals("citrus-core")) {
                    allModules.remove("citrus");
                } else {
                    allModules.remove(moduleName);
                }

                modules.add(new Module(moduleName.substring("citrus-".length()), project.getVersion(), true));
            }
        } catch (IOException e) {
            throw new ApplicationRuntimeException("Unable to open Maven pom.xml file", e);
        }
    }

    allModules.stream()
            .filter(name -> !name.equals("citrus-test"))
            .map(name -> name.equals("citrus") ? "citrus-core" : name)
            .map(name -> new Module(name.substring("citrus-".length()), project.getVersion(), false))
            .forEach(modules::add);

    return modules;
}
 
Example 15
Source File: SpringJavaConfigServiceTest.java    From citrus-admin with Apache License 2.0 4 votes vote down vote up
@Test
public void testAddJavaConfig() throws Exception {
    SchemaModel xsdSchema1 = new SchemaModelBuilder().withId("xsdSchema1").withLocation("path/to/schema1.xsd").build();
    SchemaModel xsdSchema2 = new SchemaModelBuilder().withId("xsdSchema2").withLocation("path/to/schema2.xsd").build();

    SchemaRepositoryModel schemaRepository = new SchemaRepositoryModelBuilder()
            .withId("schemaRepository")
            .addSchema(xsdSchema1)
            .addSchema(xsdSchema2).build();

    JmsEndpointModel endpoint = new JmsEndpointModel();
    endpoint.setId("jmsEndpoint");
    endpoint.setDestinationName("jms.inbound.queue");

    File configFile = new ClassPathResource("config/AddBeanJavaConfig.java").getFile();

    springJavaConfigService.addBeanDefinition(configFile, project, xsdSchema1);
    springJavaConfigService.addBeanDefinition(configFile, project, xsdSchema2);
    springJavaConfigService.addBeanDefinition(configFile, project, schemaRepository);
    springJavaConfigService.addBeanDefinition(configFile, project, endpoint);

    String result = FileUtils.readToString(new FileInputStream(configFile));

    System.out.println(result);

    Assert.assertTrue(result.contains("import com.consol.citrus.dsl.endpoint.CitrusEndpoints;"));
    Assert.assertTrue(result.contains("import com.consol.citrus.xml.XsdSchemaRepository;"));
    Assert.assertTrue(result.contains("import org.springframework.core.io.ClassPathResource;"));
    Assert.assertTrue(result.contains("import org.springframework.xml.xsd.SimpleXsdSchema;"));
    Assert.assertTrue(result.contains("import com.consol.citrus.jms.endpoint.JmsEndpoint;"));
    Assert.assertTrue(result.contains("import com.consol.citrus.http.client.HttpClient;"));

    Assert.assertTrue(result.contains("public HttpClient httpClient() {"));
    Assert.assertTrue(result.contains("public JmsEndpoint jmsEndpoint() {"));
    Assert.assertTrue(result.contains("return CitrusEndpoints.jms().asynchronous()"));
    Assert.assertTrue(result.contains(".destination(\"jms.inbound.queue\")"));
    Assert.assertTrue(result.contains("public XsdSchemaRepository schemaRepository() {"));
    Assert.assertTrue(result.contains("public SimpleXsdSchema xsdSchema1() {"));
    Assert.assertTrue(result.contains("xsdSchema1.setXsd(new ClassPathResource(\"path/to/schema1.xsd\"));"));
    Assert.assertTrue(result.contains("public SimpleXsdSchema xsdSchema2() {"));
    Assert.assertTrue(result.contains("xsdSchema2.setXsd(new ClassPathResource(\"path/to/schema2.xsd\"));"));
}
 
Example 16
Source File: ProjectService.java    From citrus-admin with Apache License 2.0 4 votes vote down vote up
/**
 * Adds the citrus admin connector dependency to the target project Maven POM.
 */
public void addConnector() {
    if (project.isMavenProject()) {
        try {
            String pomXml = FileUtils.readToString(new FileSystemResource(project.getMavenPomFile()));
                                                                                  
            if (!pomXml.contains("<artifactId>citrus-admin-connector</artifactId>")) {
                String[] patterns = new String[] {
                        "\\s*<dependency>[\\s\\n\\r]*<groupId>com\\.consol\\.citrus</groupId>[\\s\\n\\r]*<artifactId>citrus-core</artifactId>[\\s\\n\\r]*<version>.*</version>[\\s\\n\\r]*</dependency>",
                        "\\s*<dependency>[\\s\\n\\r]*<groupId>com\\.consol\\.citrus</groupId>[\\s\\n\\r]*<artifactId>citrus-core</artifactId>[\\s\\n\\r]*</dependency>",
                        "\\s*<dependency>[\\s\\n\\r]*<groupId>com\\.consol\\.citrus</groupId>[\\s\\n\\r]*<artifactId>citrus-core</artifactId>[\\s\\n\\r]*<version>.*</version>[\\s\\n\\r]*<scope>.*</scope>[\\s\\n\\r]*</dependency>",
                        "\\s*<dependency>[\\s\\n\\r]*<groupId>com\\.consol\\.citrus</groupId>[\\s\\n\\r]*<artifactId>citrus-core</artifactId>[\\s\\n\\r]*<scope>.*</scope>[\\s\\n\\r]*</dependency>",
                };

                for (String pattern : patterns) {
                    Matcher matcher = Pattern.compile(pattern).matcher(pomXml);

                    if (matcher.find()) {
                        pomXml = pomXml.substring(0, matcher.end()) + String.format("%n    <dependency>%n      <groupId>com.consol.citrus</groupId>%n      <artifactId>citrus-admin-connector</artifactId>%n      <version>1.0.3</version>%n    </dependency>") + pomXml.substring(matcher.end());
                        break;
                    }
                }

                if (!pomXml.contains("<artifactId>citrus-admin-connector</artifactId>")) {
                    throw new ApplicationRuntimeException("Failed to add admin connector dependency to Maven pom.xml file - please add manually");
                }

                FileUtils.writeToFile(pomXml, new FileSystemResource(project.getMavenPomFile()).getFile());
            }

            project.getSettings().setUseConnector(true);
            project.getSettings().setConnectorActive(true);
            saveProjectInfo(project);

            SpringBean bean = new SpringBean();
            bean.setId(WebSocketPushEventsListener.class.getSimpleName());
            bean.setClazz(WebSocketPushEventsListener.class.getName());

            if (!environment.getProperty("local.server.port", "8080").equals("8080")) {
                Property portProperty = new Property();
                portProperty.setName("port");
                portProperty.setValue(environment.getProperty("local.server.port"));
                bean.getProperties().add(portProperty);
            }

            if (hasSpringXmlApplicationContext() && springBeanService.getBeanDefinition(getSpringXmlApplicationContextFile(), project, WebSocketPushEventsListener.class.getSimpleName(), SpringBean.class) == null) {
                springBeanService.addBeanDefinition(getSpringXmlApplicationContextFile(), project, bean);
            } else if (hasSpringJavaConfig() && springJavaConfigService.getBeanDefinition(project.getSpringJavaConfig(), project, WebSocketPushEventsListener.class.getSimpleName(), WebSocketPushEventsListener.class) == null) {
                springJavaConfigService.addBeanDefinition(getSpringJavaConfigFile(), project, bean);
            }
        } catch (IOException e) {
            throw new ApplicationRuntimeException("Failed to add admin connector dependency to Maven pom.xml file", e);
        }
    }
}
 
Example 17
Source File: InterceptorHttp.java    From citrus-simulator with Apache License 2.0 4 votes vote down vote up
private String getRequestContent(HttpServletRequest request) throws IOException {
    return FileUtils.readToString(request.getInputStream());
}
 
Example 18
Source File: TemplateHelper.java    From citrus-simulator with Apache License 2.0 3 votes vote down vote up
/**
 * Locates a message template using the supplied {@code templatePath} returning the contents as a string. Uses given
 * file extension.
 *
 * @param templatePath      the message template name.
 * @param templateExtension template file extension.
 * @return the contents as a string
 */
public String getMessageTemplate(String templatePath, String templateExtension) {
    try {
        return FileUtils.readToString(this.getFileResource(templatePath, templateExtension), charset);
    } catch (IOException e) {
        throw new CitrusRuntimeException(String.format("Error reading template: %s", templatePath), e);
    }
}