Java Code Examples for com.consol.citrus.util.FileUtils

The following examples show how to use com.consol.citrus.util.FileUtils. These examples are extracted from open source projects. 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 Project: syndesis   Source File: WebHookToFtp_IT.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void doExecute(TestContext testContext) {
    Path publicUserDir = getFtpUserHome().resolve("public");
    Assert.assertTrue( "Missing ftp user home directory", publicUserDir.toFile().exists());

    File ftpUploadFile = publicUserDir.resolve(UPLOAD_FILENAME).toFile();
    Assert.assertTrue(String.format("Missing ftp upload file '%s'", UPLOAD_FILENAME), ftpUploadFile.exists());
    try {
        JsonTextMessageValidator validator = new JsonTextMessageValidator();
        validator.validateMessage(new DefaultMessage(FileUtils.readToString(ftpUploadFile)),
                                    new DefaultMessage("{\"message\" : \"${first_name},${company},${email}\"}"),
                                    testContext,
                                    new JsonMessageValidationContext());
    } catch (IOException e) {
        throw new CitrusRuntimeException(String.format("Failed to verify ftp upload file '%s'", UPLOAD_FILENAME), e);
    }
}
 
Example 2
Source Project: citrus-admin   Source File: Project.java    License: 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 3
Source Project: citrus-admin   Source File: TestCaseService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Lists all available Citrus test cases grouped in test packages.
 * @param project
 * @return
 */
public List<TestGroup> getTestPackages(Project project) {
    Map<String, TestGroup> testPackages = new LinkedHashMap<>();

    List<File> sourceFiles = FileUtils.findFiles(project.getJavaDirectory(), StringUtils.commaDelimitedListToSet(project.getSettings().getJavaFilePattern()));
    List<Test> tests = testProviders.parallelStream()
                                    .flatMap(provider -> provider.findTests(project, sourceFiles).stream())
                                    .collect(Collectors.toList());

    for (Test test : tests) {
        if (!testPackages.containsKey(test.getPackageName())) {
            TestGroup testPackage = new TestGroup();
            testPackage.setName(test.getPackageName());
            testPackages.put(test.getPackageName(), testPackage);
        }

        testPackages.get(test.getPackageName()).getTests().add(test);
    }

    return Arrays.asList(testPackages.values().toArray(new TestGroup[testPackages.size()]));
}
 
Example 4
Source Project: citrus-admin   Source File: TestCaseService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * List test names of latest, meaning newest or last modified tests in project.
 *
 * @param project
 * @return
 */
public List<TestGroup> getLatest(Project project, int limit) {
    Map<String, TestGroup> grouped = new LinkedHashMap<>();

    final List<File> sourceFiles = FileUtils.findFiles(project.getJavaDirectory(), StringUtils.commaDelimitedListToSet(project.getSettings().getJavaFilePattern()))
                                            .stream()
                                            .sorted((f1, f2) -> f1.lastModified() >= f2.lastModified() ? -1 : 1)
                                            .limit(limit)
                                            .collect(Collectors.toList());

    List<Test> tests = testProviders.parallelStream()
                                    .flatMap(provider -> provider.findTests(project, sourceFiles).stream())
                                    .collect(Collectors.toList());
    for (Test test : tests) {
        if (!grouped.containsKey(test.getClassName())) {
            TestGroup testGroup = new TestGroup();
            testGroup.setName(test.getClassName());
            grouped.put(test.getClassName(), testGroup);
        }

        grouped.get(test.getClassName()).getTests().add(test);
    }

    return Arrays.asList(grouped.values().toArray(new TestGroup[grouped.size()]));
}
 
Example 5
Source Project: citrus-admin   Source File: TestCaseService.java    License: 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 6
Source Project: citrus-admin   Source File: JUnit4TestReportLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Access file resource representing the TestNG results file.
 * @param activeProject
 * @return
 */
