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

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

Introduction

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

Prototype

public static String chomp(String str, String separator) 

Source Link

Document

Removes separator from the end of str if it's there, otherwise leave it alone.

Usage

From source file:org.carewebframework.smart.ui.SmartContainer2.java

/**
 * Return query string for the SMART plugin.
 * /*  w ww.j  ava 2 s.  c  o m*/
 * @return The query string.
 */
private String getQueryString() {
    QueryStringBuilder sb = new QueryStringBuilder();

    for (ContextMap context : _context.values()) {
        String param = (String) context.get("param");

        if (param != null) {
            sb.append(param, context.get("id"));
        }
    }

    if (sb.length() > 0) {
        sb.append("fhirServiceUrl", StringUtils.chomp(SpringUtil.getProperty("fhir.service.root.url"), "/"));
    }

    return sb.toString();
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.XstreamPathConverter.java

protected boolean doBasicPathsMatch(final Path path1, final Path path2) {
    if (path1.equals(path2)) {
        return true;
    }//w w  w . ja  va 2s .  c  o m
    // ignore count designators and attribute specifications whenc omparing paths
    // ie, /a/b[3]/c/@foo for our purposes is equivalent to /a/b/c

    String path1Relpaced = StringUtils
            .chomp(path1.toString().replaceAll("\\[.*\\]", "").replaceAll("/@.*$", ""), "/");
    String path2Replaced = StringUtils
            .chomp(path2.toString().replaceAll("\\[.*\\]", "").replaceAll("/@.*$", ""), "/");

    return path1Relpaced.equals(path2Replaced);

}

From source file:org.eclipse.wb.core.gef.MatchingEditPartFactory.java

/**
 * Implementation for {@link #createEditPart(Object, Class)}, with single model suffix.
 *//*from w  w w . ja va 2s. c  om*/
private EditPart createEditPart(Object model, Class<?> modelClass, String modelClassName, String modelSuffix) {
    // check each model/part packages pair
    for (int i = 0; i < m_modelPackages.size(); i++) {
        String modelPackage = m_modelPackages.get(i);
        String partPackage = m_partPackages.get(i);
        if (modelClassName.startsWith(modelPackage) && modelClassName.endsWith(modelSuffix)) {
            // prepare name of component, strip model package and "Info" suffix
            String componentName = modelClassName;
            componentName = componentName.substring(modelPackage.length());
            componentName = StringUtils.chomp(componentName, modelSuffix);
            // create corresponding EditPart, use "EditPart" prefix
            {
                String partClassName = partPackage + componentName + "EditPart";
                EditPart editPart = createEditPart0(model, modelClass, partClassName);
                if (editPart != null) {
                    return editPart;
                }
            }
        }
    }
    // not found
    return null;
}

From source file:org.eclipse.wb.internal.core.utils.jdt.core.CodeUtils.java

/**
 * @return primary {@link IType} in given {@link ICompilationUnit}, i.e. type with name of unit.
 *         Can return <code>null</code> if no such type found.
 *///from ww  w .j  a  va2  s .  co  m
public static IType findPrimaryType(ICompilationUnit compilationUnit) {
    String unitName = compilationUnit.getElementName();
    String typeName = StringUtils.chomp(unitName, ".java");
    IType primaryType = compilationUnit.getType(typeName);
    if (primaryType.exists()) {
        return primaryType;
    }
    return null;
}

From source file:org.eclipse.wb.internal.swing.laf.LafUtils.java

/**
 * Opens given <code>jarFile</code>, loads every class inside own {@link ClassLoader} and checks
 * loaded class for to be instance of {@link LookAndFeel}. Returns the array of {@link LafInfo}
 * containing all found {@link LookAndFeel} classes.
 * //ww  w . j  av a 2  s.  c  o  m
 * @param jarFileName
 *          the absolute OS path pointing to source JAR file.
 * @param monitor
 *          the progress monitor which checked for interrupt request.
 * @return the array of {@link UserDefinedLafInfo} containing all found {@link LookAndFeel}
 *         classes.
 */
public static UserDefinedLafInfo[] scanJarForLookAndFeels(String jarFileName, IProgressMonitor monitor)
        throws Exception {
    List<UserDefinedLafInfo> lafList = Lists.newArrayList();
    File jarFile = new File(jarFileName);
    URLClassLoader ucl = new URLClassLoader(new URL[] { jarFile.toURI().toURL() });
    JarFile jar = new JarFile(jarFile);
    Enumeration<?> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = (JarEntry) entries.nextElement();
        String entryName = entry.getName();
        if (entry.isDirectory() || !entryName.endsWith(".class") || entryName.indexOf('$') >= 0) {
            continue;
        }
        String className = entryName.replace('/', '.').replace('\\', '.');
        className = className.substring(0, className.lastIndexOf('.'));
        Class<?> clazz = null;
        try {
            clazz = ucl.loadClass(className);
        } catch (Throwable e) {
            continue;
        }
        // check loaded class to be a non-abstract subclass of javax.swing.LookAndFeel class
        if (LookAndFeel.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) {
            // use the class name as name of LAF
            String shortClassName = CodeUtils.getShortClass(className);
            // strip trailing "LookAndFeel"
            String lafName = StringUtils.chomp(shortClassName, "LookAndFeel");
            lafList.add(new UserDefinedLafInfo(StringUtils.isEmpty(lafName) ? shortClassName : lafName,
                    className, jarFileName));
        }
        // check for Cancel button pressed
        if (monitor.isCanceled()) {
            return lafList.toArray(new UserDefinedLafInfo[lafList.size()]);
        }
        // update ui
        while (DesignerPlugin.getStandardDisplay().readAndDispatch()) {
        }
    }
    return lafList.toArray(new UserDefinedLafInfo[lafList.size()]);
}

