org.jboss.forge.addon.resource.FileResource Java Examples

The following examples show how to use org.jboss.forge.addon.resource.FileResource. 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: ConfigureEndpointPropertiesStep.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
private Result editEndpointXml(List<String> lines, String lineNumber, String endpointUrl, String uri, FileResource file, String xml) {
    // the list is 0-based, and line number is 1-based
    int idx = Integer.valueOf(lineNumber) - 1;
    String line = lines.get(idx);

    // replace uri with new value
    line = StringHelper.replaceAll(line, endpointUrl, uri);
    lines.set(idx, line);

    LOG.info("Updating " + endpointUrl + " to " + uri + " at line " + lineNumber + " in file " + xml);

    // and save the file back
    String content = LineNumberHelper.linesToString(lines);
    file.setContents(content);

    return Results.success("Update endpoint uri: " + uri + " in file " + xml);
}
 
Example #2
Source File: ConfigureEipPropertiesStep.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected int calculateIndent(FileResource file, String lineNumber) throws Exception {
    List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());

    int idx = Integer.valueOf(lineNumber);

    int spaces = LineNumberHelper.leadingSpaces(lines, idx - 1);
    int spaces1 = LineNumberHelper.leadingSpaces(lines, idx);
    int spaces2 = LineNumberHelper.leadingSpaces(lines, idx + 1);

    int delta = Math.abs(spaces1 - spaces);
    int delta2 = Math.abs(spaces2 - spaces1);

    int answer = delta2 > 0 ? delta2 : delta;
    // the indent must minimum be 2 spaces
    return Math.max(answer, 2);
}
 
Example #3
Source File: ConfigureEndpointPropertiesStep.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected Result editEndpointOther(Project project, ResourcesFacet facet, FileResource file, String uri, String endpointUrl,
                                  String currentFile, String lineNumber) throws Exception {

    List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());

    // the list is 0-based, and line number is 1-based
    int idx = Integer.valueOf(lineNumber) - 1;
    String line = lines.get(idx);

    // replace uri with new value
    line = StringHelper.replaceAll(line, endpointUrl, uri);
    lines.set(idx, line);

    LOG.info("Updating " + endpointUrl + " to " + uri + " at line " + lineNumber + " in file " + currentFile);

    // and save the file back
    String content = LineNumberHelper.linesToString(lines);
    file.setContents(content);

    return Results.success("Update endpoint uri: " + uri + " in file " + currentFile);
}
 
Example #4
Source File: AbstractCamelProjectCommand.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected FileResource getXmlResourceFile(Project project, String xmlResourceName) {
    if (xmlResourceName == null) {
        return null;
    }

    ResourcesFacet facet = null;
    WebResourcesFacet webResourcesFacet = null;
    if (project.hasFacet(ResourcesFacet.class)) {
        facet = project.getFacet(ResourcesFacet.class);
    }
    if (project.hasFacet(WebResourcesFacet.class)) {
        webResourcesFacet = project.getFacet(WebResourcesFacet.class);
    }

    FileResource file = facet != null ? facet.getResource(xmlResourceName) : null;
    if (file == null || !file.exists()) {
        file = webResourcesFacet != null ? webResourcesFacet.getWebResource(xmlResourceName) : null;
    }
    return file;
}
 
Example #5
Source File: EditNodeXmlStep.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
protected Result editModelXml(String pattern, List<String> lines, String lineNumber, String lineNumberEnd, String modelXml, FileResource file, String xml) throws Exception {
    // the list is 0-based, and line number is 1-based
    int idx = Integer.valueOf(lineNumber) - 1;
    int idx2 = Integer.valueOf(lineNumberEnd) - 1;
    int delta = (idx2 - idx) + 1;

    // use the same indent from the eip we are replacing
    int spaces = LineNumberHelper.leadingSpaces(lines, idx);

    // remove the old lines
    while (delta > 0) {
        delta--;
        lines.remove(idx);
    }

    LOG.info("Spaces " + spaces);

    String[] editLines = modelXml.split("\n");
    for (String line : editLines) {
        // use the same indent from the eip we are replacing
        line = LineNumberHelper.padString(line, spaces);
        // add the new line at the old starting position
        lines.add(idx, line);
        idx++;
    }

    // and save the file back
    String content = LineNumberHelper.linesToString(lines);
    file.setContents(content);
    return Results.success("Edited: " + modelXml);
}
 
