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:com.xpn.xwiki.web.DeleteAttachmentAction.java

/**
 * {@inheritDoc}//from  w  w w  .j a v a 2  s. c  om
 * 
 * @see com.xpn.xwiki.web.XWikiAction#action(com.xpn.xwiki.XWikiContext)
 */
@Override
public boolean action(XWikiContext context) throws XWikiException {
    // CSRF prevention
    if (!csrfTokenCheck(context)) {
        return false;
    }

    XWikiRequest request = context.getRequest();
    XWikiResponse response = context.getResponse();
    XWikiDocument doc = context.getDoc();
    XWikiAttachment attachment = null;
    XWiki xwiki = context.getWiki();
    String filename;

    // Delete from the trash
    if (request.getParameter("trashId") != null) {
        long trashId = NumberUtils.toLong(request.getParameter("trashId"));
        DeletedAttachment da = xwiki.getAttachmentRecycleBinStore().getDeletedAttachment(trashId, context,
                true);
        // If the attachment hasn't been previously deleted (i.e. it's not in the deleted attachment store) then
        // don't try to delete it and instead redirect to the attachment list.
        if (da != null) {
            com.xpn.xwiki.api.DeletedAttachment daapi = new com.xpn.xwiki.api.DeletedAttachment(da, context);
            if (!daapi.canDelete()) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS,
                        XWikiException.ERROR_XWIKI_ACCESS_DENIED,
                        "You are not allowed to delete an attachment from the trash "
                                + "immediately after it has been deleted from the wiki");
            }
            if (!da.getDocName().equals(doc.getFullName())) {
                throw new XWikiException(XWikiException.MODULE_XWIKI_APP,
                        XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION,
                        "The specified trash entry does not match the current document");
            }
            // TODO: Add a confirmation check
            xwiki.getAttachmentRecycleBinStore().deleteFromRecycleBin(trashId, context, true);
        }
        sendRedirect(response, Utils.getRedirect("attach", context));
        return false;
    }

    if (context.getMode() == XWikiContext.MODE_PORTLET) {
        filename = request.getParameter("filename");
    } else {
        // Note: We use getRequestURI() because the spec says the server doesn't decode it, as
        // we want to use our own decoding.
        String requestUri = request.getRequestURI();
        filename = Util.decodeURI(requestUri.substring(requestUri.lastIndexOf("/") + 1), context);
    }

    XWikiDocument newdoc = doc.clone();

    // An attachment can be indicated either using an id, or using the filename.
    if (request.getParameter("id") != null) {
        int id = NumberUtils.toInt(request.getParameter("id"));
        if (newdoc.getAttachmentList().size() > id) {
            attachment = newdoc.getAttachmentList().get(id);
        }
    } else {
        attachment = newdoc.getAttachment(filename);
    }

    // No such attachment
    if (attachment == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        VelocityContext vcontext = (VelocityContext) context.get("vcontext");
        if (vcontext != null) {
            vcontext.put("message",
                    context.getMessageTool().get("core.action.deleteAttachment.failed", filename));
            vcontext.put("details",
                    context.getMessageTool().get("platform.core.action.deleteAttachment.noAttachment"));
        }
        return true;
    }

    newdoc.setAuthor(context.getUser());

    // Set "deleted attachment" as the version comment.
    ArrayList<String> params = new ArrayList<String>();
    params.add(filename);
    if (attachment.isImage(context)) {
        newdoc.setComment(context.getMessageTool().get("core.comment.deleteImageComment", params));
    } else {
        newdoc.setComment(context.getMessageTool().get("core.comment.deleteAttachmentComment", params));
    }

    try {
        newdoc.deleteAttachment(attachment, context);

        // Needed to counter a side effect: the attachment is deleted from the newdoc.originalDoc as well
        newdoc.setOriginalDocument(doc);

        // Also save the document and attachment metadata
        context.getWiki().saveDocument(newdoc, context);
    } catch (Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        VelocityContext vcontext = (VelocityContext) context.get("vcontext");
        if (vcontext != null) {
            vcontext.put("message",
                    context.getMessageTool().get("core.action.deleteAttachment.failed", filename));
            vcontext.put("details", ExceptionUtils.getRootCauseMessage(ex));
        }
        return true;
    }

    // forward to attach page
    String redirect = Utils.getRedirect("attach", context);
    sendRedirect(response, redirect);

    return false;
}

