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

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

Introduction

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

Prototype

public static int countMatches(String str, String sub) 

Source Link

Document

Counts how many times the substring appears in the larger String.

Usage

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.TypeLibraryUtil.java

/**
 * Checks if is new style base location.
 *
 * @param baseLocationStr the base location str
 * @return true, if is new style base location
 *///from  www.  j a va 2 s. c om
public static boolean isNewStyleBaseLocation(String baseLocationStr) {
    return !(StringUtils.countMatches(
            StringUtils.substringAfterLast(baseLocationStr, SOATypeLibraryConstants.FOLDER_META_SRC_TYPES),
            WorkspaceUtil.PATH_SEPERATOR) == 1);
}

From source file:org.ebayopensource.turmeric.eclipse.typelibrary.ui.wst.WTPCopyUtil.java

private static void updatePrefixes(Element element, Map<String, String> prefixMap) {
    NamedNodeMap namedNodeMap = element.getAttributes();
    for (int i = 0; i < namedNodeMap.getLength(); i++) {
        String attrValue = namedNodeMap.item(i).getNodeValue();
        String attrName = namedNodeMap.item(i).getNodeName();
        for (String str : prefixMap.keySet()) {
            if (StringUtils.isNotEmpty(attrValue) && attrValue.trim().startsWith(str + ":")) {
                String trimmedAttrValue = attrValue.trim();
                String newAttrValue = trimmedAttrValue;
                if (trimmedAttrValue.startsWith(str + ":xs:")) {
                    newAttrValue = StringUtils.replaceOnce(trimmedAttrValue, str + ":xs:", "xs:");
                } else if (StringUtils.countMatches(trimmedAttrValue, ":") == 2) {
                    //already contains a prefix
                    trimmedAttrValue = StringUtils.substringAfter(trimmedAttrValue, ":");
                    String oldPrefix = StringUtils.substringBefore(trimmedAttrValue, ":");
                    newAttrValue = StringUtils.replaceOnce(trimmedAttrValue, oldPrefix + ":",
                            prefixMap.get(oldPrefix) + ":");
                } else {
                    newAttrValue = StringUtils.replaceOnce(trimmedAttrValue, str + ":",
                            prefixMap.get(str) + ":");
                }/*from  w w  w .ja  v  a  2 s . c  o m*/
                element.getAttributeNode(attrName).setValue(newAttrValue);
            }
        }
    }
    NodeList children = element.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node child = children.item(i);
        if (child instanceof Element)
            updatePrefixes((Element) child, prefixMap);
    }
}

From source file:org.eclipse.mdht.uml.cda.core.util.CDACommonUtils.java

/**
 * @param element//from w  w  w  .  j av  a2  s.c  o  m
 * @param fullSection
 *            whether to return the full section number or only the last digit
 * @return
 */