Example #6
Source File: RulesetsUpdater.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
public void extractArtifact(Coordinate artifactCoords, File targetDir) throws IOException, DependencyException
{
    final DependencyQueryBuilder query = DependencyQueryBuilder.create(artifactCoords);
    Dependency dependency = depsResolver.resolveArtifact(query);
    FileResource<?> artifact = dependency.getArtifact();
    ZipUtil.unzipToFolder(new File(artifact.getFullyQualifiedName()), targetDir);
}
 
Example #7
Source File: AddNodeXmlStep.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
protected Result addModelXml(String pattern, List<String> lines, String lineNumber, String lineNumberEnd, String modelXml, FileResource file, String xml) throws Exception {

    // the list is 0-based, and line number is 1-based
    int idx = Integer.valueOf(lineNumberEnd);
    if ("route".equals(pattern)) {
        // we want to add at the end of the existing route, not after the route
        idx = idx - 1;
    }

    // use the same indent from the parent line
    int spaces = LineNumberHelper.leadingSpaces(lines, idx - 1);

    LOG.info("Spaces " + spaces);

    String[] editLines = modelXml.split("\n");
    for (String line : editLines) {
        // use the same indent from the eip we are replacing
        line = LineNumberHelper.padString(line, spaces);
        // add the new line at the old starting position
        lines.add(idx, line);
        idx++;
    }

    // and save the file back
    String content = LineNumberHelper.linesToString(lines);
    file.setContents(content);
    return Results.success("Added: " + modelXml);
}
 
Example #8
Source File: ConfigureEipPropertiesStep.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected Result addOrEditModelXml(FileResource file, String pattern, String modelXml, String xml, String lineNumber, String lineNumberEnd, String mode) throws Exception {
    List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());
    if ("add".equals(mode)) {
        return addModelXml(pattern, lines, lineNumber, lineNumberEnd, modelXml, file, xml);
    } else {
        return editModelXml(pattern, lines, lineNumber, lineNumberEnd, modelXml, file, xml);
    }
}
 
Example #9
Source File: EditFromOrToEndpointXmlStep.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
protected Result addOrEditEndpointXml(FileResource file, String uri, String endpointUrl, String endpointInstanceName, String xml, String lineNumber, String lineNumberEnd) throws Exception {
    String key = parentNode.getKey();
    if (Strings.isNullOrBlank(key)) {
        return Results.fail("Parent node has no key! " + parentNode + " in file " + file.getName());
    }

    Document root = XmlLineNumberParser.parseXml(file.getResourceInputStream());
    if (root != null) {
        Node selectedNode = CamelXmlHelper.findCamelNodeInDocument(root, key);
        if (selectedNode != null) {

            // we need to add after the parent node, so use line number information from the parent
            lineNumber = (String) selectedNode.getUserData(XmlLineNumberParser.LINE_NUMBER);
            lineNumberEnd = (String) selectedNode.getUserData(XmlLineNumberParser.LINE_NUMBER_END);

            if (lineNumber != null && lineNumberEnd != null) {

                // read all the lines
                List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());

                // the list is 0-based, and line number is 1-based
                int idx = Integer.valueOf(lineNumber) - 1;
                String line = lines.get(idx);

                // replace uri with new value
                line = StringHelper.replaceAll(line, endpointUrl, uri);
                lines.set(idx, line);

                // and save the file back
                String content = LineNumberHelper.linesToString(lines);
                file.setContents(content);
                return Results.success("Updated: " + line.trim());
            }
        }
        return Results.fail("Cannot find Camel node in XML file: " + key);
    } else {
        return Results.fail("Cannot load Camel XML file: " + file.getName());
    }
}
 