From source file:com.blackducksoftware.integration.hub.detect.configuration.DetectPropertyMap.java

private Integer convertInt(final String integerString) {
    if (null == integerString) {
        return null;
    }/*from www.j av  a  2  s .  co m*/
    return NumberUtils.toInt(integerString);
}

From source file:com.mirth.connect.plugins.datatypes.hl7v2.XMLEncodedHL7Handler.java

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    logger.trace("starting element: " + localName);
    inElement = true;//from  w w  w .j  ava2  s.c o  m

    String[] localNameArray = StringUtils.split(localName, ID_DELIMETER);

    if (rootLevel == -1) {
        rootLevel = localNameArray.length;
    }

    /*
     * Skip the root element, MSH.1, and MSH.2 since those don't have any data that we care
     * about.
     */
    if ((localNameArray.length == 1) && (localNameArray[0].equals(ER7Reader.MESSAGE_ROOT_ID))) {
        rootLevel = 0;
        return;
    } else if (localNameArray.length == 2) {
        if (isHeaderSegment(localNameArray[0])) {
            if ((localNameArray[1].length() == 1)
                    && (localNameArray[1].charAt(0) == '1' || localNameArray[1].charAt(0) == '2')) {
                previousFieldNameArray = localNameArray;
                return;
            }
        }
    }

    /*
     * If the element that we've found is the same as the last, then we have a repetition, so we
     * remove the last separator that was added and append to repetition separator.
     */
    if (ArrayUtils.isEquals(localNameArray, previousFieldNameArray)) {
        output.deleteCharAt(output.length() - 1);
        output.append(repetitionSeparator);
        previousComponentNameArray = null;
        return;
    }

    /*
     * To find the delimeter count we are splitting the element name by the ID delimeter.
     */
    int currentDelimeterCount = localNameArray.length - 1;

    /*
     * MIRTH-2078: Don't add missing fields/components/subcomponents if the current level was
     * the starting level. This only pertains to partial XML messages where the root is a field
     * or component.
     */
    if (currentDelimeterCount == 1 && rootLevel <= 1) {
        /*
         * This will add missing fields if any (ex. between OBX.1 and OBX.5).
         */
        int previousFieldId = 0;

        if (previousFieldNameArray != null) {
            previousFieldId = NumberUtils.toInt(previousFieldNameArray[1]);
        }

        int currentFieldId = NumberUtils.toInt(localNameArray[1]);

        for (int i = 1; i < (currentFieldId - previousFieldId); i++) {
            output.append(fieldSeparator);
        }

        previousFieldNameArray = localNameArray;
    } else if (currentDelimeterCount == 2 && rootLevel <= 2) {
        /*
         * This will add missing components if any (ex. between OBX.1.1 and OBX.1.5).
         */
        int previousComponentId = 0;

        if (previousComponentNameArray != null) {
            previousComponentId = NumberUtils.toInt(previousComponentNameArray[2]);
        }

        int currentComponentId = NumberUtils.toInt(localNameArray[2]);

        for (int i = 1; i < (currentComponentId - previousComponentId); i++) {
            output.append(componentSeparator);
            previousDelimiterLength = componentSeparator.length();
        }

        previousComponentNameArray = localNameArray;
    } else if (currentDelimeterCount == 3 && rootLevel <= 3) {
        /*
         * This will add missing subcomponents if any (ex. between OBX.1.1.1 and OBX.1.1.5).
         */
        int previousSubcomponentId = 0;

        if (previousSubcomponentNameArray != null) {
            previousSubcomponentId = NumberUtils.toInt(previousSubcomponentNameArray[3]);
        }

        int currentSubcomponentId = NumberUtils.toInt(localNameArray[3]);

        for (int i = 1; i < (currentSubcomponentId - previousSubcomponentId); i++) {
            output.append(subcomponentSeparator);
            previousDelimiterLength = subcomponentSeparator.length();
        }

        previousSubcomponentNameArray = localNameArray;
    }

    /*
     * If we have an element with no periods, then we know its the name of the segment, so write
     * it to the output buffer followed by the field separator.
     */
    if (currentDelimeterCount == 0) {
        output.append(localName);
        output.append(fieldSeparator);

        /*
         * Also set previousFieldName to null so that multiple segments in a row with only one
         * field don't trigger a repetition character. (i.e. NTE|1<CR>NTE|2)
         */
        previousFieldNameArray = null;
    } else if (currentDelimeterCount == 1) {
        previousComponentNameArray = null;
    } else if (currentDelimeterCount == 2) {
        previousSubcomponentNameArray = null;
    }
}