static public String getPDFSection(Element element, boolean fullSection, boolean level2) {
    int incr = Integer.getInteger("MDHT_SECTION_INCREMENT", 0);
    if (incr == 0 && element.eResource() != null && element.eResource().getResourceSet() != null) {
        Resource resource = element.eResource().getResourceSet().getResources().get(0);
        String uri = resource.getURI().toString();
        int index = uri.indexOf(".model/");
        if (index != -1) {
            try {
                uri = uri.substring(0, index) + ".doc/dita/spec-book.ditamap";
                InputStream inputStream = new URL(uri).openConnection().getInputStream();
                String specBook = CDACommonUtils.toString(inputStream);
                index = specBook.indexOf("<chapter format=\"ditamap\" href=\"content/content.ditamap\"/>");
                if (index != -1) {
                    incr = StringUtils.countMatches(specBook.substring(0, index), "<chapter") - 1;
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }
    }
    String result = "";
    EObject eObject = element;
    while (eObject != null && !(eObject instanceof Package)) {
        String step = "?";
        if (eObject instanceof Class) {
            Class class1 = (Class) eObject;
            int mainSection = getMainSection(class1);
            if (mainSection != -1) {
                step = (mainSection + incr) + "." + (getCDAContents(class1).indexOf(class1) + 1);
                if (!fullSection || level2) {
                    return step + " " + CDACommonUtils.getBusinessName(class1);
                } else if (fullSection) {
                    result = step + "." + result;
                    break;
                }
            } else {
                Property property = getOverallPropertyReference(class1);
                if (property != null) {
                    step = getPropertyStep(getClassReference(property), property);

                }
            }
        } else if (eObject instanceof Constraint
                && CDACommonUtils.getParentingProperty((Constraint) eObject) != null) {
            Property prop = CDACommonUtils.getParentingProperty((Constraint) eObject);
            if (prop.getType() instanceof Class && getMainSection((Class) prop.getType()) == -1) {
                Class class1 = (Class) prop.getType();
                step = getPropertyStep(class1, class1);
            } else {
                step = getCustomizedBulletItem(prop, 0);
            }
            eObject = prop;
            result = step + "." + result;
            continue;
        } else if (eObject instanceof NamedElement && getContainerReference(eObject) instanceof Class) {
            NamedElement property = (NamedElement) eObject;
            Class parentClass = (Class) getContainerReference(eObject);
            step = getPropertyStep(parentClass, property);
        } else if (eObject instanceof Enumeration && getContainerReference(eObject) instanceof Package) {
            Package package1 = (Package) getContainerReference(eObject);
            Enumeration enumeration = (Enumeration) eObject;
            return "6." + (package1.getPackagedElements().indexOf(eObject) + 1) + " " + enumeration.getName();
        } else if (eObject instanceof EnumerationLiteral) {
            EnumerationLiteral enumerationLiteral = (EnumerationLiteral) eObject;
            return enumerationLiteral.getName();
        }
        if (!fullSection) {
            return step + ".";
        }
        result = step + "." + result;
        if (!fullSection) {
            return step;
        }
        eObject = getContainerReference(eObject);
    }
    return result.endsWith(".") ? result.substring(0, result.length() - 1) : result;
}

From source file:org.eclipse.mylyn.internal.gerrit.core.GerritUtil.java

public static String toChangeId(String id) {
    if (StringUtils.countMatches(id, String.valueOf('~')) == 2) {
        // project~branch~change_id in Gerrit 2.6 and later
        id = id.substring(id.lastIndexOf('~') + 1);
    }/*from   ww w .java  2  s.  c o m*/
    return id;
}

From source file:org.eclipse.smarthome.binding.homematic.internal.type.generator.CcuMetadataExtractor.java

/**
 * Loads all description keys.//w w  w.  ja  v a  2 s  .co  m
 */
private Map<String, String> loadDeviceKeys() throws IOException {
    final Map<String, String> deviceKeys = new TreeMap<String, String>();

    new UrlLoader(CCU_URL + DEVICE_KEYS) {

        @Override
        public void line(String line) {
            if (line.startsWith("elvST['")) {
                line = StringUtils.remove(line, "elvST['");
                line = StringUtils.replace(line, "'] = '", "=");
                line = StringUtils.remove(line, "';");
                line = StringUtils.remove(line, "$");
                line = StringUtils.remove(line, "{");
                line = StringUtils.remove(line, "}");

                int count = StringUtils.countMatches(line, "=");
                if (count > 1) {
                    line = StringUtils.replace(line, "=", "|", 1);
                }

                String[] split = StringUtils.split(line, "=", 2);
                deviceKeys.put(StringUtils.trim(split[0]), StringUtils.trim(split[1]));
            }
        }
    };
    return deviceKeys;
}

From source file:org.eclipse.virgo.ide.manifest.internal.core.model.BundleManifestHeader.java

public void init() {
    if (this.manifestElements == null) {
        if (getValue().trim().length() > 0) {
            try {

                // Make sure the every " is closed
                if (StringUtils.countMatches(getValue(), "\"") % 2 != 0) {
                    throw new BundleException("");
                }//from   www .  j a  va2 s. c  o m

                List<BundleManifestHeaderElement> headerElements = new ArrayList<BundleManifestHeaderElement>();
                ManifestElement[] elements = ManifestElement.parseHeader(getName(), getValue());
                for (ManifestElement element : elements) {
                    headerElements.add(new BundleManifestHeaderElement(this, element));
                }
                this.manifestElements = headerElements
                        .toArray(new BundleManifestHeaderElement[headerElements.size()]);
            } catch (BundleException be) {
                String message = NLS.bind(BundleManifestCoreMessages.BundleErrorReporter_parseHeader,
                        getName());
                ((BundleManifest) getParent()).error(IMarker.SEVERITY_ERROR, message, getLineNumber() + 1);
                this.manifestElements = new BundleManifestHeaderElement[0];
            }
        } else {
            this.manifestElements = new BundleManifestHeaderElement[0];
        }
    }
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * @return the {@link Class} with given name - primitive or {@link Object} (including arrays).
 *//*from   w  w w. j  av a2s .c  om*/
public static Class<?> getClassByName(ClassLoader classLoader, String className) throws Exception {
    Assert.isNotNull(className);
    // check for primitive type
    if ("boolean".equals(className)) {
        return boolean.class;
    } else if ("byte".equals(className)) {
        return byte.class;
    } else if ("char".equals(className)) {
        return char.class;
    } else if ("short".equals(className)) {
        return short.class;
    } else if ("int".equals(className)) {
        return int.class;
    } else if ("long".equals(className)) {
        return long.class;
    } else if ("float".equals(className)) {
        return float.class;
    } else if ("double".equals(className)) {
        return double.class;
    }
    // check for array
    if (className.endsWith("[]")) {
        int dimensions = StringUtils.countMatches(className, "[]");
        String componentClassName = StringUtils.substringBefore(className, "[]");
        Class<?> componentClass = getClassByName(classLoader, componentClassName);
        return Array.newInstance(componentClass, new int[dimensions]).getClass();
    }
    // OK, load this class as object
    return classLoader.loadClass(className);
}

From source file:org.eclipse.wb.tests.designer.XWT.wizard.ApplicationWizardTest.java

/**
 * PDE project - RCP plugin./*  w w w . jav  a 2s. c  om*/
 */
@DisposeProjectAfter
public void test_libraries_forPlugin() throws Exception {
    // prepare default PDE/RCP project
    {
        do_projectDispose();
        do_projectCreate();
        BTestUtils.configure(m_testProject);
        PdeProjectConversionUtils.convertToPDE(m_project, null, null);
    }
    // animate
    animateWizard();
    // libraries in classpath
    assertTrue(ProjectUtils.hasType(m_javaProject, "org.eclipse.e4.xwt.XWT"));
    assertTrue(ProjectUtils.hasType(m_javaProject, "org.eclipse.e4.xwt.forms.XWTForms"));
    assertTrue(ProjectUtils.hasType(m_javaProject, "org.pushingpixels.trident.Timeline"));
    assertTrue(ProjectUtils.hasType(m_javaProject, "org.eclipse.core.databinding.Binding"));
    assertTrue(ProjectUtils.hasType(m_javaProject, "org.eclipse.core.databinding.observable.IObservable"));
    assertTrue(ProjectUtils.hasType(m_javaProject, "org.eclipse.jface.databinding.swt.SWTObservables"));
    // libraries in manifest
    {
        String manifest = AbstractPdeTest.getManifest();
        assertEquals(manifest, 1, StringUtils.countMatches(manifest, "org.pushingpixels.trident_"));
        assertEquals(manifest, 1, StringUtils.countMatches(manifest, "org.eclipse.e4.xwt_"));
        assertEquals(manifest, 1, StringUtils.countMatches(manifest, "org.eclipse.e4.xwt.forms_"));
    }
}

From source file:org.efs.openreports.actions.admin.ReportUploadAction.java

@Override
public String execute() {
    try {/*from ww  w  .  j a v  a2  s  .  c  om*/
        if ("upload".equals(command)) {
            if (reportFile != null) {
                File destinationFile = new File(directoryProvider.getReportDirectory() + reportFileFileName);

                try {
                    if (destinationFile.exists()) {
                        int revisionCount = reportProvider.getReportTemplate(reportFileFileName)
                                .getRevisionCount();
                        File versionedFile = new File(directoryProvider.getReportDirectory()
                                + reportFileFileName + "." + revisionCount);
                        FileUtils.copyFile(destinationFile, versionedFile);
                    }

                    FileUtils.copyFile(reportFile, destinationFile);
                } catch (IOException ioe) {
                    addActionError(ioe.toString());
                    return SUCCESS;
                }
            } else {
                addActionError("Invalid File.");
            }
        }

        if ("download".equals(command)) {
            String templateFileName = revision;

            // if there is a revision at the end of the file name, strip it off
            if (StringUtils.countMatches(templateFileName, ".") > 1) {
                templateFileName = revision.substring(0, revision.lastIndexOf("."));
            }

            File templateFile = new File(directoryProvider.getReportDirectory() + revision);
            byte[] template = FileUtils.readFileToByteArray(templateFile);

            HttpServletResponse response = ServletActionContext.getResponse();
            response.setHeader("Content-disposition", "inline; filename=" + templateFileName);
            response.setContentType("application/octet-stream");
            response.setContentLength(template.length);

            ServletOutputStream out = response.getOutputStream();
            out.write(template, 0, template.length);
            out.flush();
            out.close();
        }

        if ("revert".equals(command)) {
            String templateFileName = revision.substring(0, revision.lastIndexOf("."));

            File revisionFile = new File(directoryProvider.getReportDirectory() + revision);
            File currentFile = new File(directoryProvider.getReportDirectory() + templateFileName);

            // create a new revision from the current version
            int revisionCount = reportProvider.getReportTemplate(templateFileName).getRevisionCount();
            File versionedFile = new File(
                    directoryProvider.getReportDirectory() + templateFileName + "." + revisionCount);
            FileUtils.copyFile(currentFile, versionedFile);

            // copy the selected revision to the current version
            FileUtils.copyFile(revisionFile, currentFile);
        }

        reportTemplates = reportProvider.getReportTemplates();
    } catch (Exception pe) {
        addActionError(pe.getMessage());
    }

    return SUCCESS;
}

From source file:org.ensembl.healthcheck.testcase.compara.CheckMethodLinkSpeciesSetTag.java

/**                                                                                                                                                                             
* Check that the each multi-species analysis that uses a species tree has the species tree stored in the method_link_species_set_tag table.
*///from w  w  w.ja  va  2s .co  m

private boolean checkSpeciesTreesArePresent(DatabaseRegistryEntry dbre) {

    boolean result = true;

    // get version from mlsstag table 
    Connection con = dbre.getConnection();

    // get all the links between conservation scores and multiple genomic alignments
    String sql = "SELECT method_link_species_set_id, IFNULL(tag, 'NULL'), IFNULL(value, 'NULL'),"
            + " method_link_species_set.name, count(distinct genome_db_id)" + " FROM method_link_species_set"
            + " JOIN method_link USING (method_link_id)"
            + " LEFT JOIN method_link_species_set_tag USING (method_link_species_set_id)"
            + " JOIN species_set USING (species_set_id)"
            + " WHERE (class LIKE 'GenomicAlignTree%' OR class LIKE '%multiple_alignment' OR class LIKE '%tree_node')"
            + " AND tag = 'species_tree'" + " GROUP BY method_link_species_set_id";

    try {
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            Integer methodLinkSpeciesSetIdInt = rs.getInt(1);
            String metaKeyStr = rs.getString(2);
            String treeStr = rs.getString(3);
            String methodLinkSpeciesSetNameStr = rs.getString(4);
            Integer numSpecies = rs.getInt(5);
            if (metaKeyStr.equals("NULL")) {
                ReportManager.problem(this, con,
                        "MethodLinkSpeciesSet " + methodLinkSpeciesSetIdInt + " (" + methodLinkSpeciesSetNameStr
                                + ") does not have its tree in the method_link_species_set_tag table!");
                result = false;
            } else if (StringUtils.countMatches(treeStr, "(") != StringUtils.countMatches(treeStr, ")")) {
                ReportManager.problem(this, con,
                        "The tree for MethodLinkSpeciesSet " + methodLinkSpeciesSetIdInt + " ("
                                + methodLinkSpeciesSetNameStr
                                + ") does not have the same number of opening and closing brackets!");
                result = false;
            } else if (StringUtils.countMatches(treeStr, ",") + 1 != numSpecies) {
                ReportManager.problem(this, con,
                        "The tree for MethodLinkSpeciesSet " + methodLinkSpeciesSetIdInt + " ("
                                + methodLinkSpeciesSetNameStr + ") does not have the right number of leaves!");
                result = false;
            }
        }
        rs.close();
        stmt.close();
    } catch (SQLException se) {
        se.printStackTrace();
        result = false;
    }

    return result;

}