Example #10
Source File: CurrentLineCompleter.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected String getCurrentCursorLineText() throws Exception {
    if (relativeFile != null) {
        LOG.info("Loading relative file: " + relativeFile + " using java source facet: " + sourceFacet);
        FileResource file = sourceFacet != null ? sourceFacet.getJavaResource(relativeFile) : null;
        if (file == null || !file.exists()) {
            LOG.info("Loading relative file: " + relativeFile + " using resource facet: " + resourcesFacet);
            file = resourcesFacet != null ? resourcesFacet.getResource(relativeFile) : null;
        }
        if (file == null || !file.exists()) {
            LOG.info("Loading relative file: " + relativeFile + " using web facet: " + webFacet);
            file = webFacet != null ? webFacet.getWebResource(relativeFile) : null;
        }
        if (file != null) {
            // read all the lines
            List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());

            LOG.info("Read " + lines.size() + " lines from file: " + relativeFile);

            // the list is 0-based, and line number is 1-based
            int idx = lineNumber - 1;
            String line = lines.get(idx);

            return line;
        }
    }

    return null;
}
 
Example #11
Source File: SpringBootConfigurationResourcesFilesVisitor.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(VisitContext visitContext, Resource<?> resource) {
    // skip directories
    if (resource instanceof FileResource) {
        if (((FileResource) resource).isDirectory()) {
            return;
        }
    }

    String name = resource.getFullyQualifiedName();
    name = AbstractCamelProjectCommand.asRelativeFile(name, null, facet, null);
    LOG.info("Resource name " + name);

    if (name.equals("application.properties") || name.equals("application.yaml") || name.equals("application.yml")) {
        boolean include = true;
        if (filter != null) {
            Boolean out = filter.apply(name);
            include = out == null || out;
        }

        if (include) {
            // we only want the relative dir name from the resource directory, eg META-INF/spring/foo.xml
            String baseDir = facet.getResourceDirectory().getFullyQualifiedName();
            String fqn = resource.getFullyQualifiedName();
            if (fqn.startsWith(baseDir)) {
                fqn = fqn.substring(baseDir.length() + 1);
            }
            files.add(fqn);
        }
    }
}
 
Example #12
Source File: XmlResourcesCamelEndpointsVisitor.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(VisitContext visitContext, Resource<?> resource) {
    // skip directories
    if (resource instanceof FileResource) {
        if (((FileResource) resource).isDirectory()) {
            return;
        }
    }

    String name = resource.getFullyQualifiedName();
    name = AbstractCamelProjectCommand.asRelativeFile(name, null, facet, null);
    LOG.info("Resource name " + name);

    if (name.endsWith(".xml")) {
        boolean include = true;
        if (filter != null) {
            Boolean out = filter.apply(name);
            LOG.info("Filter " + name + " -> " + out);
            include = out == null || out;
        }

        if (include) {
            boolean camel = containsCamelRoutes(resource);
            if (camel) {
                // find all the endpoints (currently only <endpoint> and within <route>)
                try {
                    InputStream is = resource.getResourceInputStream();
                    String fqn = resource.getFullyQualifiedName();
                    String baseDir = facet.getResourceDirectory().getFullyQualifiedName();
                    XmlRouteParser.parseXmlRouteEndpoints(is, baseDir, fqn, endpoints);
                } catch (Throwable e) {
                    // ignore
                }
            }
        }
    }
}
 
Example #13
Source File: XmlWebResourcesCamelEndpointsVisitor.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(VisitContext visitContext, Resource<?> resource) {
    // skip directories
    if (resource instanceof FileResource) {
        if (((FileResource) resource).isDirectory()) {
            return;
        }
    }

    String name = resource.getFullyQualifiedName();
    name = AbstractCamelProjectCommand.asRelativeFile(name, null, null, facet);
    LOG.info("Resource name " + name);

    if (name.endsWith(".xml")) {
        boolean include = true;
        if (filter != null) {
            Boolean out = filter.apply(name);
            LOG.info("Filter " + name + " -> " + out);
            include = out == null || out;
        }

        if (include) {
            boolean camel = containsCamelRoutes(resource);
            if (camel) {
                // find all the endpoints (currently only <endpoint> and within <route>)
                try {
                    InputStream is = resource.getResourceInputStream();
                    String fqn = resource.getFullyQualifiedName();
                    String baseDir = facet.getWebRootDirectory().getFullyQualifiedName();
                    XmlRouteParser.parseXmlRouteEndpoints(is, baseDir, fqn, endpoints);
                } catch (Throwable e) {
                    // ignore
                }
            }
        }
    }
}
 