From source file:com.bekwam.examples.javafx.oldscores.ScoresDialogController.java

@FXML
public void updateVerbal1995() {
    if (logger.isDebugEnabled()) {
        logger.debug("[UPD V 1995]");
    }/*from w w  w.  j  a v a  2s . c om*/

    if (dao == null) {
        throw new IllegalArgumentException(
                "dao has not been set; call setRecenteredDAO() before calling this method");
    }

    String recenteredScore_s = txtVerbalScoreRecentered.getText();

    if (StringUtils.isNumeric(recenteredScore_s)) {
        Integer scoreRecentered = NumberUtils.toInt(recenteredScore_s);
        if (withinRange(scoreRecentered)) {

            if (needsRound(scoreRecentered)) {
                scoreRecentered = round(scoreRecentered);
                txtVerbalScoreRecentered.setText(String.valueOf(scoreRecentered));
            }

            resetErrMsgs();
            Integer score1995 = dao.lookup1995VerbalScore(scoreRecentered);
            txtVerbalScore1995.setText(String.valueOf(score1995));
        } else {
            errMsgVerbalRecentered.setVisible(true);
        }
    } else {
        errMsgVerbalRecentered.setVisible(true);
    }
}

From source file:com.esri.geoevent.test.performance.ui.ProducerController.java

@Override
protected void loadState() {
    Preferences preferences = Preferences.userNodeForPackage(ProducerController.class);
    Protocol selectedProtocol = Protocol.fromValue(preferences.get("protocol", Protocol.TCP.toString()));
    int portNumber = NumberUtils.toInt(preferences.get("port", String.valueOf(DEFAULT_COMMAND_PORT)));
    int serverPortNumber = NumberUtils
            .toInt(preferences.get("serverPort", String.valueOf(DEFAULT_SERVER_PORT)));

    protocol.setValue(selectedProtocol);
    port.setText(String.valueOf(portNumber));
    serverPort.setText(String.valueOf(serverPortNumber));
}

From source file:com.adguard.filter.rules.ContentFilterRule.java

/**
 * Creates an instance of the ContentFilterRule from its text format
 *
 * @param ruleText Rule text//from   w w w  . ja  v a  2s .com
 */