From source file:org.gbif.portal.harvest.workflow.activity.taxonomy.RankAndScientificNameHandlerActivity.java

/**
 * @see org.gbif.portal.util.workflow.Activity#execute(org.gbif.portal.util.workflow.ProcessContext)
 *//*from  www .  j a  va  2s .  c o m*/
@SuppressWarnings("unchecked")
public ProcessContext execute(ProcessContext context) throws Exception {
    String rankString = (String) context.get(getContextKeyRank(), String.class, false);
    if (rankString != null) {
        Integer rank = taxonRankMapping.mapToCode(StringUtils.chomp(rankString, "."));
        if (rank == null) {
            StringBuffer sb = new StringBuffer();
            sb.append(rankString);
            sb.append(": rank string not mapped");

            if (getContextKeyRawOccurrenceRecord() != null) {
                RawOccurrenceRecord ror = (RawOccurrenceRecord) context.get(getContextKeyRawOccurrenceRecord(),
                        RawOccurrenceRecord.class, false);
                if (ror != null) {
                    sb.append(" raw occurrence record: ");
                    sb.append(ror.getId());
                    if (ror.getCollectionCode() != null) {
                        sb.append("; collection code: ");
                        sb.append(ror.getCollectionCode());
                    }
                    if (ror.getInstitutionCode() != null) {
                        sb.append("; catalogue number: ");
                        sb.append(ror.getInstitutionCode());
                    }
                    if (ror.getCatalogueNumber() != null) {
                        sb.append("; catalogue number: ");
                        sb.append(ror.getCatalogueNumber());
                    }
                }
            }
            GbifLogMessage message = gbifLogUtils.createGbifLogMessage(context,
                    LogEvent.EXTRACT_TAXONRANKPARSEISSUE, sb.toString());
            message.setCountOnly(true);
            logger.error(message);
            throw new UnknownRankException("Could not find a mapping for rank string: " + rankString);
        }
        context.put(getContextKeyParsedRank(), rank);
        String contextKey = (String) ranksToNameContextKeys.get(rank.toString());
        if (contextKey != null && !contextKey.equals(getContextKeyScientificName())) {
            String scientificName = (String) context.get(getContextKeyScientificName(), String.class, false);
            // If the name is of species rank or lower and starts with an upper case
            // character, assume it is a full scientific name
            if (scientificName != null && (rank < 7000 || Character.isLowerCase(scientificName.charAt(0)))) {
                String rankValue = (String) context.get(contextKey, String.class, false);
                if (rankValue == null) {
                    context.put(contextKey, scientificName);
                    context.remove(getContextKeyScientificName());
                }
            }
        }
        contextKey = (String) ranksToAuthorContextKeys.get(rank.toString());
        if (contextKey != null && !contextKey.equals(getContextKeyAuthor())) {
            String author = (String) context.get(getContextKeyAuthor(), String.class, false);
            if (author != null) {
                String rankValue = (String) context.get(contextKey, String.class, false);
                if (rankValue == null) {
                    context.put(contextKey, author);
                    context.remove(getContextKeyAuthor());
                }
            }
        }
        String infraspecificMarker = (String) ranksToInfraspecificMarkers.get(rank);
        if (infraspecificMarker != null) {
            String currentMarker = (String) context.get(getContextKeyInfraspecificMarker(), String.class,
                    false);
            if (currentMarker == null) {
                context.put(getContextKeyInfraspecificMarker(), infraspecificMarker);
            }
        }
    }
    return context;
}

