Example usage for org.apache.commons.lang3.math NumberUtils toInt

List of usage examples for org.apache.commons.lang3.math NumberUtils toInt

Introduction

In this page you can find the example usage for org.apache.commons.lang3.math NumberUtils toInt.

Prototype

public static int toInt(final String str) 

Source Link

Document

Convert a String to an int, returning zero if the conversion fails.

If the string is null, zero is returned.

 NumberUtils.toInt(null) = 0 NumberUtils.toInt("")   = 0 NumberUtils.toInt("1")  = 1 

Usage

From source file:org.craftercms.social.migration.mongo.MongoConnection.java

public static void init(final String srcHost, final String srcPort, final String srcDb, final String dstHost,
        final String dtsPort, final String dtsDb) throws MigrationException {
    LoggerFactory.getLogger(MongoConnection.class).info("Starting DB connection");
    if (instance == null) {

        int iSrcPort = NumberUtils.toInt(srcPort);
        if (iSrcPort == 0) {

            throw new MigrationException("Source Port is not valid", true);
        }//from  w w w. ja v a 2s.c  o m
        int iDstPort = NumberUtils.toInt(dtsPort);
        if (iDstPort == 0) {

            throw new MigrationException("Destination Port is not valid", true);
        }
        if (StringUtils.isBlank(srcHost)) {

            throw new MigrationException("Source Host is not valid", true);
        }
        if (StringUtils.isBlank(dstHost)) {

            throw new MigrationException("Destination Host is not valid", true);
        }

        if (StringUtils.isBlank(srcDb)) {
            throw new MigrationException("Source Db is not valid", true);
        }
        if (StringUtils.isBlank(dtsDb)) {
            throw new MigrationException("Destination Db is not valid", true);
        }

        try {
            instance = new MongoConnection(new MongoClient(srcHost, iSrcPort), srcDb,
                    new MongoClient(dstHost, iDstPort), dtsDb);
        } catch (UnknownHostException e) {
            throw new MigrationException(e, true);
        }
    }
}

From source file:org.fabrician.enabler.DockerContainer.java

private int resolveToInteger(String runtimeContextVariableName) throws Exception {
    String val = SpecialDirective.resolveStringValue(this,
            StringUtils.trimToEmpty(getStringVariableValue(runtimeContextVariableName)));
    return NumberUtils.toInt(val);
}

From source file:org.finra.herd.service.impl.BusinessObjectFormatServiceImpl.java

/**
 * Validate that a new list of schema columns is additive to an old one.
 *
 * @param newSchemaColumns the list of schema columns from the new schema
 * @param oldSchemaColumns the list of schema columns from the old schema
 *
 * @return true if schema columns are additive, false otherwise
 *//*from  w  w  w  .ja va 2  s.c om*/
private boolean validateNewSchemaColumnsAreAdditiveToOldSchemaColumns(List<SchemaColumn> newSchemaColumns,
        List<SchemaColumn> oldSchemaColumns) {
    // Null check is required for the new and old list of columns, since partition columns are optional in format schema.
    if (newSchemaColumns == null || oldSchemaColumns == null) {
        return (newSchemaColumns == null && oldSchemaColumns == null);
    } else if (newSchemaColumns.size() != oldSchemaColumns.size()) {
        return false;
    } else {
        // Loop through the schema columns and compare each pair of new and old columns.
        for (int i = 0; i < newSchemaColumns.size(); i++) {
            // Get instance copies for both new and old schema columns.
            // Null check is not needed here, since schema column instance can not be null.
            SchemaColumn newSchemaColumnCopy = (SchemaColumn) newSchemaColumns.get(i).clone();
            SchemaColumn oldSchemaColumnCopy = (SchemaColumn) oldSchemaColumns.get(i).clone();

            // Since we allow column description to be changed, set the description field to null for both columns.
            newSchemaColumnCopy.setDescription(null);
            oldSchemaColumnCopy.setDescription(null);

            // For a set of data types, size increase is considered to be an additive change.
            // Null check on schema column date type is not needed, since it is a required field for schema column.
            if (SCHEMA_COLUMN_DATA_TYPES_WITH_ALLOWED_SIZE_INCREASE
                    .contains(newSchemaColumnCopy.getType().toUpperCase())) {
                // The below string to integer conversion methods return an int represented by the string, or zero if conversion fails.
                int newSize = NumberUtils.toInt(newSchemaColumnCopy.getSize());
                int oldSize = NumberUtils.toInt(oldSchemaColumnCopy.getSize());

                // If new size is greater than the old one and they are both positive integers, then set the size field to null for both columns.
                if (oldSize > 0 && newSize >= oldSize) {
                    newSchemaColumnCopy.setSize(null);
                    oldSchemaColumnCopy.setSize(null);
                }
            }

            // Fail the validation if columns do not match.
            if (!newSchemaColumnCopy.equals(oldSchemaColumnCopy)) {
                return false;
            }
        }

        return true;
    }
}