private Resource getTestResultsFile(Project activeProject) {
    FileSystemResource testSuiteFile = new FileSystemResource(activeProject.getProjectHome() + "/target/failsafe-reports/TEST-TestSuite.xml");
    if (testSuiteFile.exists()) {
        return testSuiteFile;
    }

    if (new File(activeProject.getProjectHome() + "/target/failsafe-reports").exists()) {
        List<File> testCaseFiles = FileUtils.findFiles(activeProject.getProjectHome() + "/target/failsafe-reports", Collections.singleton("/TEST-*.xml"));
        if (!CollectionUtils.isEmpty(testCaseFiles)) {
            return new FileSystemResource(testCaseFiles.get(0));
        }
    }

    return null;
}
 
Example 7
Source Project: citrus-admin   Source File: SpringBeanServiceTest.java    License: 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 Project: citrus-admin   Source File: SpringBeanServiceTest.java    License: 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 9
Source Project: citrus-admin   Source File: SpringBeanServiceTest.java    License: 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 10
Source Project: citrus-admin   Source File: SpringBeanServiceTest.java    License: 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 11
Source Project: citrus-admin   Source File: SpringBeanServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a temporary file in operating system and writes template content to file.
 * @param templateName
 * @return
 */
private File createTempContextFile(String templateName) throws IOException {
    FileWriter writer = null;
    File tempFile;

    try {
        tempFile = File.createTempFile(templateName, ".xml");

        writer = new FileWriter(tempFile);
        writer.write(FileUtils.readToString(new ClassPathResource(templateName + ".xml", SpringBeanService.class)));
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }

    return tempFile;
}
 
Example 12
Source Project: citrus-admin   Source File: TestActionServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddActionDefinition() throws Exception {
    EchoModel echo1 = new EchoModel();
    echo1.setMessage("echo1");
    EchoModel echo2 = new EchoModel();
    echo2.setMessage("echo2");

    SendModel sendModel = new SendModel();
    sendModel.setEndpoint("myEndpoint");

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

    testActionService.addTestAction(tempFile, project, 0, echo1);
    testActionService.addTestAction(tempFile, project, 0, echo2);
    testActionService.addTestAction(tempFile, project, 2, sendModel);

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

    Assert.assertTrue(result.contains("<sleep milliseconds=\"5000\">"), String.format("Failed to validate '%s'", result));
    Assert.assertTrue(result.contains("<message>echo1</message>"), String.format("Failed to validate '%s'", result));
    Assert.assertTrue(result.contains("<message>echo2</message>"), String.format("Failed to validate '%s'", result));
    Assert.assertTrue(result.contains("<send endpoint=\"myEndpoint\"/>"), String.format("Failed to validate '%s'", result));
}
 
Example 13
Source Project: citrus-admin   Source File: TestActionServiceTest.java    License: 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 14
Source Project: citrus-admin   Source File: TestActionServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a temporary file in operating system and writes template content to file.
 * @param templateName
 * @return
 */
private File createTempContextFile(String templateName) throws IOException {
    FileWriter writer = null;
    File tempFile;

    try {
        tempFile = File.createTempFile(templateName, ".xml");

        writer = new FileWriter(tempFile);
        writer.write(FileUtils.readToString(new ClassPathResource(templateName + ".xml", TestActionService.class)));
    } finally {
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    }

    return tempFile;
}
 
Example 15
Source Project: citrus-admin   Source File: ProjectServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testManageConnector() throws Exception {
    Project testProject = new Project(new ClassPathResource("projects/maven").getFile().getCanonicalPath());
    projectService.setActiveProject(testProject);

    Assert.assertFalse(FileUtils.readToString(new FileSystemResource(testProject.getMavenPomFile())).contains("citrus-admin-connector"));

    when(springBeanService.getBeanDefinition(any(File.class), eq(testProject), eq(WebSocketPushEventsListener.class.getSimpleName()), eq(SpringBean.class))).thenReturn(null);
    when(environment.getProperty("local.server.port", "8080")).thenReturn("8080");
    projectService.addConnector();

    Assert.assertTrue(FileUtils.readToString(new FileSystemResource(testProject.getMavenPomFile())).contains("citrus-admin-connector"));

    when(springBeanService.getBeanNames(any(File.class), eq(testProject), eq(WebSocketPushEventsListener.class.getName()))).thenReturn(Collections.singletonList(WebSocketPushEventsListener.class.getSimpleName()));
    projectService.removeConnector();

    Assert.assertFalse(FileUtils.readToString(new FileSystemResource(testProject.getMavenPomFile())).contains("citrus-admin-connector"));

    verify(springBeanService).addBeanDefinition(any(File.class), eq(testProject), any(SpringBean.class));
    verify(springBeanService).removeBeanDefinition(any(File.class), eq(testProject), eq(WebSocketPushEventsListener.class.getSimpleName()));
}
 