From source file:org.hspconsortium.cwf.api.smart.SmartContextService.java

private String getServiceRoot() {
    if (serviceRoot == null) {
        serviceRoot = StringUtils.isEmpty(smartServiceRoot) ? fhirServiceRoot : smartServiceRoot;
        serviceRoot = StringUtils.chomp(serviceRoot, "/");

        if (StringUtils.isEmpty(serviceRoot)) {
            throw new IllegalArgumentException("No service root url defined for SMART.");
        }/*ww  w.ja  v  a 2  s .  co  m*/
    }

    return serviceRoot;
}

From source file:org.intermine.webservice.server.ServiceListingHandler.java

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {

    final String[] lines = sb.toString().replace("\n", "").trim().split("\n");
    StringBuffer contentBuffer = new StringBuffer();
    for (String line : lines) {
        contentBuffer.append(line.replaceAll("^ +", "") + "\n");
    }//from   w ww.ja  v a 2s .c o m
    final String content = contentBuffer.toString().trim();

    if ("servlet-mapping".equals(qName)) {
        currentEndPoint = null;
    } else if ("url-pattern".equals(qName)) {
        if (currentEndPoint != null) {
            currentEndPoint.put("URI", StringUtils.chomp(content, "/*"));
        }
    } else if ("content".equals(qName)) {
        if (currentContentType != null) {
            // Don't trim and reflow text for bodies, but do de-indent it.
            currentContentType.put("example", deIndent(sb.toString()));
        }
        currentContentType = null;
    } else if ("body".equals(qName)) {
        if (bodyFormats != null && !bodyFormats.isEmpty()) {
            currentMethod.put("body", bodyFormats);
            currentMethod.put("bodyDescription", bodyDescription);
        }
        bodyFormats = null;
        bodyDescription = null;
    } else if ("servlet-name".equals(qName)) {
        if (content.startsWith("ws-") && currentEndPoint != null) {
            endpoints.add(currentEndPoint);
            currentEndPoint.put("name", content);
            currentEndPoint.put("identifier", content);
        }
    } else if ("name".equals(qName)) {
        if (path.contains("method")) {
            currentMethod.put("MethodName", content);
        } else if (path.contains("metadata")) {
            currentEndPoint.put("name", content);
        }
    } else if ("param".equals(qName)) {
        currentParam.put("Name", content);
        if (!currentParam.containsKey("Default")) {
            // Resolve configured default, if possible and not already set.
            String configuredDefault = webProperties
                    .getProperty(String.format(DEFAULT_PROP_FMT, currentEndPoint.get("URI"), content));
            if (configuredDefault != null) {
                currentParam.put("Default", configuredDefault);
            }
        }
        currentParam = null;
    } else if ("format".equals(qName)) {
        format.put("Name", content);
        format = null;
    } else if ("summary".equals(qName)) {
        currentMethod.put("Synopsis", content);
    } else if ("description".equals(qName)) {
        currentMethod.put("Description", deIndent(sb.toString()));
    } else if ("minVersion".equals(qName)) {
        Integer minVersion = Integer.valueOf(content);
        currentEndPoint.put("minVersion", minVersion);
    } else if ("returns".equals(qName)) {
        if (returns.size() > 1) {
            Map<String, Object> formatParam = new HashMap<String, Object>();
            formatParam.put("Name", "format");
            formatParam.put("Required", "N");
            formatParam.put("Default", returns.get(0).get("Name"));
            formatParam.put("Type", "enumerated");
            formatParam.put("Description", "Output format");
            List<String> formatValues = new ArrayList<String>();
            // TODO: interpret accept info into header options here.
            for (Map<String, Object> map : returns) {
                formatValues.add(String.valueOf(map.get("Name")));
            }
            formatParam.put("EnumeratedList", formatValues);
            params.add(formatParam);
        }
        returns = null;
    } else if ("method".equals(qName)) {
        if (currentMethod.containsKey("ALSO")) {
            String[] otherMethods = String.valueOf(currentMethod.get("ALSO")).split(",");
            for (String m : otherMethods) {
                Map<String, Object> aliasMethod = new HashMap<String, Object>(currentMethod);
                aliasMethod.put("HTTPMethod", m);
                methods.add(aliasMethod);
            }
        }
        currentMethod = null;
    }

    path.pop();
}