Example #14
Source File: XmlResourcesCamelFilesVisitor.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(VisitContext visitContext, Resource<?> resource) {
    // skip directories
    if (resource instanceof FileResource) {
        if (((FileResource) resource).isDirectory()) {
            return;
        }
    }

    String name = resource.getFullyQualifiedName();
    name = AbstractCamelProjectCommand.asRelativeFile(name, null, facet, null);
    LOG.info("Resource name " + name);

    if (name.endsWith(".xml")) {
        boolean include = true;
        if (filter != null) {
            Boolean out = filter.apply(name);
            include = out == null || out;
        }

        if (include) {
            boolean camel = containsCamelRoutes(resource);
            if (camel) {
                // we only want the relative dir name from the resource directory, eg META-INF/spring/foo.xml
                String baseDir = facet.getResourceDirectory().getFullyQualifiedName();
                String fqn = resource.getFullyQualifiedName();
                if (fqn.startsWith(baseDir)) {
                    fqn = fqn.substring(baseDir.length() + 1);
                }

                files.add(fqn);
            }
        }
    }
}
 
Example #15
Source File: AbstractCamelProjectCommand.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected boolean isSelectedFileXml(UIContext context) {
    Optional<UIRegion<Object>> region = context.getSelection().getRegion();
    if (region.isPresent()) {
        Object resource = region.get().getResource();
        if (resource instanceof FileResource) {
            return ((FileResource) resource).getFullyQualifiedName().endsWith(".xml");
        }
    }
    return false;
}
 
Example #16
Source File: FunktionArchetypeSelectionWizardStep.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    UIContext uiContext = context.getUIContext();
    Project project = (Project) uiContext.getAttributeMap().get(Project.class);
    Archetype chosenArchetype = archetype.getValue();
    String coordinate = chosenArchetype.getGroupId() + ":" + chosenArchetype.getArtifactId() + ":"
            + chosenArchetype.getVersion();
    DependencyQueryBuilder depQuery = DependencyQueryBuilder.create(coordinate);
    String repository = chosenArchetype.getRepository();
    if (!Strings.isNullOrEmpty(repository)) {
        if (repository.endsWith(".xml")) {
            int lastRepositoryPath = repository.lastIndexOf('/');
            if (lastRepositoryPath > -1)
                repository = repository.substring(0, lastRepositoryPath);
        }
        if (!repository.isEmpty()) {
            depQuery.setRepositories(new DependencyRepository("archetype", repository));
        }
    }
    Dependency resolvedArtifact = dependencyResolver.resolveArtifact(depQuery);
    FileResource<?> artifact = resolvedArtifact.getArtifact();
    MetadataFacet metadataFacet = project.getFacet(MetadataFacet.class);
    File fileRoot = project.getRoot().reify(DirectoryResource.class).getUnderlyingResourceObject();
    ArchetypeHelper archetypeHelper = new ArchetypeHelper(artifact.getResourceInputStream(), fileRoot,
            metadataFacet.getProjectGroupName(), metadataFacet.getProjectName(), metadataFacet.getProjectVersion());
    JavaSourceFacet facet = project.getFacet(JavaSourceFacet.class);
    archetypeHelper.setPackageName(facet.getBasePackage());
    archetypeHelper.execute();
    return Results.success();
}
 
Example #17
Source File: ConfigureEndpointPropertiesStep.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected Result addOrEditEndpointXml(FileResource file, String uri, String endpointUrl, String endpointInstanceName, String xml, String lineNumber, String lineNumberEnd) throws Exception {
    // if we have a line number then use that to edit the existing value
    if (lineNumber != null) {
        List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());
        return editEndpointXml(lines, lineNumber, endpointUrl, uri, file, xml);
    } else {
        // we are in add mode, so parse dom to find <camelContext> and insert the endpoint where its needed
        Document root = XmlLineNumberParser.parseXml(file.getResourceInputStream());
        return addEndpointXml(root, endpointInstanceName, uri, file, xml);
    }
}
 