From source file:org.jamwiki.migrate.MediaWikiXmlImporter.java

/**
 * end of xml-tag//from  w  ww. j  av a2  s . com
 *
 * @param uri The Namespace URI, or the empty string if the element has no Namespace URI or
 *  if Namespace processing is not being performed.
 * @param localName The local name (without prefix), or the empty string if Namespace processing
 *  is not being performed.
 * @param qName The qualified name (with prefix), or the empty string if qualified names are not available.
 */
public void endElement(String uri, String localName, String qName) throws SAXException {
    if (StringUtils.equals(MediaWikiConstants.MEDIAWIKI_ELEMENT_NAMESPACE, qName)) {
        int key = NumberUtils.toInt(this.currentAttributeMap.get("key"));
        try {
            Namespace jamwikiNamespace = WikiBase.getDataHandler().lookupNamespaceById(key);
            if (jamwikiNamespace != null) {
                String mediawikiNamespace = currentElementBuffer.toString().trim();
                mediawikiNamespaceMap.put(mediawikiNamespace, jamwikiNamespace.getLabel(this.virtualWiki));
            }
        } catch (DataAccessException e) {
            throw new SAXException("Failure while processing namespace with ID: " + key, e);
        }
    } else if (MediaWikiConstants.MEDIAWIKI_ELEMENT_TOPIC_NAME.equals(qName)) {
        String topicName = currentElementBuffer.toString().trim();
        this.initCurrentTopic(topicName);
    } else if (MediaWikiConstants.MEDIAWIKI_ELEMENT_TOPIC_CONTENT.equals(qName)) {
        String topicContent = this.convertToJAMWikiNamespaces(currentElementBuffer.toString().trim());
        currentTopicVersion.setVersionContent(topicContent);
        currentTopicVersion.setCharactersChanged(StringUtils.length(topicContent) - previousTopicContentLength);
        previousTopicContentLength = StringUtils.length(topicContent);
    } else if (MediaWikiConstants.MEDIAWIKI_ELEMENT_TOPIC_VERSION_COMMENT.equals(qName)) {
        this.currentTopicVersion.setEditComment(currentElementBuffer.toString().trim());
    } else if (MediaWikiConstants.MEDIAWIKI_ELEMENT_TOPIC_VERSION_MINOR_EDIT.equals(qName)) {
        this.currentTopicVersion.setEditType(TopicVersion.EDIT_MINOR);
    } else if (MediaWikiConstants.MEDIAWIKI_ELEMENT_TOPIC_VERSION_EDIT_DATE.equals(qName)) {
        this.currentTopicVersion
                .setEditDate(this.parseMediaWikiTimestamp(currentElementBuffer.toString().trim()));
    } else if (MediaWikiConstants.MEDIAWIKI_ELEMENT_TOPIC_VERSION_IP.equals(qName)
            || MediaWikiConstants.MEDIAWIKI_ELEMENT_TOPIC_VERSION_USERNAME.equals(qName)) {
        // Login name in Mediawiki can be longer than 100 characters, so trim to conform to
        // JAMWiki limits.  In general very long login names seem to be used only by vandals,
        // so this should be an acceptable workaround.
        String authorDisplay = currentElementBuffer.toString().trim();
        if (authorDisplay.length() > 100) {
            authorDisplay = authorDisplay.substring(0, 100);
        }
        this.currentTopicVersion.setAuthorDisplay(authorDisplay);
    } else if (MediaWikiConstants.MEDIAWIKI_ELEMENT_TOPIC_VERSION.equals(qName)) {
        this.commitTopicVersion();
    } else if (MediaWikiConstants.MEDIAWIKI_ELEMENT_TOPIC.equals(qName)) {
        // flush any pending topic version data
        this.writeTopicVersion(true);
        this.orderTopicVersions();
    }
}

From source file:org.jamwiki.servlets.SearchServlet.java