From source file:org.intermine.webservice.server.ServicesListingsServlet.java

private DefaultHandler getHandler() {
    DefaultHandler handler = new DefaultHandler() {
        private final Map<String, Object> result = new HashMap<String, Object>();
        private final List<Map<String, Object>> endpoints = new ArrayList<Map<String, Object>>();
        private Map<String, Object> currentEndPoint = null;
        private List<Map<String, Object>> methods = null;
        private Map<String, Object> currentMethod = null;
        private List<Map<String, Object>> params = null;
        private Map<String, Object> currentParam = null;
        private List<Map<String, Object>> returns = null;
        private Map<String, Object> format = null;
        private List<Map<String, Object>> bodyFormats = null;
        private String bodyDescription = null;
        private Map<String, Object> currentContentType = null;
        private Stack<String> path = new Stack<String>();
        private StringBuffer sb = null;
        private Properties webProperties = InterMineContext.getWebProperties();
        private static final String DEFAULT_PROP_FMT = "ws.listing.default.%s.%s";

        public void startDocument() {
            result.put("endpoints", endpoints);
        }/*from   ww w  .ja v a 2 s .  c  o m*/

        public void endDocument() {
            services = new JSONObject(result);
        }

        private void addToCurrentMethod(String key, Object value) throws SAXException {
            if (currentMethod == null) {
                throw new SAXException("Illegal document structure");
            }
            currentMethod.put(key, value);
        }

        private String deIndent(String input) {
            if (input == null) {
                return null;
            }
            input = input.replaceAll("^\\n", "").replaceAll("\\t", "    ");
            if (!input.startsWith(" ")) {
                return input;
            }
            int i = 1;
            while (input.charAt(i) == ' ') {
                i++;
            }
            String regex = "(?m)^\\s{" + i + "}";
            return input.replaceAll(regex, "");
        }

        public void startElement(String uri, String localName, String qName, Attributes attrs)
                throws SAXException {
            path.push(qName);
            if ("servlet-mapping".equals(qName)) {
                currentEndPoint = new HashMap<String, Object>();
                methods = new ArrayList<Map<String, Object>>();
                currentEndPoint.put("methods", methods);
            } else if ("returns".equals(qName)) {
                returns = new ArrayList<Map<String, Object>>();
                addToCurrentMethod("returnFormats", returns);
            } else if ("method".equals(qName)) {
                currentMethod = new HashMap<String, Object>();
                addToCurrentMethod("URI",
                        String.valueOf(currentEndPoint.get("URI")).replaceAll("^/service", ""));
                addToCurrentMethod("HTTPMethod", attrs.getValue("type"));
                addToCurrentMethod("RequiresAuthentication", attrs.getValue("authenticationRequired"));
                final String slug = attrs.getValue("slug");
                if (slug != null) {
                    addToCurrentMethod("URI", currentMethod.get("URI") + slug);
                }
                final String also = attrs.getValue("ALSO");
                if (also != null) {
                    addToCurrentMethod("ALSO", also);
                }
                params = new ArrayList<Map<String, Object>>();
                currentMethod.put("parameters", params);
                methods.add(currentMethod);
            } else if ("body".equals(qName)) {
                bodyDescription = attrs.getValue("description");
                bodyFormats = new LinkedList<Map<String, Object>>();
            } else if ("content".equals(qName)) {
                currentContentType = new HashMap<String, Object>();
                currentContentType.put("contentType", attrs.getValue("type"));
                currentContentType.put("schema", attrs.getValue("schema"));
                bodyFormats.add(currentContentType);
            } else if ("param".equals(qName)) {
                currentParam = new HashMap<String, Object>();
                currentParam.put("Required", Boolean.valueOf(attrs.getValue("required")) ? "Y" : "N");
                currentParam.put("Type", attrs.getValue("type"));
                currentParam.put("Description", attrs.getValue("description"));
                currentParam.put("Schema", attrs.getValue("schema"));
                String defaultValue = attrs.getValue("default");
                if (defaultValue != null) {
                    currentParam.put("Default", defaultValue);
                }
                if ("enumerated".equals(currentParam.get("Type"))) {
                    currentParam.put("EnumeratedList", Arrays.asList(attrs.getValue("values").split(",")));
                }
                params.add(currentParam);
            } else if ("format".equals(qName)) {
                format = new HashMap<String, Object>();
                int attrLen = attrs.getLength();
                for (int i = 0; i < attrLen; i++) {
                    String ln = attrs.getLocalName(i);
                    format.put(ln, attrs.getValue(i));
                }
                returns.add(format);
            }
            sb = new StringBuffer();
        }

        public void endElement(String uri, String localName, String qName) throws SAXException {

            final String content = sb.toString().replace("\n", "").trim().replaceAll(" +", " ");

            if ("servlet-mapping".equals(qName)) {
                currentEndPoint = null;
            } else if ("url-pattern".equals(qName)) {
                if (currentEndPoint != null) {
                    currentEndPoint.put("URI", StringUtils.chomp(content, "/*"));
                }
            } else if ("content".equals(qName)) {
                if (currentContentType != null) {
                    // Don't trim and reflow text for bodies, but do de-indent it.
                    currentContentType.put("example", deIndent(sb.toString()));
                }
                currentContentType = null;
            } else if ("body".equals(qName)) {
                if (bodyFormats != null && !bodyFormats.isEmpty()) {
                    currentMethod.put("body", bodyFormats);
                    currentMethod.put("bodyDescription", bodyDescription);
                }
                bodyFormats = null;
                bodyDescription = null;
            } else if ("servlet-name".equals(qName)) {
                if (content.startsWith("ws-") && currentEndPoint != null) {
                    endpoints.add(currentEndPoint);
                    currentEndPoint.put("name", content);
                    currentEndPoint.put("identifier", content);
                }
            } else if ("name".equals(qName)) {
                if (path.contains("method")) {
                    currentMethod.put("MethodName", content);
                } else if (path.contains("metadata")) {
                    currentEndPoint.put("name", content);
                }
            } else if ("param".equals(qName)) {
                currentParam.put("Name", content);
                if (!currentParam.containsKey("Default")) {
                    // Resolve configured default, if possible and not already set.
                    String configuredDefault = webProperties
                            .getProperty(String.format(DEFAULT_PROP_FMT, currentEndPoint.get("URI"), content));
                    if (configuredDefault != null) {
                        currentParam.put("Default", configuredDefault);
                    }
                }
                currentParam = null;
            } else if ("format".equals(qName)) {
                format.put("Name", content);
                format = null;
            } else if ("summary".equals(qName)) {
                currentMethod.put("Synopsis", content);
            } else if ("description".equals(qName)) {
                currentMethod.put("Description", content);
            } else if ("minVersion".equals(qName)) {
                Integer minVersion = Integer.valueOf(content);
                currentEndPoint.put("minVersion", minVersion);
            } else if ("returns".equals(qName)) {
                if (returns.size() > 1) {
                    Map<String, Object> formatParam = new HashMap<String, Object>();
                    formatParam.put("Name", "format");
                    formatParam.put("Required", "N");
                    formatParam.put("Default", returns.get(0).get("Name"));
                    formatParam.put("Type", "enumerated");
                    formatParam.put("Description", "Output format");
                    List<String> formatValues = new ArrayList<String>();
                    // TODO: interpret accept info into header options here.
                    for (Map<String, Object> map : returns) {
                        formatValues.add(String.valueOf(map.get("Name")));
                    }
                    formatParam.put("EnumeratedList", formatValues);
                    params.add(formatParam);
                }
                returns = null;
            } else if ("method".equals(qName)) {
                if (currentMethod.containsKey("ALSO")) {
                    String[] otherMethods = String.valueOf(currentMethod.get("ALSO")).split(",");
                    for (String m : otherMethods) {
                        Map<String, Object> aliasMethod = new HashMap<String, Object>(currentMethod);
                        aliasMethod.put("HTTPMethod", m);
                        methods.add(aliasMethod);
                    }
                }
                currentMethod = null;
            }

            path.pop();
        }

        public void characters(char[] ch, int start, int length) throws SAXException {
            sb.append(ch, start, length);
        }
    };
    return handler;
}

From source file:org.jahia.utils.maven.plugin.contentgenerator.wise.WiseService.java

private List<String> getFilePaths(List<FolderBO> folders) {
    List<String> filePaths = new ArrayList<String>();
    if (CollectionUtils.isNotEmpty(folders)) {
        for (FolderBO folder : folders) {
            filePaths.addAll(getFilePaths(folder.getSubFolders()));

            for (FileBO file : folder.getFiles()) {
                String nodePath = StringUtils.chomp(file.getNodePath(), "/");
                filePaths.add(nodePath);
            }//from   w  w  w. j  a v a 2s  .c  o m
        }
    }
    return filePaths;
}