Example #18
Source File: ConfigureEndpointPropertiesStep.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
private Result addEndpointXml(FileResource file, String uri, String endpointInstanceName, String xml, String cursorPosition) throws Exception {

        LOG.info("Adding uri " + uri + " at position " + cursorPosition + " in file " + xml);

        // we do not want to change the current code formatting so we need to search
        // replace the unformatted class source code
        StringBuilder sb = new StringBuilder(file.getContents());

        int pos = Integer.valueOf(cursorPosition);

        // move to end if pos is after the content
        pos = Math.min(sb.length(), pos);

        LOG.info("Adding endpoint at pos: " + pos + " in file: " + xml);

        // check if prev and next is a quote and if not then add it automatic
        int prev = pos - 1;
        int next = pos + 1;
        char ch = sb.charAt(prev);
        char ch2 = next < sb.length() ? sb.charAt(next) : ' ';
        if (ch != '"' && ch2 != '"') {
            uri = "\"" + uri + "\"";
        }

        // insert uri at position
        sb.insert(pos, uri);

        String text = sb.toString();

        // use this code currently to save content unformatted
        file.setContents(text);

        return Results.success("Added endpoint " + uri + " in " + xml);
    }
 
Example #19
Source File: AbstractCamelProjectCommand.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected Element getSelectedCamelElementNode(Project project, String xmlResourceName, String key) throws Exception {
    FileResource file = getXmlResourceFile(project, xmlResourceName);
    if (file != null) {
        InputStream resourceInputStream = file.getResourceInputStream();
        return CamelXmlHelper.getSelectedCamelElementNode(key, resourceInputStream);
    } else {
        return null;
    }
}
 
Example #20
Source File: AbstractCamelProjectCommand.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected boolean isSelectedFileJava(UIContext context) {
    Optional<UIRegion<Object>> region = context.getSelection().getRegion();
    if (region.isPresent()) {
        Object resource = region.get().getResource();
        if (resource instanceof FileResource) {
            return ((FileResource) resource).getFullyQualifiedName().endsWith(".java");
        }
    }
    return false;
}
 
Example #21
Source File: XmlWebResourcesCamelFilesVisitor.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(VisitContext visitContext, Resource<?> resource) {
    // skip directories
    if (resource instanceof FileResource) {
        if (((FileResource) resource).isDirectory()) {
            return;
        }
    }

    String name = resource.getFullyQualifiedName();
    name = AbstractCamelProjectCommand.asRelativeFile(name, null, null, facet);
    LOG.info("Resource name " + name);

    if (name.endsWith(".xml")) {
        boolean include = true;
        if (filter != null) {
            Boolean out = filter.apply(name);
            LOG.info("Filter " + name + " -> " + out);
            include = out == null || out;
        }

        if (include) {
            boolean camel = containsCamelRoutes(resource);
            if (camel) {
                // we only want the relative dir name from the resource directory, eg WEB-INF/foo.xml
                String baseDir = facet.getWebRootDirectory().getFullyQualifiedName();
                String fqn = resource.getFullyQualifiedName();
                if (fqn.startsWith(baseDir)) {
                    fqn = fqn.substring(baseDir.length() + 1);
                }

                int idx = Math.max(fqn.lastIndexOf("/"), fqn.lastIndexOf("\\"));
                if (idx > 0) {
                    directories.add(fqn.substring(0, idx));
                }
                files.add(fqn);
            }
        }
    }
}
 
Example #22
Source File: AddFromOrToEndpointXmlStep.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
@Override
protected Result addOrEditEndpointXml(FileResource file, String uri, String endpointUrl, String endpointInstanceName, String xml, String lineNumber, String lineNumberEnd) throws Exception {
    String key = parentNode.getKey();
    if (Strings.isNullOrBlank(key)) {
        return Results.fail("Parent node has no key! " + parentNode + " in file " + file.getName());
    }

    Document root = XmlLineNumberParser.parseXml(file.getResourceInputStream());
    if (root != null) {
        Node selectedNode = CamelXmlHelper.findCamelNodeInDocument(root, key);
        if (selectedNode != null) {

            // we need to add after the parent node, so use line number information from the parent
            lineNumber = (String) selectedNode.getUserData(XmlLineNumberParser.LINE_NUMBER);
            lineNumberEnd = (String) selectedNode.getUserData(XmlLineNumberParser.LINE_NUMBER_END);

            LOG.info("Add endpoint at line number " + lineNumber + "-" + lineNumberEnd + " at selected node " + selectedNode.getNodeName());

            if (lineNumber != null && lineNumberEnd != null) {

                String line;
                if (isFrom) {
                    line = String.format("<from uri=\"%s\"/>", uri);
                } else {
                    line = String.format("<to uri=\"%s\"/>", uri);
                }

                // read all the lines
                List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());

                // the list is 0-based, and line number is 1-based
                // if from then use the start line number, otherwise use the end line number
                int idx = isFrom ? Integer.valueOf(lineNumber) : Integer.valueOf(lineNumberEnd);
                // use the same indent from the parent line
                int spaces = LineNumberHelper.leadingSpaces(lines, idx - 1);
                if (isFrom) {
                    // and append 2 if we are starting a new route with <from>
                    spaces += 2;
                }
                line = LineNumberHelper.padString(line, spaces);
                // add the line at the position
                lines.add(idx, line);

                // and save the file back
                String content = LineNumberHelper.linesToString(lines);
                file.setContents(content);
                return Results.success("Added: " + line.trim());
            }
        }
        return Results.fail("Cannot find Camel node in XML file: " + key);
    } else {
        return Results.fail("Cannot load Camel XML file: " + file.getName());
    }
}
 
