Java Code Examples for io.fabric8.utils.IOHelpers

The following examples show how to use io.fabric8.utils.IOHelpers. 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: fabric8-forge   Source File: CamelProjectHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean isCamelComponentArtifact(Dependency dependency) {
    try {
        // is it a JAR file
        File file = dependency.getArtifact().getUnderlyingResourceObject();
        if (file != null && file.getName().toLowerCase().endsWith(".jar")) {
            URL url = new URL("file:" + file.getAbsolutePath());
            URLClassLoader child = new URLClassLoader(new URL[]{url});

            // custom component
            InputStream is = child.getResourceAsStream("META-INF/services/org/apache/camel/component.properties");
            if (is != null) {
                IOHelpers.close(is);
                return true;
            }
        }
    } catch (Throwable e) {
        // ignore
    }

    return false;
}
 
Example 2
Source Project: ipaas-quickstarts   Source File: ArchetypeTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if we can find a system test Java file which uses the nice <code>isPodReadyForPeriod()</code>
 * assertions
 */
protected boolean hasGoodSystemTest(File file) {
    if (file.isFile()) {
        String name = file.getName();
        if (name.endsWith("KT.java")) {
            try {
                String text = IOHelpers.readFully(file);
                if (text.contains("isPodReadyForPeriod(")) {
                    LOG.info("Found good system test at " + file.getAbsolutePath() + " so not generating a new one for this archetype");
                    return true;
                }
            } catch (IOException e) {
                LOG.warn("Failed to load file " + file + ". " + e, e);
            }
        }
    }
    File[] files = file.listFiles();
    if (files != null) {
        for (File child : files) {
            if (hasGoodSystemTest(child)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 3
Source Project: updatebot   Source File: MarkupHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static void savePrettyJson(File file, Object value) throws IOException {
    // lets use the node layout
    NpmJsonPrettyPrinter printer = new NpmJsonPrettyPrinter();

    ObjectMapper objectMapper = createPrettyJsonObjectMapper();
    objectMapper.setDefaultPrettyPrinter(printer);
    String json = objectMapper.writer().writeValueAsString(value);

    IOHelpers.writeFully(file, json + System.lineSeparator());
}
 
Example 4
Source Project: updatebot   Source File: ProcessHelper.java    License: Apache License 2.0 5 votes vote down vote up
protected static String loadFile(File file) {
    String output = null;
    if (Files.isFile(file)) {
        try {
            output = IOHelpers.readFully(file);
        } catch (IOException e) {
            LOG.error("Failed to load " + file + ". " + e, e);
        }
    }
    return output;
}
 
Example 5
Source Project: updatebot   Source File: PomUpdateStatus.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Saves the pom.xml if its been changed
 *
 * @return true if the pom was modified
 * @throws IOException
 */
public boolean saveIfChanged() throws IOException {
    if (updated) {
        LOG.info("Updating " + pom);
        try {
            IOHelpers.writeFully(pom, doc.toXML());
        } catch (Exception e) {
            throw new IOException("failed to save " + pom + ". " + e, e);
        }
    }
    return updated;
}
 
Example 6
Source Project: updatebot   Source File: PluginsUpdater.java    License: Apache License 2.0 5 votes vote down vote up
private boolean updateVersionsInFile(CommandContext context, File file, PluginsDependencies plugins, List<DependencyVersionChange> changes) throws IOException {
    LOG.info("Processing file " + file);
    List<String> lines = IOHelpers.readLines(file);
    List<String> answer = new ArrayList<>(lines.size());

    Map<String, String> versionMap = new HashMap<>();
    for (DependencyVersionChange change : changes) {
        versionMap.put(change.getDependency(), change.getVersion());
    }

    boolean changed = false;
    for (String line : lines) {
        int idx = line.indexOf(PLUGINS_SEPARATOR);
        if (idx < 0) {
            answer.add(line);
            continue;
        }
        String artifactId = line.substring(0, idx);
        String newVersion = versionMap.get(PLUGIN_DEPENDENCY_PREFIX + artifactId);
        if (newVersion == null) {
            answer.add(line);
            continue;
        } else {
            answer.add(artifactId + PLUGINS_SEPARATOR + newVersion);
            changed = true;
        }
    }
    if (changed) {
        IOHelpers.writeLines(file, answer);
    }
    return changed;
}
 
Example 7
Source Project: fabric8-forge   Source File: RepositoryResource.java    License: Apache License 2.0 5 votes vote down vote up
protected Response doUploadFile(final String path, String message, final InputStream body) throws Exception {
    this.message = message;
    final File file = getRelativeFile(path);

    boolean exists = file.exists();
    if (LOG.isDebugEnabled()) {
        LOG.debug("writing file: " + file.getPath());
    }
    file.getParentFile().mkdirs();
    IOHelpers.writeTo(file, body);
    String status = exists ? "updated" : "created";
    return Response.ok(new StatusDTO(path, status)).build();
}
 
Example 8
Source Project: fabric8-forge   Source File: RootResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.TEXT_HTML)
public String index() throws IOException {
    URL resource = getClass().getResource("index.html");
    if (resource != null) {
        InputStream in = resource.openStream();
        if (in != null) {
            return IOHelpers.readFully(in);
        }
    }
    return null;
}
 
Example 9
Source Project: fabric8-forge   Source File: DevOpsSave.java    License: Apache License 2.0 5 votes vote down vote up
private static String getFlowContent(String flow, UIContext context) {
    File dir = getJenkinsWorkflowFolder(context);
    if (dir != null) {
        File file = new File(dir, flow);
        if (file.isFile() && file.exists()) {
            try {
                return IOHelpers.readFully(file);
            } catch (IOException e) {
                LOG.warn("Failed to load local pipeline " + file + ". " + e, e);
            }
        }
    }
    return null;
}
 
Example 10
private void runProcess(String commands, boolean verbose) throws IOException {
    ProcessBuilder builder = new ProcessBuilder("bash", "-c", commands);
    Process process = builder.start();

    String out = IOHelpers.readFully(process.getInputStream());
    String err = IOHelpers.readFully(process.getErrorStream());
    if (verbose) {
        listener.getLogger().println("command: " + commands + " out: " + out);
        listener.getLogger().println("command: " + commands + " err: " + err);
    }
}
 
Example 11
Source Project: ipaas-quickstarts   Source File: ArchetypeHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Extracts properties declared in "META-INF/maven/archetype-metadata.xml" file
 */
protected void parseReplaceProperties(InputStream zip, Map<String, String> replaceProperties) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOHelpers.copy(zip, bos);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();

    InputSource inputSource = new InputSource(new ByteArrayInputStream(bos.toByteArray()));
    Document document = db.parse(inputSource);

    XPath xpath = XPathFactory.newInstance().newXPath();
    SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
    nsContext.registerMapping("ad", archetypeDescriptorUri);
    xpath.setNamespaceContext(nsContext);

    NodeList properties = (NodeList) xpath.evaluate(requiredPropertyXPath, document, XPathConstants.NODESET);

    for (int p = 0; p < properties.getLength(); p++) {
        Element requiredProperty = (Element) properties.item(p);

        String key = requiredProperty.getAttribute("key");
        NodeList children = requiredProperty.getElementsByTagNameNS(archetypeDescriptorUri, "defaultValue");
        String value = "";
        if (children.getLength() == 1 && children.item(0).hasChildNodes()) {
            value = children.item(0).getTextContent();
        } else {
            if ("name".equals(key) && value.isEmpty()) {
                value = "HelloWorld";
            }
        }
        replaceProperties.put(key, value);
    }
}
 
Example 12
Source Project: ipaas-quickstarts   Source File: CatalogBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts generation of Archetype Catalog (see: http://maven.apache.org/xsd/archetype-catalog-1.0.0.xsd)
 *
 * @throws IOException
 */
public void configure() throws IOException {
    if (archetypesPomFile != null) {
        archetypesPomArtifactIds = loadArchetypesPomArtifactIds(archetypesPomFile);
    }
    catalogXmlFile.getParentFile().mkdirs();
    LOG.info("Writing catalog: " + catalogXmlFile);
    printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(catalogXmlFile), "UTF-8"));

    printWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<archetype-catalog xmlns=\"http://maven.apache.org/plugins/maven-archetype-plugin/archetype-catalog/1.0.0\"\n" +
        indent + indent + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
        indent + indent + "xsi:schemaLocation=\"http://maven.apache.org/plugins/maven-archetype-plugin/archetype-catalog/1.0.0 http://maven.apache.org/xsd/archetype-catalog-1.0.0.xsd\">\n" +
        indent + "<archetypes>");

    if (bomFile != null && bomFile.exists()) {
        // read all properties of the bom, so we have default values for ${ } placeholders
        String text = IOHelpers.readFully(bomFile);
        Document doc = archetypeUtils.parseXml(new InputSource(new StringReader(text)));
        Element root = doc.getDocumentElement();

        // lets load all the properties defined in the <properties> element in the bom pom.
        NodeList propertyElements = root.getElementsByTagName("properties");
        if (propertyElements.getLength() > 0)  {
            Element propertyElement = (Element) propertyElements.item(0);
            NodeList children = propertyElement.getChildNodes();
            for (int cn = 0; cn < children.getLength(); cn++) {
                Node e = children.item(cn);
                if (e instanceof Element) {
                    versionProperties.put(e.getNodeName(), e.getTextContent());
                }
            }
        }
        if (LOG.isDebugEnabled()) {
            for (Map.Entry<String, String> entry : versionProperties.entrySet()) {
                LOG.debug("bom property: {}={}", entry.getKey(), entry.getValue());
            }
        }
    }
}
 
