Example usage for org.apache.commons.lang StringUtils substringBefore

List of usage examples for org.apache.commons.lang StringUtils substringBefore

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringBefore.

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:org.commonjava.maven.ext.core.impl.DependencyManipulator.java

/**
 * Apply a set of version overrides to a list of dependencies. Return a set of the overrides which were not applied.
 *
 * @param project The current Project/*from  w  w  w .  j  a  v a 2s.c  o  m*/
 * @param dependencies The list of dependencies
 * @param explicitOverrides Any explicitOverrides to track for ignoring
 * @param overrides The map of dependency version overrides
 * @return The map of overrides that were not matched in the dependencies
 * @throws ManipulationException if an error occurs
 */
private Map<ArtifactRef, String> applyOverrides(final Project project,
        final HashMap<ArtifactRef, Dependency> dependencies, final WildcardMap<String> explicitOverrides,
        final Map<ArtifactRef, String> overrides) throws ManipulationException {
    // Duplicate the override map so unused overrides can be easily recorded
    final Map<ArtifactRef, String> unmatchedVersionOverrides = new LinkedHashMap<>(overrides);

    if (dependencies == null || dependencies.size() == 0) {
        return unmatchedVersionOverrides;
    }

    final CommonState commonState = session.getState(CommonState.class);
    final boolean strict = commonState.getStrict();

    // Apply matching overrides to dependencies
    for (final ArtifactRef dependency : dependencies.keySet()) {
        ProjectRef depPr = new SimpleProjectRef(dependency.getGroupId(), dependency.getArtifactId());

        // We might have junit:junit:3.8.2 and junit:junit:4.1 for differing override scenarios within the
        // overrides list. If strict mode alignment is enabled, using multiple overrides will work with
        // different modules. It is currently undefined what will happen if non-strict mode is enabled and
        // multiple versions are in the remote override list (be it from a bom or rest call). Actually, what
        // will most likely happen is last-wins.
        for (final Map.Entry<ArtifactRef, String> entry : overrides.entrySet()) {
            ProjectRef groupIdArtifactId = entry.getKey().asProjectRef();
            if (depPr.equals(groupIdArtifactId)) {
                final String oldVersion = dependencies.get(dependency).getVersion();
                final String overrideVersion = entry.getValue();
                final String resolvedValue = dependency.getVersionString();

                if (isEmpty(overrideVersion)) {
                    logger.warn("Unable to align with an empty override version for " + groupIdArtifactId
                            + "; ignoring");
                } else if (isEmpty(oldVersion)) {
                    logger.debug("Dependency is a managed version for " + groupIdArtifactId + "; ignoring");
                } else if (oldVersion.equals("${project.version}")
                        || (oldVersion.contains("$") && project.getVersion().equals(resolvedValue))) {
                    logger.warn(
                            "Dependency {} with original version {} and project version {} for {} references ${project.version} so skipping.",
                            dependency, oldVersion, project.getVersion(), project.getPom());
                }
                // If we have an explicitOverride, this will always override the dependency changes made here.
                // By avoiding the potential duplicate work it also avoids a possible property clash problem.
                else if (explicitOverrides.containsKey(depPr)) {
                    logger.debug(
                            "Dependency {} matches known explicit override so not performing initial override pass.",
                            depPr);
                    unmatchedVersionOverrides.remove(entry.getKey());
                }
                // If we're doing strict matching with properties, then the original parts should match.
                // i.e. assuming original resolved value is 1.2 and potential new value is 1.2.rebuild-1
                // then this is fine to continue. If the original is 1.2 and potential new value is 1.3.rebuild-1
                // then don't bother to attempt to cache the property as the strict check would fail.
                // This extra check avoids an erroneous "Property replacement clash" error.

                // Can't blindly compare resolvedValue [original] against ar as ar / overrideVersion is the new GAV. We don't
                // have immediate access to the original property so the closest that is feasible is verify strict matching.
                else if (strict && oldVersion.contains("$")
                        && !PropertiesUtils.checkStrictValue(session, resolvedValue, overrideVersion)) {
                    logger.debug(
                            "Original fully resolved version {} of {} does not match override version {} -> {} so ignoring",
                            resolvedValue, dependency, entry.getKey(), overrideVersion);
                    if (commonState.getFailOnStrictViolation()) {
                        throw new ManipulationException(
                                "For {} replacing original property version {} (fully resolved: {} ) with new version {} for {} violates the strict version-alignment rule!",
                                depPr.toString(), dependencies.get(dependency).getVersion(), resolvedValue,
                                entry.getKey().getVersionString(), entry.getKey().asProjectRef().toString());
                    } else {
                        logger.warn(
                                "Replacing original property version {} with new version {} for {} violates the strict version-alignment rule!",
                                resolvedValue, overrideVersion, dependencies.get(dependency).getVersion());
                    }
                } else {
                    if (!PropertiesUtils.cacheProperty(project, commonState, versionPropertyUpdateMap,
                            oldVersion, overrideVersion, entry.getKey(), false)) {
                        if (strict
                                && !PropertiesUtils.checkStrictValue(session, resolvedValue, overrideVersion)) {
                            if (commonState.getFailOnStrictViolation()) {
                                throw new ManipulationException(
                                        "Replacing original version {} in dependency {} with new version {} violates the strict version-alignment rule!",
                                        oldVersion, groupIdArtifactId.toString(), overrideVersion);
                            } else {
                                logger.warn(
                                        "Replacing original version {} in dependency {} with new version {} violates the strict version-alignment rule!",
                                        oldVersion, groupIdArtifactId, overrideVersion);
                            }
                        } else {
                            logger.debug("Altered dependency {} : {} -> {}", groupIdArtifactId, oldVersion,
                                    overrideVersion);

                            if (oldVersion.contains("${")) {
                                String suffix = PropertiesUtils.getSuffix(session);
                                String replaceVersion;

                                if (commonState.getStrictIgnoreSuffix() && oldVersion.contains(suffix)) {
                                    replaceVersion = StringUtils.substringBefore(oldVersion, suffix);
                                    replaceVersion += suffix
                                            + StringUtils.substringAfter(overrideVersion, suffix);
                                } else {
                                    replaceVersion = oldVersion
                                            + StringUtils.removeStart(overrideVersion, resolvedValue);
                                }
                                logger.debug("Resolved value is {} and replacement version is {} ",
                                        resolvedValue, replaceVersion);

                                // In this case the previous value couldn't be cached even though it contained a property
                                // as it was either multiple properties or a property combined with a hardcoded value. Therefore
                                // just append the suffix.
                                dependencies.get(dependency).setVersion(replaceVersion);
                            } else {
                                dependencies.get(dependency).setVersion(overrideVersion);
                            }
                        }
                    }
                    unmatchedVersionOverrides.remove(entry.getKey());
                }
            }
        }
    }

    return unmatchedVersionOverrides;
}