Example #23
Source File: AddRouteFromEndpointXmlStep.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
@Override
protected Result addOrEditEndpointXml(FileResource file, String uri, String endpointUrl, String endpointInstanceName, String xml, String lineNumber, String lineNumberEnd) throws Exception {
    Document root = XmlLineNumberParser.parseXml(file.getResourceInputStream());
    if (root != null) {
        NodeList camels = getCamelContextElements(root);
        // TODO: what about 2+ camel's ?
        if (camels != null && camels.getLength() == 1) {
            Node camel = camels.item(0);
            Node camelContext = null;

            for (int i = 0; i < camel.getChildNodes().getLength(); i++) {
                if (CamelXmlHelper.isCamelContextOrRoutesNode(camel)) {
                    camelContext = camel;
                }

                Node child = camel.getChildNodes().item(i);
                if (CamelXmlHelper.isCamelContextOrRoutesNode(child)) {
                    camelContext = child;
                }
            }

            if (camelContext == null) {
                return Results.fail("Cannot find <camelContext> or <routes> in XML file " + xml);
            }

            // we need to add after the parent node, so use line number information from the parent
            lineNumber = (String) camelContext.getUserData(XmlLineNumberParser.LINE_NUMBER);
            lineNumberEnd = (String) camelContext.getUserData(XmlLineNumberParser.LINE_NUMBER_END);

            if (lineNumber != null && lineNumberEnd != null) {

                String line1;
                if (routeId != null) {
                    line1 = String.format("<route id=\"%s\">", routeId);
                } else {
                    line1 = "<route>";
                }
                String line2 = String.format("<from uri=\"%s\"/>", uri);
                String line3 = "</route>";

                // if we created a new endpoint, then insert a new line with the endpoint details
                List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());

                // the list is 0-based, and line number is 1-based
                int idx = Integer.valueOf(lineNumberEnd) - 1;
                int spaces = LineNumberHelper.leadingSpaces(lines, idx);

                line3 = LineNumberHelper.padString(line3, spaces + 2);
                line2 = LineNumberHelper.padString(line2, spaces + 4);
                line1 = LineNumberHelper.padString(line1, spaces + 2);

                // check if previous line is empty or not
                String text = lines.get(idx - 1);
                boolean emptyLine = text == null || text.trim().isEmpty();

                lines.add(idx, "");
                lines.add(idx, line3);
                lines.add(idx, line2);
                lines.add(idx, line1);
                if (!emptyLine) {
                    // insert empty lines around the added route (if needed to avoid 2x empty lines)
                    lines.add(idx, "");
                }

                // and save the file back
                String content = LineNumberHelper.linesToString(lines);
                file.setContents(content);
            }
            return Results.success("Added route");
        }
        return Results.fail("Cannot find Camel node in XML file: " + xml);
    } else {
        return Results.fail("Could not load camel XML");
    }
}
 