Example 13
Source Project: fabric8-forge   Source File: ForgeTestSupport.java    License: Apache License 2.0 4 votes vote down vote up
protected Build assertCodeChangeTriggersWorkingBuild(final String projectName, Build firstBuild) throws Exception {
    File cloneDir = new File(getBasedir(), "target/projects/" + projectName);

    String gitUrl = asserGetAppGitCloneURL(forgeClient, projectName);
    Git git = ForgeClientAsserts.assertGitCloneRepo(gitUrl, cloneDir);

    // lets make a dummy commit...
    File readme = new File(cloneDir, "ReadMe.md");
    boolean mustAdd = false;
    String text = "";
    if (readme.exists()) {
        text = IOHelpers.readFully(readme);
    } else {
        mustAdd = true;
    }
    text += "\nupdated at: " + new Date();
    Files.writeToFile(readme, text, Charset.defaultCharset());

    if (mustAdd) {
        AddCommand add = git.add().addFilepattern("*").addFilepattern(".");
        add.call();
    }


    LOG.info("Committing change to " + readme);

    CommitCommand commit = git.commit().setAll(true).setAuthor(forgeClient.getPersonIdent()).setMessage("dummy commit to trigger a rebuild");
    commit.call();
    PushCommand command = git.push();
    command.setCredentialsProvider(forgeClient.createCredentialsProvider());
    command.setRemote("origin").call();

    LOG.info("Git pushed change to " + readme);

    // now lets wait for the next build to start
    int nextBuildNumber = firstBuild.getNumber() + 1;


    Asserts.assertWaitFor(10 * 60 * 1000, new Block() {
        @Override
        public void invoke() throws Exception {
            JobWithDetails job = assertJob(projectName);
            Build lastBuild = job.getLastBuild();
            assertThat(lastBuild.getNumber()).describedAs("Waiting for latest build for job " + projectName + " to start").isGreaterThanOrEqualTo(nextBuildNumber);
        }
    });

    return ForgeClientAsserts.assertBuildCompletes(forgeClient, projectName);
}
 