/**
 *
 *///  w  w w.j ava2 s .co m
private void search(HttpServletRequest request, ModelAndView next, WikiPageInfo pageInfo) throws Exception {
    String virtualWiki = pageInfo.getVirtualWikiName();
    String searchField = WikiUtil.getParameterFromRequest(request, "text", false);
    if (StringUtils.isBlank(searchField)) {
        pageInfo.setPageTitle(new WikiMessage("search.title"));
    } else {
        pageInfo.setPageTitle(new WikiMessage("searchresult.title", searchField));
    }
    next.addObject("searchConfig", WikiConfiguration.getCurrentSearchConfiguration());
    // add a map of namespace id & label for display on the front end.
    Map<Integer, String> namespaceMap = ServletUtil.loadNamespaceDisplayMap(virtualWiki,
            ServletUtil.retrieveUserLocale(request));
    next.addObject("namespaces", namespaceMap);
    List<Integer> selectedNamespaces = null;
    if (request.getParameter("ns") != null) {
        Map<Integer, Integer> selectedNamespaceMap = new TreeMap<Integer, Integer>();
        selectedNamespaces = new ArrayList<Integer>();
        for (String namespaceId : request.getParameterValues("ns")) {
            selectedNamespaces.add(NumberUtils.toInt(namespaceId));
            selectedNamespaceMap.put(NumberUtils.toInt(namespaceId), NumberUtils.toInt(namespaceId));
        }
        next.addObject("selectedNamespaces", selectedNamespaceMap);
    }
    if (!StringUtils.isBlank(searchField)) {
        // grab search engine instance and find results
        List<SearchResultEntry> results = WikiBase.getSearchEngine().findResults(virtualWiki, searchField,
                selectedNamespaces);
        next.addObject("searchField", searchField);
        next.addObject("results", results);
    }
    pageInfo.setContentJsp(JSP_SEARCH);
    pageInfo.setSpecial(true);
}

From source file:org.labkey.freezerpro.export.FreezerProExport.java