Example #24
Source File: CamelDeleteNodeXmlCommand.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
@Override
public Result execute(UIExecutionContext context) throws Exception {
    Project project = getSelectedProject(context);

    NodeDto nodeValue = null;
    int selectedIdx = node.getSelectedIndex();
    if (selectedIdx != -1) {
        nodeValue = nodes.get(selectedIdx);
    }
    if (nodeValue == null) {
        return Results.fail("No node to delete!");
    }
    String key = nodeValue.getKey();
    if (Strings.isNullOrBlank(key)) {
        return Results.fail("Selected node does not have a key so cannot delete it!");
    }
    String xmlResourceName = xml.getValue();

    FileResource file = getXmlResourceFile(project, xmlResourceName);
    if (file == null || !file.exists()) {
        return Results.fail("Cannot find XML file " + xmlResourceName);
    }

    List<ContextDto> camelContexts = CamelXmlHelper.loadCamelContext(getCamelCatalog(), context.getUIContext(), project, xmlResourceName);
    if (camelContexts == null) {
        return Results.fail("No file found for: " + xmlResourceName);
    }

    Document root = XmlLineNumberParser.parseXml(file.getResourceInputStream());
    if (root != null) {
        Node selectedNode = CamelXmlHelper.findCamelNodeInDocument(root, key);
        if (selectedNode != null) {

            // we need to add after the parent node, so use line number information from the parent
            String lineNumber = (String) selectedNode.getUserData(XmlLineNumberParser.LINE_NUMBER);
            String lineNumberEnd = (String) selectedNode.getUserData(XmlLineNumberParser.LINE_NUMBER_END);

            if (lineNumber != null && lineNumberEnd != null) {

                // read all the lines
                List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());

                // the list is 0-based, and line number is 1-based
                int idx = Integer.valueOf(lineNumber) - 1;
                int idx2 = Integer.valueOf(lineNumberEnd) - 1;
                int delta = (idx2 - idx) + 1;

                // remove the lines
                while (delta > 0) {
                    delta--;
                    lines.remove(idx);
                }

                // and save the file back
                String content = LineNumberHelper.linesToString(lines);
                file.setContents(content);
                return Results.success("Removed node");
            }
        }
        return Results.fail("Cannot find Camel node in XML file: " + nodeValue);
    } else {
        return Results.fail("Cannot load Camel XML file: " + file.getName());
    }
}
 
Example #25
Source File: ConfigureEndpointPropertiesStep.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
protected Result addEndpointOther(Project project, ResourcesFacet facet, FileResource file, String uri,
                                  String currentFile, String cursorPosition) throws Exception {

    StringBuilder sb = new StringBuilder(file.getContents());

    int pos = Integer.valueOf(cursorPosition);

    // move to end if pos is after the content
    pos = Math.min(sb.length(), pos);

    LOG.info("Adding endpoint at pos: " + pos + " in file: " + currentFile);

    // insert uri at position
    sb.insert(pos, uri);

    // use this code currently to save content unformatted
    file.setContents(sb.toString());

    return Results.success("Added endpoint " + uri + " in " + currentFile);
}
 
Example #26
Source File: EditNodeXmlStep.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
@Override
protected Result addModelXml(String pattern, List<String> lines, String lineNumber, String lineNumberEnd, String modelXml, FileResource file, String xml) throws Exception {
    // noop
    return null;
}
 
Example #27
Source File: AddNodeXmlStep.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
@Override
protected Result editModelXml(String pattern, List<String> lines, String lineNumber, String lineNumberEnd, String modelXml, FileResource file, String xml) throws Exception {
    // noop
    return null;
}
 