Example 14
Source Project: ipaas-quickstarts   Source File: ArchetypeTest.java    License: Apache License 2.0 4 votes vote down vote up
private void assertArchetypeCreated(String artifactId, String groupId, String version, File archetypejar) throws Exception {
    artifactId = Strings.stripSuffix(artifactId, "-archetype");
    artifactId = Strings.stripSuffix(artifactId, "-example");
    File outDir = new File(projectsOutputFolder, artifactId);

    LOG.info("Creating Archetype " + groupId + ":" + artifactId + ":" + version);
    Map<String, String> properties = new ArchetypeHelper(archetypejar, outDir, groupId, artifactId, version, null, null).parseProperties();
    LOG.info("Has preferred properties: " + properties);

    ArchetypeHelper helper = new ArchetypeHelper(archetypejar, outDir, groupId, artifactId, version, null, null);
    helper.setPackageName(packageName);

    // lets override some properties
    HashMap<String, String> overrideProperties = new HashMap<String, String>();
    // for camel-archetype-component
    overrideProperties.put("scheme", "mycomponent");
    helper.setOverrideProperties(overrideProperties);

    // this is where the magic happens
    helper.execute();

    LOG.info("Generated archetype " + artifactId);

    // expected pom file
    File pom = new File(outDir, "pom.xml");

    // this archetype might not be a maven project
    if (!pom.isFile()) {
        return;
    }

    String pomText = Files.toString(pom);
    String badText = "${camel-";
    if (pomText.contains(badText)) {
        if (verbose) {
            LOG.info(pomText);
        }
        fail("" + pom + " contains " + badText);
    }

    // now lets ensure we have the necessary test dependencies...
    boolean updated = false;
    Document doc = XmlUtils.parseDoc(pom);
    boolean funktion = isFunktionProject(doc);
    LOG.debug("Funktion project: " + funktion);
    if (!funktion) {
        if (ensureMavenDependency(doc, "io.fabric8", "fabric8-arquillian", "test")) {
            updated = true;
        }
        if (ensureMavenDependency(doc, "org.jboss.arquillian.junit", "arquillian-junit-container", "test")) {
            updated = true;
        }
        if (ensureMavenDependency(doc, "org.jboss.shrinkwrap.resolver", "shrinkwrap-resolver-impl-maven", "test")) {
            updated = true;
        }
        if (ensureMavenDependencyBOM(doc, "io.fabric8", "fabric8-project-bom-with-platform-deps", fabric8Version)) {
            updated = true;
        }
    }
    if (ensureFailsafePlugin(doc)) {
        updated = true;
    }
    if (updated) {
        DomHelper.save(doc, pom);
    }


    // lets generate the system test
    if (!hasGoodSystemTest(new File(outDir, "src/test/java"))) {
        File systemTest = new File(outDir, "src/test/java/io/fabric8/systests/KubernetesIntegrationKT.java");
        systemTest.getParentFile().mkdirs();
        String javaFileName = "KubernetesIntegrationKT.java";
        URL javaUrl = getClass().getClassLoader().getResource(javaFileName);
        assertNotNull("Could not load resource on the classpath: " + javaFileName, javaUrl);
        IOHelpers.copy(javaUrl.openStream(), new FileOutputStream(systemTest));
    }

    outDirs.add(outDir.getPath());
}
 
Example 15
Source Project: updatebot   Source File: PluginsUpdaterTest.java    License: Apache License 2.0 3 votes vote down vote up
public void assertUpdatePackageJson(File packageJson, String dependencyKey, String artifactId, String version) throws IOException {
    List<DependencyVersionChange> changes = new ArrayList<>();
    changes.add(new DependencyVersionChange(Kind.MAVEN, PluginsUpdater.PLUGIN_DEPENDENCY_PREFIX + artifactId, version));
    updater.pushVersions(parentContext, changes);


    // lets assert that the file contains the correct line
    String expectedLine = artifactId + PluginsUpdater.PLUGINS_SEPARATOR + version;


    List<String> lines = IOHelpers.readLines(pluginsFile);
    assertThat(lines).describedAs("Should have updated the plugin " + artifactId + " to " + version).contains(expectedLine);
}