From source file:org.commonjava.maven.ext.manip.impl.DependencyManipulator.java

/**
 * Apply a set of version overrides to a list of dependencies. Return a set of the overrides which were not applied.
 *
 * @param session The ManipulationSession
 * @param project The current Project//from  ww w  . ja  va 2s . com
 * @param dependencies The list of dependencies
 * @param overrides The map of dependency version overrides
 * @param explicitOverrides Any explicitOverrides to track for ignoring    @return The map of overrides that were not matched in the dependencies
 * @throws ManipulationException if an error occurs
 */
private Map<ArtifactRef, String> applyOverrides(final ManipulationSession session, Project project,
        final List<Dependency> dependencies, final Map<ArtifactRef, String> overrides,
        WildcardMap<String> explicitOverrides) throws ManipulationException {
    // Duplicate the override map so unused overrides can be easily recorded
    final Map<ArtifactRef, String> unmatchedVersionOverrides = new LinkedHashMap<>();
    unmatchedVersionOverrides.putAll(overrides);

    if (dependencies == null) {
        return unmatchedVersionOverrides;
    }

    final DependencyState state = session.getState(DependencyState.class);
    final boolean strict = state.getStrict();

    // Apply matching overrides to dependencies
    for (final Dependency dependency : dependencies) {
        ProjectRef depPr = new SimpleProjectRef(dependency.getGroupId(), dependency.getArtifactId());

        // We might have junit:junit:3.8.2 and junit:junit:4.1 for differing override scenarios within the
        // overrides list. If strict mode alignment is enabled, using multiple overrides will work with
        // different modules. It is currently undefined what will happen if non-strict mode is enabled and
        // multiple versions are in the remote override list (be it from a bom or rest call). Actually, what
        // will most likely happen is last-wins.
        for (final Map.Entry<ArtifactRef, String> entry : overrides.entrySet()) {
            ProjectRef groupIdArtifactId = entry.getKey().asProjectRef();

            if (depPr.equals(groupIdArtifactId)) {
                final String oldVersion = dependency.getVersion();
                final String overrideVersion = entry.getValue();
                final String resolvedValue = PropertiesUtils.resolveProperties(session.getProjects(),
                        oldVersion);

                if (isEmpty(overrideVersion)) {
                    logger.warn("Unable to align with an empty override version for " + groupIdArtifactId
                            + "; ignoring");
                } else if (isEmpty(oldVersion)) {
                    logger.debug("Dependency is a managed version for " + groupIdArtifactId + "; ignoring");
                }
                // If we have an explicitOverride, this will always override the dependency changes made here.
                // By avoiding the potential duplicate work it also avoids a possible property clash problem.
                else if (explicitOverrides.containsKey(depPr)) {
                    logger.debug(
                            "Dependency {} matches known explicit override so not performing initial override pass.",
                            depPr);
                    unmatchedVersionOverrides.remove(entry.getKey());
                }
                // If we're doing strict matching with properties, then the original parts should match.
                // i.e. assuming original resolved value is 1.2 and potential new value is 1.2.rebuild-1
                // then this is fine to continue. If the original is 1.2 and potential new value is 1.3.rebuild-1
                // then don't bother to attempt to cache the property as the strict check would fail.
                // This extra check avoids an erroneous "Property replacement clash" error.

                // Can't blindly compare resolvedValue [original] against ar as ar / overrideVersion is the new GAV. We don't
                // have immediate access to the original property so the closest that is feasible is verify strict matching.
                else if (strict && oldVersion.contains("$")
                        && !PropertiesUtils.checkStrictValue(session, resolvedValue, overrideVersion)) {
                    logger.debug(
                            "Original fully resolved version {} of {} does not match override version {} -> {} so ignoring",
                            resolvedValue, dependency, entry.getKey(), overrideVersion);
                    if (state.getFailOnStrictViolation()) {
                        throw new ManipulationException(
                                "For {} replacing original property version {} (fully resolved: {} ) with new version {} for {} violates the strict version-alignment rule!",
                                depPr.toString(), dependency.getVersion(), resolvedValue,
                                entry.getKey().getVersionString(), entry.getKey().asProjectRef().toString());
                    } else {
                        logger.warn(
                                "Replacing original property version {} with new version {} for {} violates the strict version-alignment rule!",
                                resolvedValue, overrideVersion, dependency.getVersion());
                    }
                } else {
                    // Too much spurious logging with project.version.
                    if (!oldVersion.equals("${project.version}")) {
                        logger.info("Updating version {} for dependency {} from {}.", overrideVersion,
                                dependency, project.getPom());
                    }

                    if (!PropertiesUtils.cacheProperty(versionPropertyUpdateMap, oldVersion, overrideVersion,
                            entry.getKey(), false)) {
                        if (oldVersion.equals("${project.version}")) {
                            logger.debug("For dependency {} ; version is built in {} so skipping inlining {}",
                                    groupIdArtifactId, oldVersion, overrideVersion);
                        } else if (strict
                                && !PropertiesUtils.checkStrictValue(session, resolvedValue, overrideVersion)) {
                            if (state.getFailOnStrictViolation()) {
                                throw new ManipulationException(
                                        "Replacing original version {} in dependency {} with new version {} violates the strict version-alignment rule!",
                                        oldVersion, groupIdArtifactId.toString(), overrideVersion);
                            } else {
                                logger.warn(
                                        "Replacing original version {} in dependency {} with new version {} violates the strict version-alignment rule!",
                                        oldVersion, groupIdArtifactId, overrideVersion);
                            }
                        } else {
                            logger.debug("Altered dependency {} : {} -> {}", groupIdArtifactId, oldVersion,
                                    overrideVersion);

                            if (oldVersion.contains("${")) {
                                String suffix = PropertiesUtils.getSuffix(session);
                                String replaceVersion;

                                if (state.getStrictIgnoreSuffix() && oldVersion.contains(suffix)) {
                                    replaceVersion = StringUtils.substringBefore(oldVersion, suffix);
                                    replaceVersion += suffix
                                            + StringUtils.substringAfter(overrideVersion, suffix);
                                } else {
                                    replaceVersion = oldVersion
                                            + StringUtils.removeStart(overrideVersion, resolvedValue);
                                }
                                logger.debug("Resolved value is {} and replacement version is {} ",
                                        resolvedValue, replaceVersion);

                                // In this case the previous value couldn't be cached even though it contained a property
                                // as it was either multiple properties or a property combined with a hardcoded value. Therefore
                                // just append the suffix.
                                dependency.setVersion(replaceVersion);
                            } else {
                                dependency.setVersion(overrideVersion);
                            }
                        }
                    }
                    unmatchedVersionOverrides.remove(entry.getKey());
                }
            }
        }
    }

    return unmatchedVersionOverrides;
}