Example #28
Source File: DetectFractionsCommand.java    From thorntail-addon with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Result execute(UIExecutionContext executionContext) throws Exception
{
   UIProgressMonitor progressMonitor = executionContext.getProgressMonitor();
   UIOutput output = executionContext.getUIContext().getProvider().getOutput();
   FractionUsageAnalyzer analyzer = ThorntailFacet.getFractionUsageAnalyzer();
   DirectoryResource value = inputDir.getValue();
   analyzer.source(value.getUnderlyingResourceObject());
   Project project = getSelectedProject(executionContext);
   int total = 1;
   if (build.getValue())
      total++;
   if (depend.getValue())
      total++;
   progressMonitor.beginTask("Detecting fractions", total);
   if (build.getValue())
   {
      PackagingFacet packaging = project.getFacet(PackagingFacet.class);
      progressMonitor.setTaskName("Building the project...");
      FileResource<?> finalArtifact = packaging.createBuilder().build(output.out(), output.err())
               .reify(FileResource.class);
      analyzer.source(finalArtifact.getUnderlyingResourceObject());
      progressMonitor.worked(1);
   }
   Collection<FractionDescriptor> detectedFractions = analyzer.detectNeededFractions();
   output.info(output.out(), "Detected fractions: " + detectedFractions);
   progressMonitor.worked(1);
   if (depend.getValue() && detectedFractions.size() > 0)
   {
      progressMonitor.setTaskName("Adding missing fractions as project dependencies...");
      ThorntailFacet facet = project.getFacet(ThorntailFacet.class);
      detectedFractions.removeAll(facet.getInstalledFractions());
      // detectedFractions.remove(fractionList.getFractionDescriptor(Swarm.DEFAULT_FRACTION_GROUPID, "container"));
      if (detectedFractions.isEmpty())
      {
         output.warn(output.out(), "Project already contains all the installed fractions. Doing nothing.");
      }
      else
      {
         output.info(output.out(), "Installing the following dependencies: " + detectedFractions);
         facet.installFractions(detectedFractions);
      }
      progressMonitor.worked(1);
   }
   progressMonitor.done();
   return Results.success();
}
 
Example #29
Source File: WindupCommand.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
private void initializeConfigurationOptionComponents(UIBuilder builder)
{
    for (final ConfigurationOption option : WindupConfiguration.getWindupConfigurationOptions())
    {
        InputComponent<?, ?> inputComponent = null;
        switch (option.getUIType())
        {
        case SINGLE:
        {
            UIInput<?> inputSingle = componentFactory.createInput(option.getName(), option.getType());
            inputSingle.setDefaultValue(new DefaultValueAdapter(option));
            inputComponent = inputSingle;
            break;
        }
        case MANY:
        {
            // forge can't handle "Path", so use File
            Class<?> optionType = option.getType() == Path.class ? File.class : option.getType();

            UIInputMany<?> inputMany = componentFactory.createInputMany(option.getName(), optionType);
            inputMany.setDefaultValue(new DefaultValueAdapter(option, Iterable.class));
            inputComponent = inputMany;
            break;
        }
        case SELECT_MANY:
        {
            UISelectMany<?> selectMany = componentFactory.createSelectMany(option.getName(), option.getType());
            selectMany.setValueChoices((Iterable) option.getAvailableValues());
            selectMany.setDefaultValue(new DefaultValueAdapter(option, Iterable.class));
            inputComponent = selectMany;
            break;
        }
        case SELECT_ONE:
        {
            UISelectOne<?> selectOne = componentFactory.createSelectOne(option.getName(), option.getType());
            selectOne.setValueChoices((Iterable) option.getAvailableValues());
            selectOne.setDefaultValue(new DefaultValueAdapter(option));
            inputComponent = selectOne;
            break;
        }
        case DIRECTORY:
        {
            UIInput<DirectoryResource> directoryInput = componentFactory.createInput(option.getName(),
                        DirectoryResource.class);
            directoryInput.setDefaultValue(new DefaultValueAdapter(option, DirectoryResource.class));
            inputComponent = directoryInput;
            break;
        }
        case FILE:
        {
            UIInput<?> fileInput = componentFactory.createInput(option.getName(), FileResource.class);
            fileInput.setDefaultValue(new DefaultValueAdapter(option, FileResource.class));
            inputComponent = fileInput;
            break;
        }
        case FILE_OR_DIRECTORY:
        {
            UIInput<?> fileOrDirInput = componentFactory.createInput(option.getName(), FileResource.class);
            fileOrDirInput.setDefaultValue(new DefaultValueAdapter(option, FileResource.class));
            inputComponent = fileOrDirInput;
            break;
        }
        }
        if (inputComponent == null)
        {
            throw new IllegalArgumentException("Could not build input component for: " + option);
        }
        inputComponent.setLabel(option.getLabel());
        inputComponent.setRequired(option.isRequired());
        inputComponent.setDescription(option.getDescription());
        builder.add(inputComponent);
        inputOptions.put(option, inputComponent);
    }
}
 
Example #30
Source File: ConfigureEipPropertiesStep.java    From fabric8-forge with Apache License 2.0 votes vote down vote up
protected abstract Result addModelXml(String pattern, List<String> lines, String lineNumber, String lineNumberEnd, String modelXml, FileResource file, String xml) throws Exception;