private List<Freezer> getFreezers(HttpClient client) {
    GetFreezersCommand sampleTypesCommand = new GetFreezersCommand(this, _config.getBaseServerUrl(),
            _config.getUsername(), _config.getPassword());
    FreezerProCommandResonse response = sampleTypesCommand.execute(client, _job);
    List<Freezer> freezers = new ArrayList<>();

    try {/*from   ww  w . ja va  2  s.  c  o  m*/
        if (response != null) {
            if (response.getStatusCode() == HttpStatus.SC_OK) {
                for (Map<String, Object> row : response.loadData()) {
                    freezers.add(new Freezer(String.valueOf(row.get("id")), String.valueOf(row.get("name")),
                            String.valueOf(row.get("description")),
                            NumberUtils.toInt(String.valueOf(row.get("subdivisions"))),
                            NumberUtils.toInt(String.valueOf(row.get("boxes"))),
                            String.valueOf(row.get(BARCODE_FIELD_NAME)), String.valueOf(row.get("rfid_tag"))));

                }
                return freezers;
            } else {
                _job.error("request for freezer data failed, status code: " + response.getStatusCode());
                throw new RuntimeException(
                        "request for freezer data failed, status code: " + response.getStatusCode());
            }
        }
        return Collections.EMPTY_LIST;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.libreplan.web.planner.limiting.allocation.LimitingAllocationRow.java

private int toNumber(String str) {
    if (NumberUtils.isNumber(str)) {
        int result = NumberUtils.toInt(str);
        return (result >= 1 && result <= 10) ? result : 1;
    }//w w w. ja  va2  s.  com
    return 1;
}

From source file:org.manalith.ircbot.plugin.linuxpkgfinder.ArchPackageFinder.java

public String getResultFromMainPkgDB(String arg) throws IOException {

    String[] arch_keywords = { "any", "i686", "x86_64" };
    int len = arch_keywords.length;
    int pages = 100000000;

    String infostr = "";
    String url = "";

    for (int i = 0; i < len; i++) {
        for (int j = 0; j < pages; j++) {
            url = "http://www.archlinux.org/packages/?page=" + (new Integer(j + 1)).toString() + "&arch="
                    + arch_keywords[i] + "&q=" + arg;

            String pageinfo = "";
            try {
                pageinfo = Jsoup.connect(url).get().select("div#pkglist-results>div.pkglist-stats>p").get(0)
                        .text();/*from  www.  j  a v  a 2s  .  c  o m*/
            } catch (Exception e) {
                pages = 1;
            }

            if (j == 0 && pages == 100000000) {
                if (StringUtils.countMatches(pageinfo, ".") == 1)
                    pages = 1;
                else {
                    if (pageinfo.charAt(pageinfo.length() - 1) == '.')
                        pageinfo = pageinfo.substring(0, pageinfo.length() - 1);
                    String[] piarray = pageinfo.split("\\s");
                    pages = NumberUtils.toInt(piarray[piarray.length - 1]);
                }
            }

            Iterator<Element> e = Jsoup.connect(url).get().select("table.results>tbody>tr").iterator();

            while (e.hasNext()) {
                Elements ee = e.next().select("td");
                if (ee.get(2).select("a").get(0).text().equals(arg)) {
                    if (!infostr.equals(""))
                        infostr += ", ";
                    infostr += "\u0002(main-" + ee.get(0).text() + " " + ee.get(1).text() + ")\u0002 ";

                    if (pkgname.length() == 0)
                        pkgname = ee.get(2).select("a").get(0).text();
                    if (description.length() == 0)
                        description = ee.get(4).text();

                    if (ee.get(3).select("span.flagged").size() > 0)
                        infostr += ee.get(3).select("span.flagged").get(0).text();
                    else
                        infostr += ee.get(3).text();

                    break;
                }
            }
        }
        pages = 100000000;
    }

    return infostr;
}

From source file:org.manalith.ircbot.plugin.linuxpkgfinder.ArchPackageFinder.java

private String getResultFromAUR(String arg) throws IOException {
    String infostr = "";
    String pageinfo = "";
    String url = "";

    int pages = 100000000;

    for (int i = 0; i < pages; i++) {

        url = "http://aur.archlinux.org/packages.php?SeB=x&K=" + arg + "&PP=50&O=" + (i * 50);

        try {/*from w  w  w .  ja  v  a 2s  .c o m*/
            pageinfo = Jsoup.connect(url).get().select("div#pkglist-results>div.pkglist-stats>p").get(0).text();
        } catch (IndexOutOfBoundsException e) {
            return "";
        }

        if (i == 0 && pages == 100000000) {
            if (StringUtils.countMatches(pageinfo, ".") == 1)
                pages = 1;
            else {
                if (pageinfo.charAt(pageinfo.length() - 1) == '.')
                    pageinfo = pageinfo.substring(0, pageinfo.length() - 1);
                String[] piarray = pageinfo.split("\\s");
                pages = NumberUtils.toInt(piarray[piarray.length - 1]);
            }
        }

        Iterator<Element> e = Jsoup.connect(url).get().select("table>tbody>tr").iterator();

        while (e.hasNext()) {
            Elements ee = e.next().select("td");
            if (ee.get(1).select("td").get(0).text().equals(arg)) {
                if (!infostr.equals(""))
                    infostr += " | ";
                if (pkgname.length() == 0)
                    pkgname = ee.get(1).select("a").text();
                if (description.length() == 0)
                    description = ee.get(4).text();

                infostr += "\u0002(AUR-" + ee.get(0).text() + ")\u0002 ";
                infostr += ee.get(2).text();
                break;
            }
        }
    }

    return infostr;
}

From source file:org.manalith.ircbot.plugin.linuxpkgfinder.PhPortageProvider.java

@Override
public String find(String arg) {
    String result = "";
    String url = "http://darkcircle.kr/phportage/phportage.xml?k=" + arg + "&limit=1&similarity=exact"
            + "&showmasked=true&livebuild=false";

    try {/*from  w  w w  .ja  va 2s  . c  o  m*/
        Document d = Jsoup.connect(url).get();
        System.out.println(d.select("result>code").get(0).text());
        if (NumberUtils.toInt(d.select("result>code").get(0).text()) == 0) {
            if (NumberUtils.toInt(d.select("result>actualnumofres").get(0).text()) == 0)
                result = "[Gentoo]  ";
            else {
                Element e = d.select("result>packages>pkg").get(0);
                String pkgname = e.select("category").get(0).text() + "/" + e.select("name").get(0).text();

                String ver = e.select("version").get(0).text();
                String description = e.select("description").get(0).text();

                result = "[Gentoo] \u0002" + pkgname + "\u0002 - " + description + ", " + ver;
            }
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        result = ": " + e.getMessage();
    }

    return result;
}