From source file:org.cruxframework.mediamanager.core.utils.QueryBuilder.java

private void registerPropertyForJoin(Filter filter) {
    String property = filter.getField();
    String rootProperty = StringUtils.substringBefore(property, ".");
    joinProperties.add(rootProperty);//from   w w  w .  j a va  2  s  .  co  m
}

From source file:org.cruxframework.mediamanager.core.utils.QueryBuilder.java

private boolean isMultivaluedProperty(String property) {
    String rootProperty = StringUtils.substringBefore(property, ".");

    try {//from  ww w  .ja va2s.  c om
        Field field = entityClass.getDeclaredField(rootProperty);
        return Iterable.class.isAssignableFrom(field.getType());
    } catch (Exception e) {
        return false;
    }
}

From source file:org.debux.webmotion.netbeans.completion.WebMotionCompletion.java

@Override
public CompletionTask createTask(int queryType, JTextComponent component) {
    if (queryType != CompletionProvider.COMPLETION_QUERY_TYPE) {
        return null;
    }/*from   ww w . j a  va  2s.  c  o m*/

    return new AsyncCompletionTask(new AsyncCompletionQuery() {
        @Override
        protected void query(CompletionResultSet completionResultSet, Document document, int caretOffset) {

            String filter = null;
            int startOffset = caretOffset - 1;
            int column = 0;

            try {
                // Get filter
                StyledDocument doc = (StyledDocument) document;
                int lineStartOffset = Utils.getRowFirstNonWhite(doc, caretOffset);
                char[] line = doc.getText(lineStartOffset, caretOffset - lineStartOffset).toCharArray();
                int whiteOffset = Utils.indexOfWhite(line);
                filter = new String(line, whiteOffset + 1, line.length - whiteOffset - 1);
                if (whiteOffset > 0) {
                    startOffset = lineStartOffset + whiteOffset + 1;
                } else {
                    startOffset = lineStartOffset;
                }

                // Get position
                Element lineElement = doc.getParagraphElement(caretOffset);
                String lineValue = doc.getText(lineElement.getStartOffset(),
                        caretOffset - lineElement.getStartOffset());

                Pattern pattern = Pattern.compile("\\s+");
                Matcher matcher = pattern.matcher(lineValue);
                while (matcher.find()) {
                    column++;
                }

            } catch (BadLocationException ex) {
                Exceptions.printStackTrace(ex);
            }

            // Get section
            Section section = LexerUtils.getSection(document, caretOffset);

            // Get the package in configuration
            String packageBase = Utils.getPackageValue("package.base", null);
            String packageTarget = null;
            String filterSuperClass = null;
            String separator = "/";
            boolean onlyFolder = false;
            String onlyMimeType = null;

            String[] keywords = {};
            if (section != null) {

                if (section == Section.CONFIG) {
                    keywords = KEYWORDS_CONFIG;

                } else if (section == Section.ERRORS && column % 2 == 0) {
                    keywords = KEYWORDS_ERROR;
                    packageTarget = "";
                    filterSuperClass = "java.lang.Exception";

                } else if (section == Section.ERRORS && column % 2 == 1) {
                    keywords = KEYWORDS_ERROR_ACTION;

                    if (filter.startsWith("view:")) {
                        packageTarget = Utils.getPackageValue("package.views", null);

                    } else if (filter.startsWith("action:") || !filter.contains(":")) {
                        packageTarget = Utils.getPackageValue("package.errors", packageBase);
                        filterSuperClass = "org.debux.webmotion.server.WebMotionController";
                    }

                } else if (section == Section.EXTENSIONS && column % 2 == 0) {
                    keywords = KEYWORDS_EXTENSION;

                } else if (section == Section.EXTENSIONS && column % 2 == 1) {
                    packageTarget = "";
                    onlyMimeType = WebMotionLanguage.MIME_TYPE;

                } else if (section == Section.FILTERS && column % 3 == 0) {
                    keywords = KEYWORDS_METHODS;

                } else if (section == Section.FILTERS && column % 3 == 1) {
                    keywords = KEYWORDS_FILTER;

                } else if (section == Section.FILTERS && column % 3 == 2) {
                    keywords = KEYWORDS_FILTER_ACTION;
                    packageTarget = Utils.getPackageValue("package.filters", packageBase);
                    filterSuperClass = "org.debux.webmotion.server.WebMotionFilter";

                } else if (section == Section.ACTIONS && column % 3 == 0) {
                    keywords = KEYWORDS_METHODS;

                } else if (section == Section.ACTIONS && column % 3 == 1) {
                    keywords = KEYWORDS_ACTION;

                } else if (section == Section.ACTIONS && column % 3 == 2) {
                    keywords = KEYWORDS_ACTION_ACTION;

                    if (filter.startsWith("view:")) {
                        packageTarget = Utils.getPackageValue("package.views", null);

                    } else if (filter.startsWith("action:") || !filter.contains(":")) {
                        packageTarget = Utils.getPackageValue("package.actions", packageBase);
                        filterSuperClass = "org.debux.webmotion.server.WebMotionController";
                    }

                } else if (section == Section.PROPERTIES) {
                    keywords = KEYWORDS_SECTIONS;
                }

            } else {
                keywords = KEYWORDS_SECTIONS;
            }

            // Keywords
            if (keywords == KEYWORDS_METHODS && filter.contains(",")) {
                keywords = KEYWORDS_METHOD;
                startOffset += StringUtils.substringBeforeLast(filter, ",").length();
                filter = StringUtils.substringAfterLast(filter, ",");

            } else if (keywords == KEYWORDS_ERROR && filter.contains("code:")) {
                keywords = KEYWORDS_ERROR_CODE;
                startOffset += "code:".length();
                filter = filter.substring("code:".length());
                packageTarget = null;

            } else if (filter.startsWith("javac.debug=") || filter.startsWith("server.async=")
                    || filter.startsWith("server.static.autodetect=")) {
                keywords = KEYWORDS_CONFIG_BOOLEAN;
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=");

            } else if (filter.startsWith("server.error.page=")) {
                keywords = KEYWORDS_CONFIG_ERROR;
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=");

            } else if (filter.startsWith("server.controller.scope=")) {
                keywords = KEYWORDS_CONFIG_SCOPE;
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=");

            } else if (filter.startsWith("package.base=")) {
                keywords = KEYWORDS_EMPTY;
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=").replaceAll("\\.", "/");

                packageTarget = "";
                filterSuperClass = null;
                separator = ".";
                onlyFolder = true;

            } else if (filter.startsWith("package.views=")) {
                keywords = KEYWORDS_EMPTY;
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=").replaceAll("\\.", "/");

                packageTarget = "";
                filterSuperClass = null;
                separator = "/";
                onlyFolder = true;

            } else if (filter.startsWith("server.listener.class=")) {
                keywords = KEYWORDS_EMPTY;
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=");

                packageTarget = "";
                filterSuperClass = "org.debux.webmotion.server.WebMotionServerListener";

            } else if (filter.startsWith("server.main.handler.class=")) {
                keywords = KEYWORDS_EMPTY;
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=");

                packageTarget = "";
                filterSuperClass = "org.debux.webmotion.server.WebMotionHandler";

            } else if (filter.startsWith("default.render=")) {
                keywords = KEYWORDS_EMPTY;
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=");

                packageTarget = "";
                filterSuperClass = "org.debux.webmotion.server.render.Render";

            } else if (filter.startsWith("package.actions=") || filter.startsWith("package.filters=")
                    || filter.startsWith("package.errors=")) {
                keywords = KEYWORDS_EMPTY;
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=");

                packageTarget = Utils.getPackageValue("package.base", null);
                filterSuperClass = null;
                separator = ".";
                onlyFolder = true;

            } else if (filter.startsWith("server.encoding=")) {
                keywords = KEYWORDS_CONFIG_ENCODING;
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=");

            } else if (filter.startsWith("server.secret=")) {
                keywords = new String[] { RandomStringUtils.random(31, true, true) };
                startOffset += StringUtils.substringBefore(filter, "=").length() + 1;
                filter = StringUtils.substringAfter(filter, "=");

            } else if (filter.startsWith("javac.debug") || filter.startsWith("server.async")
                    || filter.startsWith("server.static.autodetect") || filter.startsWith("server.error.page")
                    || filter.startsWith("server.controller.scope") || filter.startsWith("package.base")
                    || filter.startsWith("package.views") || filter.startsWith("server.listener.class")
                    || filter.startsWith("server.main.handler.class") || filter.startsWith("package.actions")
                    || filter.startsWith("package.filters") || filter.startsWith("package.errors")
                    || filter.startsWith("server.encoding") || filter.startsWith("server.secret")) {

                keywords = KEYWORDS_CONFIG_EQUAL;
                startOffset += StringUtils.substringBefore(filter, "=").length();
                filter = "";
            }

            for (String keyword : keywords) {
                if (keyword.startsWith(filter)) {
                    completionResultSet.addItem(new WebMotionCompletionItem(keyword, startOffset, caretOffset));
                }
            }

            if (packageTarget != null) {

                // File
                if (filterSuperClass == null) {
                    String path = packageTarget.replaceAll("\\.", "/");
                    String filterFile = filter;
                    int startOffsetFile = startOffset;
                    Set<String> names = new HashSet<String>();

                    if (filter.startsWith("view:")) {
                        filterFile = filter.replaceFirst("view:", "");
                        startOffsetFile += "view:".length();
                    }

                    if (filterFile.contains("/")) {
                        String current = StringUtils.substringBeforeLast(filterFile, "/");
                        path += current;
                        startOffsetFile += current.length() + 1;
                        filterFile = StringUtils.substringAfterLast(filterFile, "/");

                    } else if (packageTarget.isEmpty() && separator.equals("/")) {
                        String fileName = "WEB-INF";
                        names.add(fileName);
                        if (fileName.startsWith(filterFile)) {
                            if (!fileName.equals(filterFile)) {
                                completionResultSet.addItem(
                                        new WebMotionCompletionItem(fileName, startOffsetFile, caretOffset));
                            } else {
                                completionResultSet.addItem(new WebMotionCompletionItem(separator,
                                        startOffsetFile + fileName.length(), caretOffset));
                            }
                        }
                    }

                    GlobalPathRegistry registry = GlobalPathRegistry.getDefault();
                    List<ClassPath> paths = new ArrayList<ClassPath>();
                    paths.addAll(registry.getPaths(ClassPath.BOOT));
                    paths.addAll(registry.getPaths(ClassPath.COMPILE));
                    paths.addAll(registry.getPaths(ClassPath.SOURCE));

                    for (ClassPath classPath : paths) {
                        FileObject resource = classPath.findResource(path);

                        if (resource != null) {
                            FileObject[] children = resource.getChildren();
                            for (FileObject child : children) {
                                String fileName = child.getNameExt();

                                if ((!onlyFolder || onlyFolder && child.isFolder())
                                        && (onlyMimeType == null || child.isFolder()
                                                || onlyMimeType != null
                                                        && child.getMIMEType().equals(onlyMimeType))
                                        && fileName.startsWith(filterFile) && !fileName.startsWith(".")) {

                                    if (!names.contains(fileName)) {
                                        if (!fileName.equals(filterFile)) {
                                            completionResultSet.addItem(new WebMotionCompletionItem(fileName,
                                                    startOffsetFile, caretOffset));
                                        } else {
                                            completionResultSet.addItem(new WebMotionCompletionItem(separator,
                                                    startOffsetFile + fileName.length(), caretOffset));
                                        }
                                        names.add(fileName);
                                    }
                                }
                            }
                        }
                    }
                    completionResultSet.finish();

                } else {

                    // Class
                    if (filter.contains(":") && !filter.startsWith("code:")) {
                        startOffset += StringUtils.substringBefore(filter, ":").length() + 1;
                        filter = StringUtils.substringAfter(filter, ":");
                    }

                    int startOffsetClass = startOffset;
                    if (filter.contains(".")) {
                        startOffsetClass += StringUtils.substringBeforeLast(filter, ".").length() + 1;
                    }

                    String fullName = packageTarget + filter;
                    String rootPackage = "";
                    String filerPackage = fullName;
                    if (fullName.contains(".")) {
                        rootPackage = StringUtils.substringBeforeLast(fullName, ".");
                        filerPackage = StringUtils.substringAfterLast(fullName, ".");
                    }

                    String folderPackage = rootPackage.replaceAll("\\.", "/");

                    FileObject fo = Utils.getFO(document);
                    ClassPath bootCp = ClassPath.getClassPath(fo, ClassPath.BOOT);
                    ClassPath compileCp = ClassPath.getClassPath(fo, ClassPath.COMPILE);
                    ClassPath sourcePath = ClassPath.getClassPath(fo, ClassPath.SOURCE);
                    ClasspathInfo info = ClasspathInfo.create(bootCp, compileCp, sourcePath);
                    JavaSource src = JavaSource.create(info);

                    final String filterSuperJavaClass = filterSuperClass;
                    final CompletionResultSet completionResultSetClass = completionResultSet;
                    final int startOffsetJavaClass = startOffsetClass;
                    final int caretOffsetClass = caretOffset;

                    // Package names
                    List<FileObject> folders = new ArrayList<FileObject>();
                    folders.addAll(bootCp.findAllResources(folderPackage));
                    folders.addAll(compileCp.findAllResources(folderPackage));
                    folders.addAll(sourcePath.findAllResources(folderPackage));

                    final String rootPackageFilter = rootPackage;
                    final String filterPackageFilter = filerPackage;
                    final Set<String> names = new HashSet<String>();
                    for (final FileObject folder : folders) {

                        try {
                            src.runUserActionTask(new CancellableTask<CompilationController>() {
                                @Override
                                public void cancel() {
                                }

                                @Override
                                public void run(CompilationController cu) throws Exception {
                                    Types types = cu.getTypes();
                                    Elements elements = cu.getElements();

                                    TypeElement superElement = elements.getTypeElement(filterSuperJavaClass);
                                    TypeMirror superType = null;
                                    if (superElement != null) {
                                        superType = superElement.asType();
                                    }

                                    FileObject[] children = folder.getChildren();
                                    for (FileObject child : children) {
                                        String name = child.getName();
                                        if (!name.startsWith(".") && name.startsWith(filterPackageFilter)) {

                                            if (!names.contains(name)) {
                                                names.add(name);

                                                TypeElement element;
                                                if (rootPackageFilter.isEmpty()) {
                                                    element = elements.getTypeElement(name);
                                                } else {
                                                    element = elements
                                                            .getTypeElement(rootPackageFilter + "." + name);
                                                }

                                                if (name.equals(filterPackageFilter)) {

                                                    if (element == null
                                                            || element.getKind() != ElementKind.CLASS
                                                            || element.getKind() == ElementKind.CLASS
                                                                    && (filterSuperJavaClass.equals(
                                                                            "org.debux.webmotion.server.WebMotionFilter")
                                                                            || filterSuperJavaClass.equals(
                                                                                    "org.debux.webmotion.server.WebMotionController"))) {

                                                        WebMotionCompletionItem item = new WebMotionCompletionItem(
                                                                ".", startOffsetJavaClass + name.length(),
                                                                caretOffsetClass);
                                                        completionResultSetClass.addItem(item);
                                                    }

                                                } else if (child.isFolder()) {
                                                    WebMotionCompletionItem item = new WebMotionCompletionItem(
                                                            name, startOffsetJavaClass, caretOffsetClass);
                                                    completionResultSetClass.addItem(item);

                                                } else if (element != null) {
                                                    Set<Modifier> modifiers = element.getModifiers();
                                                    ElementKind kind = element.getKind();
                                                    TypeMirror resolveType = element.asType();

                                                    if (kind == ElementKind.CLASS
                                                            && modifiers.contains(Modifier.PUBLIC)
                                                            && !modifiers.contains(Modifier.ABSTRACT)
                                                            && superType != null
                                                            && types.isSubtype(resolveType, superType)) {

                                                        WebMotionCompletionItem item = new WebMotionCompletionItem(
                                                                name, cu, element, startOffsetJavaClass,
                                                                caretOffsetClass);
                                                        completionResultSetClass.addItem(item);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }, false);

                        } catch (IOException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }

                    // Method
                    if (filter.contains(".") && (filterSuperJavaClass
                            .equals("org.debux.webmotion.server.WebMotionFilter")
                            || filterSuperJavaClass.equals("org.debux.webmotion.server.WebMotionController"))) {

                        final String className = StringUtils.substringBeforeLast(filter, ".");
                        final String fullClassName = packageTarget + className;
                        final String filterMethod = StringUtils.substringAfterLast(filter, ".");

                        final CompletionResultSet completionResultSetJavaSource = completionResultSet;
                        final int startOffsetJavaSource = startOffset + className.length() + 1;
                        final int caretOffesetJavaSource = caretOffset;

                        try {
                            src.runUserActionTask(new CancellableTask<CompilationController>() {

                                @Override
                                public void cancel() {
                                }

                                @Override
                                public void run(CompilationController cu) throws Exception {
                                    cu.toPhase(JavaSource.Phase.PARSED);

                                    Elements elements = cu.getElements();
                                    TypeElement classElement = elements.getTypeElement(fullClassName);
                                    if (classElement != null) {

                                        List<? extends javax.lang.model.element.Element> members = elements
                                                .getAllMembers(classElement);
                                        for (javax.lang.model.element.Element member : members) {
                                            if (member.getKind() == ElementKind.METHOD) {

                                                Set<Modifier> modifiers = member.getModifiers();
                                                String methodName = member.getSimpleName().toString();
                                                String className = member.getEnclosingElement().getSimpleName()
                                                        .toString();

                                                if (!"Object".equals(className)
                                                        && !"WebMotionController".equals(className)
                                                        && !"WebMotionFilter".equals(className)
                                                        && modifiers.contains(Modifier.PUBLIC)
                                                        && !modifiers.contains(Modifier.STATIC)
                                                        && methodName.startsWith(filterMethod)) {

                                                    WebMotionCompletionItem item = new WebMotionCompletionItem(
                                                            methodName, cu, member, startOffsetJavaSource,
                                                            caretOffesetJavaSource);
                                                    completionResultSetJavaSource.addItem(item);
                                                }
                                            }
                                        }
                                    }

                                    completionResultSetJavaSource.finish();
                                }
                            }, false);
                        } catch (IOException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    } else {
                        completionResultSet.finish();
                    }
                }

            } else {
                completionResultSet.finish();
            }
        }
    }, component);
}

From source file:org.devproof.portal.core.module.common.component.ExtendedLabel.java

private IModel<String> createConvertedContentModel() {
    return new LoadableDetachableModel<String>() {
        private static final long serialVersionUID = -3507047529867991441L;

        @Override//from  w w w  .  j  a  v a2  s.co  m
        protected String load() {
            cleanupExpiredImages();
            String modifiedContent = contentModel.getObject();
            String tagParts[] = StringUtils.substringsBetween(modifiedContent, PRETAG, POSTTAG);
            if (tagParts != null) {
                for (String tagPart : tagParts) {
                    String fullTag = PRETAG + tagPart + POSTTAG;
                    String splittedAttribute[] = StringUtils
                            .split(StringUtils.substringBefore(fullTag, CLOSE_SEP), "= ");
                    int fontSize = getFontSize(splittedAttribute);
                    List<String> str2ImgLines = getTextLines(tagPart);
                    Font font = getFont(fontSize);
                    ImgResourceReference imgResource = getImageResourceAndCache(str2ImgLines, font);
                    modifiedContent = replaceTagWithImage(modifiedContent, fullTag, imgResource);
                }
            }
            return modifiedContent;
        }
    };
}

From source file:org.devproof.portal.module.article.entity.Article.java

private List<String> getSplittedPages(String pages) {
    String[] splitted = StringUtils.splitByWholeSeparator(pages, "page-break-after");
    List<String> result = new ArrayList<String>();
    if (splitted.length > 1) {
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < splitted.length; i++) {
            String actual = splitted[i];
            int open = actual.lastIndexOf('<');
            int close = actual.lastIndexOf('>');
            if (open < 0 || close > open) {
                // kein tag
                buf.append(actual);//from   w  ww . j a  va2  s . c o  m
                if (splitted.length - 1 != i)
                    buf.append("page-break-after");
            } else {
                // tag
                buf.append(StringUtils.substringBeforeLast(actual, "<"));
                result.add(buf.toString());
                buf = new StringBuilder();
                String closeTag = StringUtils.substringAfterLast(actual, "<");
                closeTag = "</" + StringUtils.substringBefore(closeTag, " ") + ">";
                splitted[i + 1] = StringUtils.substringAfter(splitted[i + 1], closeTag);
            }
        }
        if (buf.length() > 0) {
            result.add(buf.toString());
        }
    } else {
        result.add(pages);
    }
    return result;
}

From source file:org.displaytag.filter.BufferedResponseWrapper12Impl.java

/**
 * The content type is NOT set on the wrapped response. You must set it manually. Overrides any previously set
 * value./*from   w  w  w.  j  a  v  a 2s .  c om*/
 * @param theContentType the content type.
 */
public void setContentType(String theContentType) {
    if (state) {
        log.debug("Allowing content type");

        if (this.contentType != null && // content type has been set before
                this.contentType.indexOf("charset") > -1) // and it specified charset
        {
            // so copy the charset
            String charset = this.contentType.substring(this.contentType.indexOf("charset"));
            if (log.isDebugEnabled()) {
                log.debug("Adding charset: [" + charset + "]");
            }

            getResponse()
                    .setContentType(StringUtils.substringBefore(theContentType, "charset") + ' ' + charset);
        } else {
            getResponse().setContentType(theContentType);
        }

    }
    this.contentType = theContentType;
}

From source file:org.drools.lang.dsl.template.Chunk.java

void process(final String expression) {
    if (this.isHole) {
        //value = text until next next.text is found
        if (this.next == null || this.next.text == null) {
            storeSpacePadding(expression);
            this.value = expression.trim();
        } else {//from w  w  w .  ja  v  a  2 s .  co  m
            final String val = StringUtils.substringBefore(expression, this.next.text);
            storeSpacePadding(val);
            this.value = val.trim();
        }

    } else {
        this.value = this.text;
    }
    if (this.next != null) {
        this.next.process(StringUtils.substringAfter(expression, this.value));
    }
}

From source file:org.dspace.app.xmlui.cocoon.servlet.multipart.DSpaceMultipartParser.java

/**
 * Read part headers/*  www .jav a  2  s .co  m*/
 *
 * @param in
 *
 * @throws java.io.IOException
 */
private Hashtable readHeaders(DSpaceTokenStream in) throws IOException {

    Hashtable headers = new Hashtable();
    String hdrline = readln(in);

    while (!"".equals(hdrline)) {
        String name = StringUtils.substringBefore(hdrline, ": ").toLowerCase();
        String value;
        if (hdrline.contains(";")) {
            value = StringUtils.substringBetween(hdrline, ": ", "; ");
        } else {
            value = StringUtils.substringAfter(hdrline, ": ");
        }

        headers.put(name, value);

        hdrline = StringUtils.substringAfter(hdrline, ";");

        // The extra tokenizer.hasMoreTokens() hdrline headers.put
        // handles the filename="" case IE6 submits for an empty
        // upload field.
        while (0 < hdrline.length()) {
            name = StringUtils.substringBetween(hdrline, " ", "=");
            if (hdrline.contains("; ")) {
                value = StringUtils.substringBetween(hdrline, "=\"", "\";");
                hdrline = StringUtils.substringAfter(hdrline, ";");
            } else {
                value = StringUtils.substringBetween(hdrline, "=\"", "\"");
                hdrline = "";
            }

            headers.put(name, value);
        }

        hdrline = readln(in);
    }

    return headers;
}