Example 16
Source Project: yaks   Source File: OpenApiResourceLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Loads the specification from a file resource. Either classpath or file system resource path is supported.
 * @param resource
 * @return
 */
public static OasDocument fromFile(String resource) {
    try {
        return (OasDocument) Library.readDocumentFromJSONString(FileUtils.readToString(FileUtils.getFileResource(resource)));
    } catch (IOException e) {
        throw new IllegalStateException("Failed to parse Open API specification: " + resource, e);
    }
}
 
Example 17
Source Project: syndesis   Source File: SendMail_IT.java    License: 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 18
Source Project: citrus-admin   Source File: ProjectService.java    License: 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 19
Source Project: citrus-admin   Source File: ProjectService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds module to project build configuration as dependency.
 * @param module
 */
public void add(Module module) {
    if (project.isMavenProject()) {
        try {
            String pomXml = FileUtils.readToString(new FileSystemResource(project.getMavenPomFile()));

            if (!pomXml.contains("<artifactId>citrus-" + module.getName() + "</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*$",
                        "^\\s*<dependency>[\\s\\n\\r]*<groupId>com\\.consol\\.citrus</groupId>[\\s\\n\\r]*<artifactId>citrus-core</artifactId>[\\s\\n\\r]*</dependency>\\s*$",
                        "^\\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*$",
                        "^\\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>\\s*$",
                };

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

                    if (matcher.find()) {
                        String version = project.getVersion();
                        if (matcher.groupCount() > 0) {
                            version = matcher.group(1);
                        }
                        pomXml = pomXml.substring(0, matcher.end()) + String.format("%n    <dependency>%n      <groupId>com.consol.citrus</groupId>%n      <artifactId>citrus-" + module.getName() + "</artifactId>%n      <version>" + version + "</version>%n    </dependency>") + pomXml.substring(matcher.end());
                        break;
                    }
                }

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

                FileUtils.writeToFile(pomXml, new FileSystemResource(project.getMavenPomFile()).getFile());
            }
        } catch (IOException e) {
            throw new ApplicationRuntimeException("Failed to add admin connector dependency to Maven pom.xml file", e);
        }
    }
}
 
Example 20
Source Project: citrus-admin   Source File: ProjectService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Removes module from project build configuration.
 * @param module
 */
public void remove(Module module) {
    if (project.isMavenProject()) {
        try {
            String pomXml = FileUtils.readToString(new FileSystemResource(project.getMavenPomFile()));

            pomXml = pomXml.replaceAll("\\s*<dependency>[\\s\\n\\r]*<groupId>com\\.consol\\.citrus</groupId>[\\s\\n\\r]*<artifactId>citrus-" + module.getName() + "</artifactId>[\\s\\n\\r]*<version>.*</version>[\\s\\n\\r]*</dependency>", "");
            pomXml = pomXml.replaceAll("\\s*<dependency>[\\s\\n\\r]*<groupId>com\\.consol\\.citrus</groupId>[\\s\\n\\r]*<artifactId>citrus-" + module.getName() + "</artifactId>[\\s\\n\\r]*</dependency>", "");

            FileUtils.writeToFile(pomXml, new FileSystemResource(project.getMavenPomFile()).getFile());
        } catch (IOException e) {
            throw new ApplicationRuntimeException("Failed to remove Citrus module dependency from Maven pom.xml file", e);
        }
    }
}
 
Example 21
Source Project: citrus-admin   Source File: TestCaseService.java    License: 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 22
Source Project: citrus-admin   Source File: TestNGTestReportLoader.java    License: 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 23
Source Project: citrus-admin   Source File: JUnit4TestReportLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads test results file content.
 * @return
 */
private String getTestResultsAsString(Project activeProject) {
    return Optional.ofNullable(getTestResultsFile(activeProject)).map(resultFile -> {
        try {
            return FileUtils.readToString(resultFile);
        } catch (IOException e) {
            log.error("Failed to access test results", e);
            return "";
        }
    }).orElse("");
}
 