protected ContentFilterRule(String ruleText) {
    super(ruleText);

    parentSearchLevel = DEFAULT_PARENT_SEARCH_LEVEL;

    int contentRuleMarkIndex = StringUtils.indexOf(ruleText, MASK_CONTENT_RULE);
    int ruleStartIndex = StringUtils.indexOf(ruleText, ATTRIBUTE_START_MARK);

    // Cutting tag name from string
    if (ruleStartIndex == -1) {
        tagName = ruleText.substring(contentRuleMarkIndex + MASK_CONTENT_RULE.length());
    } else {
        tagName = ruleText.substring(contentRuleMarkIndex + MASK_CONTENT_RULE.length(), ruleStartIndex);
    }

    // Loading domains (if any))
    if (contentRuleMarkIndex > 0) {
        String domains = ruleText.substring(0, contentRuleMarkIndex);
        loadDomains(domains);
    }

    // Loading attributes filter
    while (ruleStartIndex != -1) {
        int equalityIndex = ruleText.indexOf(EQUAL, ruleStartIndex + 1);
        int quoteStartIndex = ruleText.indexOf(QUOTES, equalityIndex + 1);
        int quoteEndIndex = getQuoteIndex(ruleText, quoteStartIndex + 1);
        if (quoteStartIndex == -1 || quoteEndIndex == -1) {
            break;
        }
        int ruleEndIndex = ruleText.indexOf(ATTRIBUTE_END_MARK, quoteEndIndex + 1);

        String attributeName = ruleText.substring(ruleStartIndex + 1, equalityIndex);
        String attributeValue = ruleText.substring(quoteStartIndex + 1, quoteEndIndex);
        attributeValue = StringUtils.replace(attributeValue, "\"\"", "\"");

        switch (attributeName) {
        case TAG_CONTENT_MASK:
            tagContentFilter = attributeValue;
            break;
        case WILDCARD_MASK:
            wildcard = new Wildcard(attributeValue, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
            break;
        case TAG_CONTENT_MAX_LENGTH:
            maxLength = NumberUtils.toInt(attributeValue);
            break;
        case TAG_CONTENT_MIN_LENGTH:
            minLength = NumberUtils.toInt(attributeValue);
            break;
        case PARENT_ELEMENTS:
            parentElements = Arrays.asList(StringUtils.split(attributeValue, ','));
            break;
        case PARENT_SEARCH_LEVEL:
            parentSearchLevel = NumberUtils.toInt(attributeValue);
            break;
        default:
            attributesFilter.put(attributeName, attributeValue);
            break;
        }

        if (ruleEndIndex == -1)
            break;
        ruleStartIndex = ruleText.indexOf(ATTRIBUTE_START_MARK, ruleEndIndex + 1);
    }
}

From source file:com.xpn.xwiki.web.EditAction.java

@Override
public String render(XWikiContext context) throws XWikiException {
    XWikiDocument doc = context.getDoc();
    EditForm editForm = (EditForm) context.getForm();
    VelocityContext vcontext = (VelocityContext) context.get("vcontext");

    boolean hasTranslation = doc != context.get("tdoc");

    // We have to clone the context document because it is cached and the changes we are going to make are valid
    // only for the duration of the current request.
    doc = doc.clone();// www . ja va  2 s  .  com
    context.put("doc", doc);
    vcontext.put("doc", doc.newDocument(context));

    synchronized (doc) {
        doc.readDocMetaFromForm(editForm, context);

        String language = context.getWiki().getLanguagePreference(context);
        if (doc.isNew() && doc.getDefaultLanguage().equals("")) {
            doc.setDefaultLanguage(language);
        }

        String languageToEdit = StringUtils.isEmpty(editForm.getLanguage()) ? language : editForm.getLanguage();

        // If no specific language is set or if it is "default" then we edit the current doc.
        if (languageToEdit == null || languageToEdit.equals("default")) {
            languageToEdit = "";
        }
        // If the document is new or if the language to edit is the default language then we edit the default
        // translation.
        if (doc.isNew() || doc.getDefaultLanguage().equals(languageToEdit)) {
            languageToEdit = "";
        }
        // If the doc does not exist in the language to edit and the language was not explicitly set in the URL then
        // we edit the default document translation. This prevents use from creating unneeded translations.
        if (!hasTranslation && StringUtils.isEmpty(editForm.getLanguage())) {
            languageToEdit = "";
        }

        // Initialize the translated document.
        XWikiDocument tdoc;
        if (languageToEdit.equals("")) {
            // Edit the default document translation (default language).
            tdoc = doc;
            if (doc.isNew()) {
                doc.setDefaultLanguage(language);
                doc.setLanguage("");
            }
        } else if (!hasTranslation && context.getWiki().isMultiLingual(context)) {
            // Edit a new translation.
            tdoc = new XWikiDocument(doc.getDocumentReference());
            tdoc.setLanguage(languageToEdit);
            tdoc.setContent(doc.getContent());
            tdoc.setSyntax(doc.getSyntax());
            tdoc.setAuthorReference(context.getUserReference());
            tdoc.setStore(doc.getStore());
        } else {
            // Edit an existing translation. Clone the translated document object to be sure that the changes we are
            // going to make will last only for the duration of the current request.
            tdoc = ((XWikiDocument) context.get("tdoc")).clone();
        }

        // Check if section editing is enabled and if a section is specified.
        boolean sectionEditingEnabled = context.getWiki().hasSectionEdit(context);
        int sectionNumber = sectionEditingEnabled
                ? NumberUtils.toInt(context.getRequest().getParameter("section"))
                : 0;
        vcontext.put("sectionNumber", sectionNumber);

        try {
            // Try to update the edited document based on the template specified on the request.
            tdoc.readFromTemplate(editForm, context);
        } catch (XWikiException e) {
            if (e.getCode() == XWikiException.ERROR_XWIKI_APP_DOCUMENT_NOT_EMPTY) {
                context.put("exception", e);
                return "docalreadyexists";
            }
        }

        // Update the edited content.
        if (editForm.getContent() != null) {
            tdoc.setContent(editForm.getContent());
        } else if (sectionNumber > 0) {
            tdoc.setContent(tdoc.getContentOfSection(sectionNumber));
        }

        // Update the edited title.
        if (editForm.getTitle() != null) {
            tdoc.setTitle(editForm.getTitle());
        } else if (sectionNumber > 0) {
            // The edited content is either the content of the specified section or the content provided on the
            // request. We assume the content provided on the request is meant to overwrite the specified section.
            // In both cases the document content is currently having one section, so we can take its title.
            String sectionTitle = tdoc.getDocumentSection(1).getSectionTitle();
            if (StringUtils.isNotBlank(sectionTitle)) {
                tdoc.setTitle(
                        context.getMessageTool().get("core.editors.content.titleField.sectionEditingFormat",
                                tdoc.getRenderedTitle(Syntax.PLAIN_1_0, context), sectionNumber, sectionTitle));
            }
        }

        // Update the edited objects.
        tdoc.readObjectsFromForm(editForm, context);

        // Expose the translated document on the XWiki context and the Velocity context.
        context.put("tdoc", tdoc);
        vcontext.put("tdoc", tdoc.newDocument(context));
        // XWiki applications that were previously using the inline action might still expect the cdoc (content
        // document) to be properly set on the context. Expose tdoc (translated document) also as cdoc for backward
        // compatibility.
        context.put("cdoc", context.get("tdoc"));
        vcontext.put("cdoc", vcontext.get("tdoc"));

        /* Setup a lock */
        try {
            XWikiLock lock = tdoc.getLock(context);
            if (lock == null || lock.getUserName().equals(context.getUser()) || editForm.isLockForce()) {
                tdoc.setLock(context.getUser(), context);
            }
        } catch (Exception e) {
            // Lock should never make XWiki fail, but we should log any related information.
            LOGGER.error("Exception while setting up lock", e);
        }
    }

    // Make sure object property fields are displayed in edit mode.
    // See XWikiDocument#display(String, BaseObject, XWikiContext)
    // TODO: Revisit the display mode after the inline action is removed. Is the display mode still needed when
    // there is only one edit action?
    context.put("display", "edit");
    return "edit";
}

From source file:com.esri.geoevent.test.performance.ui.ConsumerController.java

@Override
protected void loadState() {
    Preferences preferences = Preferences.userNodeForPackage(ConsumerController.class);
    Protocol selectedProtocol = Protocol.fromValue(preferences.get("protocol", Protocol.TCP.toString()));
    int portNumber = NumberUtils.toInt(preferences.get("port", String.valueOf(DEFAULT_COMMAND_PORT)));
    int serverPortNumber = NumberUtils
            .toInt(preferences.get("serverPort", String.valueOf(DEFAULT_SERVER_PORT)));

    protocol.setValue(selectedProtocol);
    port.setText(String.valueOf(portNumber));
    serverPort.setText(String.valueOf(serverPortNumber));
}

From source file:com.enation.app.b2b2c.core.action.api.store.StoreApiAction.java

/**
 * ??//w w w  . j  av  a 2  s. c  om
 * @param store
 * @return Store
 */
private Store getStoreInfo() {
    HttpServletRequest request = ThreadContextHolder.getHttpRequest();
    Store store = new Store();
    store.setStore_name(request.getParameter("store_name")); //??
    store.setZip(request.getParameter("zip")); //
    store.setTel(request.getParameter("tel")); //??
    store.setId_number(request.getParameter("id_number")); //??
    store.setId_img(request.getParameter("store_id_img")); //??
    store.setLicense_img(request.getParameter("store_license_img")); //??
    store.setName_auth(NumberUtils.toInt(request.getParameter("store_name_auth").toString())); //?
    store.setStore_auth(NumberUtils.toInt(request.getParameter("store_store_auth").toString())); //?
    //??
    store.setStore_provinceid(NumberUtils.toInt(request.getParameter("store_province_id").toString())); //?ID
    store.setStore_cityid(NumberUtils.toInt(request.getParameter("store_city_id").toString())); //ID
    store.setStore_regionid(NumberUtils.toInt(request.getParameter("store_region_id").toString())); //ID

    store.setStore_province(request.getParameter("store_province")); //?
    store.setStore_city(request.getParameter("store_city")); //
    store.setStore_region(request.getParameter("store_region")); //
    store.setAttr(request.getParameter("attr")); //?
    //?
    store.setBank_account_name(request.getParameter("bank_account_name")); //??   
    store.setBank_account_number(request.getParameter("bank_account_number")); //??
    store.setBank_name(request.getParameter("bank_name")); //??
    store.setBank_code(request.getParameter("bank_code")); //??

    store.setBank_provinceid(NumberUtils.toInt(request.getParameter("bank_province_id").toString())); //?Id
    store.setBank_cityid(NumberUtils.toInt(request.getParameter("bank_city_id").toString())); //Id
    store.setBank_regionid(NumberUtils.toInt(request.getParameter("bank_region_id").toString())); //Id

    store.setBank_province(request.getParameter("bank_province")); //?
    store.setBank_city(request.getParameter("bank_city")); //
    store.setBank_region(request.getParameter("bank_region")); //

    //
    store.setCommission(0.0);

    //???
    if (request.getParameter("community_id") != null) {
        store.setCommunity_id(NumberUtils.toInt(request.getParameter("community_id")));
        store.setCommunity(request.getParameter("community"));
    }
    return store;
}

From source file:com.blackducksoftware.integration.hub.builder.HubServerConfigBuilder.java

@Override
public ValidationResults<GlobalFieldKey, HubServerConfig> buildResults() {
    final ValidationResults<GlobalFieldKey, HubServerConfig> result = assertValid();

    URL hubURL = null;//  ww w  .  j a v  a  2 s .c  om
    try {
        hubURL = new URL(hubUrl);
    } catch (final MalformedURLException e) {
    }
    final HubServerConfig config = new HubServerConfig(hubURL, NumberUtils.toInt(timeoutSeconds), credentials,
            proxyInfo);
    result.setConstructedObject(config);
    return result;
}