Example 24
Source Project: citrus-admin   Source File: TestNGAnnotationTestProvider.java    License: 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("[^/\\*]\\[email protected]").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 25
Source Project: citrus-admin   Source File: CucumberJUnit4TestProvider.java    License: 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 26
Source Project: citrus-admin   Source File: SpringBeanServiceTest.java    License: 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 27
Source Project: citrus-admin   Source File: TestActionServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveActionDefinition() throws Exception {
    File tempFile = createTempContextFile("test-remove");

    testActionService.removeTestAction(tempFile, project, 1);
    testActionService.removeTestAction(tempFile, project, 2);

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

    Assert.assertTrue(result.contains("<sleep milliseconds=\"5000\">"), String.format("Failed to validate '%s'", result));
    Assert.assertTrue(result.contains("<message>Citrus rocks!</message>"), String.format("Failed to validate '%s'", result));
    Assert.assertFalse(result.contains("<message>Hello Citrus!</message>"), String.format("Failed to validate '%s'", result));
    Assert.assertFalse(result.contains("<message>GoodBye Citrus!</message>"), String.format("Failed to validate '%s'", result));
}
 
Example 28
Source Project: citrus-admin   Source File: TestActionServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateActionDefinition() throws Exception {
    File tempFile = createTempContextFile("test-update");

    EchoModel echo = new EchoModel();
    echo.setMessage("Citrus rocks!");

    testActionService.updateTestAction(tempFile, project, 1, echo);

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

    Assert.assertTrue(result.contains("<message>Citrus rocks!</message>"), String.format("Failed to validate '%s'", result));
    Assert.assertFalse(result.contains("<message>Hello Citrus!</message>"), String.format("Failed to validate '%s'", result));
    Assert.assertTrue(result.contains("<message>GoodBye Citrus!</message>"), String.format("Failed to validate '%s'", result));
}
 
Example 29
Source Project: citrus-simulator   Source File: HttpScenarioGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    try {
        Assert.notNull(swaggerResource,
                "Missing either swagger api system property setting or explicit swagger api resource for scenario auto generation");

        Swagger swagger = new SwaggerParser().parse(FileUtils.readToString(swaggerResource));

        for (Map.Entry<String, Path> path : swagger.getPaths().entrySet()) {
            for (Map.Entry<io.swagger.models.HttpMethod, Operation> operation : path.getValue().getOperationMap().entrySet()) {

                if (beanFactory instanceof BeanDefinitionRegistry) {
                    log.info("Register auto generated scenario as bean definition: " + operation.getValue().getOperationId());
                    BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(HttpOperationScenario.class)
                            .addConstructorArgValue((contextPath + (swagger.getBasePath() != null ? swagger.getBasePath() : "")) + path.getKey())
                            .addConstructorArgValue(HttpMethod.valueOf(operation.getKey().name()))
                            .addConstructorArgValue(operation.getValue())
                            .addConstructorArgValue(swagger.getDefinitions());

                    if (beanFactory.containsBeanDefinition("inboundJsonDataDictionary")) {
                        beanDefinitionBuilder.addPropertyReference("inboundDataDictionary", "inboundJsonDataDictionary");
                    }

                    if (beanFactory.containsBeanDefinition("outboundJsonDataDictionary")) {
                        beanDefinitionBuilder.addPropertyReference("outboundDataDictionary", "outboundJsonDataDictionary");
                    }

                    ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(operation.getValue().getOperationId(), beanDefinitionBuilder.getBeanDefinition());
                } else {
                    log.info("Register auto generated scenario as singleton: " + operation.getValue().getOperationId());
                    beanFactory.registerSingleton(operation.getValue().getOperationId(), createScenario((contextPath + (swagger.getBasePath() != null ? swagger.getBasePath() : "")) + path.getKey(), HttpMethod.valueOf(operation.getKey().name()), operation.getValue(), swagger.getDefinitions()));
                }
            }
        }
    } catch (IOException e) {
        throw new SimulatorException("Failed to read swagger api resource", e);
    }
}
 
Example 30
Source Project: citrus-admin   Source File: ProjectService.java    License: 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);
        }
    }
}