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

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

Introduction

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

Prototype

public static boolean isNumeric(String str) 

Source Link

Document

Checks if the String contains only unicode digits.

Usage

From source file:com.bstek.dorado.core.pkgs.PackageManager.java

private static int compareVersionSection(String section1, String section2) {
    if (StringUtils.isNumeric(section1) && StringUtils.isNumeric(section2)) {
        return Integer.valueOf(section1) - Integer.valueOf(section2);
    } else {/*from  w  w w  .  ja  v  a 2s  . c o m*/
        return section1.compareTo(section2);
    }
}

From source file:hydrograph.ui.graph.command.ComponentPasteCommand.java

private String getPrefix(Object node) {
    String currentName = ((Component) node).getComponentLabel().getLabelContents();
    String prefix = currentName;//from   w  ww.  ja  v a2  s. com
    StringBuffer buffer = new StringBuffer(currentName);
    try {
        if (buffer.lastIndexOf(UNDERSCORE) != -1 && (buffer.lastIndexOf(UNDERSCORE) != buffer.length())) {
            String substring = StringUtils
                    .trim(buffer.substring(buffer.lastIndexOf(UNDERSCORE) + 1, buffer.length()));
            if (StringUtils.isNumeric(substring)) {
                prefix = buffer.substring(0, buffer.lastIndexOf(UNDERSCORE));
            }
        }
    } catch (Exception exception) {
        LOGGER.warn("Cannot process component name for detecting prefix : ", exception.getMessage());
    }
    return prefix;
}

From source file:net.bible.service.format.osistohtml.taghandler.ReferenceHandler.java

/** create a link tag from an OSISref and the content of the tag
 *///w  w w . j  av a  2  s.c  o  m
private String getReferenceTag(String reference, String content) {
    log.debug("Ref:" + reference + " Content:" + content);
    StringBuilder result = new StringBuilder();
    try {

        //JSword does not know the basis (default book) so prepend it if it looks like JSword failed to work it out
        //We only need to worry about the first ref because JSword uses the first ref as the basis for the subsequent refs
        // if content starts with a number and is not followed directly by an alpha char e.g. 1Sa
        if (reference == null && content != null && content.length() > 0
                && StringUtils.isNumeric(content.subSequence(0, 1))
                && (content.length() < 2 || !StringUtils.isAlphaSpace(content.subSequence(1, 2)))) {

            // maybe should use VerseRangeFactory.fromstring(orig, basis)
            // this check for a colon to see if the first ref is verse:chap is not perfect but it will do until JSword adds a fix
            int firstColonPos = content.indexOf(":");
            boolean isVerseAndChapter = firstColonPos > 0 && firstColonPos < 4;
            if (isVerseAndChapter) {
                reference = parameters.getBasisRef().getBook().getOSIS() + " " + content;
            } else {
                reference = parameters.getBasisRef().getBook().getOSIS() + " "
                        + parameters.getBasisRef().getChapter() + ":" + content;
            }
            log.debug("Patched reference:" + reference);
        } else if (reference == null) {
            reference = content;
        }

        // convert urns of type book:key to sword://book/key to simplify urn parsing (1 fewer case to check for).  
        // Avoid urls of type 'matt 3:14' by excludng urns with a space
        if (reference.contains(":") && !reference.contains(" ") && !reference.startsWith("sword://")) {
            reference = "sword://" + reference.replace(":", "/");
        }

        boolean isFullSwordUrn = reference.contains("/") && reference.contains(":");
        if (isFullSwordUrn) {
            // e.g. sword://StrongsRealGreek/01909
            // don't play with the reference - just assume it is correct
            result.append("<a href='").append(reference).append("'>");
            result.append(content);
            result.append("</a>");
        } else {
            Passage ref = (Passage) PassageKeyFactory.instance().getKey(parameters.getDocumentVersification(),
                    reference);
            boolean isSingleVerse = ref.countVerses() == 1;
            boolean isSimpleContent = content.length() < 3 && content.length() > 0;
            Iterator<VerseRange> it = ref.rangeIterator(RestrictionType.CHAPTER);

            if (isSingleVerse && isSimpleContent) {
                // simple verse no e.g. 1 or 2 preceding the actual verse in TSK
                result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":")
                        .append(it.next().getOsisRef()).append("'>");
                result.append(content);
                result.append("</a>");
            } else {
                // multiple complex references
                boolean isFirst = true;
                while (it.hasNext()) {
                    Key key = it.next();
                    if (!isFirst) {
                        result.append(" ");
                    }
                    // we just references the first verse in each range because that is the verse you would jump to.  It might be more correct to reference the while range i.e. key.getOsisRef() 
                    result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":")
                            .append(key.iterator().next().getOsisRef()).append("'>");
                    result.append(key);
                    result.append("</a>");
                    isFirst = false;
                }
            }
        }
    } catch (Exception e) {
        log.error("Error parsing OSIS reference:" + reference);
        // just return the content with no html markup
        result.append(content);
    }
    return result.toString();
}

From source file:br.com.nordestefomento.jrimum.domkee.financeiro.banco.febraban.Banco.java

/**
 * <p>// w  ww .ja v a2s . c  o  m
 * Verifica se o cdigo passado est ok em relao as regras:
 * <ol>
 * <li>No nulo</li>
 * <li>Numrico</li>
 * <li>Com 3 digitos</li>
 * </ol>
 * </p>
 * 
 * @param codigo - Cdigo de compensao BACEN do banco
 * 
 * @return se ok
 * 
 * @throws IllegalArgumentException
 * 
 * @since 0.2
 * 
 */
public static boolean isCodigoDeCompensacaoOK(String codigo) {

    boolean ok = false;

    if (isNotNull(codigo)) {

        if (StringUtils.isNumeric(codigo)) {

            if (codigo.length() == 3) {

                ok = true;

            } else {
                log.warn("O cdigo  de apenas 3 digitos!");
            }

        } else {
            log.warn("O cdigo de compensao deve ser numrico!");
        }
    }

    return ok;
}

From source file:fr.paris.lutece.plugins.workflow.modules.appointment.web.ExecuteWorkflowAction.java

/**
 * Do check if the given key is valid. If it is valid, then the user is
 * redirected to a page to execute a workflow action.
 * @param request The request//w ww  .ja v a2 s. c o m
 * @param response The response
 * @return The next URL to redirect to
 * @throws SiteMessageException If a site message needs to be displayed
 */
public String doExecuteWorkflowAction(HttpServletRequest request, HttpServletResponse response)
        throws SiteMessageException {
    String strIdAction = request.getParameter(PARAMETER_ID_ACTION);
    String strIdAdminUser = request.getParameter(PARAMETER_ID_ADMIN_USER);
    String strIdResource = request.getParameter(PARAMETER_ID_RESOURCE);
    String strTimestamp = request.getParameter(PARAMETER_TIMESTAMP);
    String strKey = request.getParameter(PARAMETER_KEY);

    if (StringUtils.isNotEmpty(strIdAction) && StringUtils.isNumeric(strIdAction)
            && StringUtils.isNotEmpty(strTimestamp) && StringUtils.isNumeric(strTimestamp)
            && StringUtils.isNotEmpty(strIdResource) && StringUtils.isNumeric(strIdResource)
            && StringUtils.isNotEmpty(strKey) && StringUtils.isNotEmpty(strIdAdminUser)
            && StringUtils.isNumeric(strIdAdminUser)) {
        int nIdAction = Integer.parseInt(strIdAction);

        long lTimestamp = Long.parseLong(strTimestamp);
        int nIdResource = Integer.parseInt(strIdResource);

        AdminUser user = null;
        int nIdAdminUser = Integer.parseInt(strIdAdminUser);

        if (nIdAdminUser > 0) {
            user = AdminUserHome.findByPrimaryKey(nIdAdminUser);
        }

        int nLinkLimitValidity = AppPropertiesService.getPropertyInt(PROPERTY_LINKS_LIMIT_VALIDITY,
                DEFAULT_LIMIT_TIME_VALIDITY);

        if (nLinkLimitValidity > 0) {
            Calendar calendar = GregorianCalendar
                    .getInstance(WorkflowAppointmentPlugin.getPluginLocale(Locale.getDefault()));
            calendar.add(Calendar.DAY_OF_WEEK, -1 * nLinkLimitValidity);

            if (calendar.getTimeInMillis() > lTimestamp) {
                SiteMessageService.setMessage(request, ERROR_MESSAGE_ACCESS_DENIED, SiteMessage.TYPE_ERROR);

                return null;
            }
        }

        String strComputedKey = computeAuthenticationKey(nIdAction, nIdAdminUser, lTimestamp, nIdResource);

        if ((user == null) || !StringUtils.equals(strComputedKey, strKey)) {
            SiteMessageService.setMessage(request, ERROR_MESSAGE_ACCESS_DENIED, SiteMessage.TYPE_ERROR);

            return null;
        }

        try {
            AdminAuthenticationService.getInstance().registerUser(request, user);
        } catch (AccessDeniedException e) {
            AppLogService.error(e.getMessage(), e);
        } catch (UserNotSignedException e) {
            AppLogService.error(e.getMessage(), e);
        }

        return AppointmentJspBean.getUrlExecuteWorkflowAction(request, strIdResource, strIdAction);
    }

    SiteMessageService.setMessage(request, ERROR_MESSAGE_ACCESS_DENIED, SiteMessage.TYPE_ERROR);

    return null;
}

From source file:fr.paris.lutece.plugins.suggest.service.subscription.SuggestSubscriptionProviderService.java

/**
 * {@inheritDoc}/*from  w  ww .  j  a  v a2s. co m*/
 */
@Override
public String getSubscriptionHtmlDescription(LuteceUser user, String strSubscriptionKey,
        String strIdSubscribedResource, Locale locale) {
    int nId = ((strIdSubscribedResource != null) && StringUtils.isNumeric(strIdSubscribedResource))
            ? Integer.parseInt(strIdSubscribedResource)
            : 0;

    if (nId > 0) {
        if (StringUtils.equals(SUBSCRIPTION_SUGGEST, strSubscriptionKey)) {
            Suggest suggest = SuggestHome.findByPrimaryKey(nId,
                    PluginService.getPlugin(SuggestPlugin.PLUGIN_NAME));

            if (suggest != null) {
                Object[] params = { suggest.getTitle() };

                return I18nService.getLocalizedString(MESSAGE_SUBSCRIBED_SUGGEST, params, locale);
            }
        } else if (StringUtils.equals(SUBSCRIPTION_SUGGEST_SUBMIT, strSubscriptionKey)) {
            SuggestSubmit suggestSubmit = SuggestSubmitService.getService().findByPrimaryKey(nId, false,
                    PluginService.getPlugin(SuggestPlugin.PLUGIN_NAME));

            if (suggestSubmit != null) {
                Object[] params = { suggestSubmit.getSuggestSubmitTitle() };

                return I18nService.getLocalizedString(MESSAGE_SUBSCRIBED_SUGGEST_SUBMIT, params, locale);
            }
        } else if (StringUtils.equals(SUBSCRIPTION_SUGGEST_CATEGORY, strSubscriptionKey)) {
            Category category = CategoryHome.findByPrimaryKey(nId,
                    PluginService.getPlugin(SuggestPlugin.PLUGIN_NAME));

            if (category != null) {
                Object[] params = { category.getTitle() };

                return I18nService.getLocalizedString(MESSAGE_SUBSCRIBED_SUGGEST_CATEGORY, params, locale);
            }
        }
    }

    return StringUtils.EMPTY;
}

From source file:com.commerce4j.storefront.controllers.CartController.java

@SuppressWarnings("unchecked")
public void update(HttpServletRequest request, HttpServletResponse response) {

    Gson gson = new GsonBuilder().create();
    List<Message> errors = new ArrayList<Message>();
    Map<String, Object> responseModel = new HashMap<String, Object>();

    List<CartDTO> cartEntries = getCart(request);
    Iterator inputSet = request.getParameterMap().keySet().iterator();
    while (inputSet.hasNext()) {
        String paramName = (String) inputSet.next();
        if (StringUtils.contains(paramName, "qty")) {
            String paramValue = request.getParameter(paramName);
            String paramId = StringUtils.substring(paramName, 4, paramName.length());
            if (paramId != null && StringUtils.isNumeric(paramId)) {
                for (CartDTO cartEntry : cartEntries) {
                    int entryId = cartEntry.getItem().getItemId().intValue();
                    int itemId = new Integer(paramId).intValue();
                    int cartQuantity = new Integer(paramValue).intValue();
                    if (entryId == itemId) {
                        cartEntry.setCartQuantity(cartQuantity);
                        cartEntry.setCartSubTotal(cartEntry.getItem().getItemPrice() * cartQuantity);
                        break;
                    }/*w  w  w .  ja  v a  2s .  c  om*/
                }
            }
        }
    }

    // fill response model
    if (errors.isEmpty()) {
        responseModel.put("responseCode", SUCCESS);
        responseModel.put("responseMessage", "Cart succesfully updated");
    } else {
        responseModel.put("responseCode", FAILURE);
        responseModel.put("responseMessage", "Error, Cart was not updated");
        responseModel.put("errors", errors);
    }

    // serialize output
    try {
        response.setContentType("application/json");
        OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream());
        String data = gson.toJson(responseModel);
        os.write(data);
        os.flush();
        os.close();
    } catch (IOException e) {
        logger.fatal(e);
    }

}

From source file:fr.paris.lutece.plugins.genericattributes.service.entrytype.AbstractEntryTypeSelect.java

/**
 * {@inheritDoc}/*  ww  w  . j av a  2  s .c om*/
 */
@Override
public GenericAttributeError getResponseData(Entry entry, HttpServletRequest request,
        List<Response> listResponse, Locale locale) {
    String strIdField = request.getParameter(PREFIX_ATTRIBUTE + entry.getIdEntry());
    int nIdField = -1;
    Field field = null;
    Response response = new Response();
    response.setEntry(entry);

    if (StringUtils.isNotEmpty(strIdField) && StringUtils.isNumeric(strIdField)) {
        nIdField = Integer.parseInt(strIdField);
    }

    if (nIdField != -1) {
        field = GenericAttributesUtils.findFieldByIdInTheList(nIdField, entry.getFields());
    }

    if (field != null) {
        response.setResponseValue(field.getValue());
        response.setField(field);
    }

    listResponse.add(response);

    if (entry.isMandatory()) {
        if ((field == null) || StringUtils.isBlank(field.getValue())) {
            return new MandatoryError(entry, locale);
        }
    }

    return null;
}

From source file:mp.platform.cyclone.webservices.access.AccessWebServiceImpl.java

public ChangeCredentialsStatus changeCredentials(final ChangeCredentialsParameters params) {

    // Get and validate the parameters
    final String principal = params == null ? null : StringUtils.trimToNull(params.getPrincipal());
    final String oldCredentials = params == null ? null : StringUtils.trimToNull(params.getOldCredentials());
    final String newCredentials = params == null ? null : StringUtils.trimToNull(params.getNewCredentials());
    if (principal == null || oldCredentials == null || newCredentials == null) {
        throw new ValidationException();
    }//from  ww  w  . j  av a 2s. com

    final Channel channel = WebServiceContext.getChannel();
    // Only login password and pin can be changed from here
    final Credentials credentials = channel.getCredentials();
    if (credentials != Credentials.LOGIN_PASSWORD && credentials != Credentials.PIN) {
        throw new PermissionDeniedException();
    }
    final PrincipalType principalType = channelHelper.resolvePrincipalType(params.getPrincipalType());

    // Load the member
    Member member;
    try {
        member = elementService.loadByPrincipal(principalType, principal, Element.Relationships.GROUP,
                Element.Relationships.USER);
    } catch (final Exception e) {
        return ChangeCredentialsStatus.MEMBER_NOT_FOUND;
    }

    // Check the current credentials
    try {
        accessService.checkCredentials(channel, member.getMemberUser(), oldCredentials,
                WebServiceContext.getRequest().getRemoteAddr(), WebServiceContext.getMember());
    } catch (final InvalidCredentialsException e) {
        return ChangeCredentialsStatus.INVALID_CREDENTIALS;
    } catch (final BlockedCredentialsException e) {
        return ChangeCredentialsStatus.BLOCKED_CREDENTIALS;
    }

    // The login password is numeric depending on settings. Others, are always numeric
    boolean numericPassword;
    if (credentials == Credentials.LOGIN_PASSWORD) {
        numericPassword = settingsService.getAccessSettings().isNumericPassword();
    } else {
        numericPassword = true;
    }
    if (numericPassword && !StringUtils.isNumeric(newCredentials)) {
        return ChangeCredentialsStatus.INVALID_CHARACTERS;
    }

    // Change the password
    try {
        accessService.changeMemberCredentialsByWebService(member.getMemberUser(), WebServiceContext.getClient(),
                newCredentials);
    } catch (final ValidationException e) {
        if (CollectionUtils.isNotEmpty(e.getGeneralErrors())) {
            // Actually, the only possible general error is that it is the same as another credential.
            // In this case, we return CREDENTIALS_ALREADY_USED
            return ChangeCredentialsStatus.CREDENTIALS_ALREADY_USED;
        }
        // There is a property error. Let's scrap it to determine which is it
        try {
            final ValidationError error = e.getErrorsByProperty().values().iterator().next().iterator().next();
            final String key = error.getKey();
            if (key.endsWith("obvious")) {
                // The password is too simple
                return ChangeCredentialsStatus.TOO_SIMPLE;
            } else {
                // Either must be numeric / must contain letters and numbers / must contain letters, numbers and special
                throw new Exception();
            }
        } catch (final Exception e1) {
            // If there is some kind of unexpected validation result, just return as invalid
            return ChangeCredentialsStatus.INVALID_CHARACTERS;
        }
    } catch (final CredentialsAlreadyUsedException e) {
        return ChangeCredentialsStatus.CREDENTIALS_ALREADY_USED;
    }
    return ChangeCredentialsStatus.SUCCESS;
}

From source file:com.impetus.client.kudu.schemamanager.KuduDBSchemaManager.java

@Override
protected boolean initiateClient() {
    for (String host : hosts) {
        if (host == null || !StringUtils.isNumeric(port) || port.isEmpty()) {
            logger.error("Host or port should not be null / port should be numeric");
            throw new IllegalArgumentException("Host or port should not be null / port should be numeric");
        }/*ww  w.j  a  v a2 s  . co m*/
        try {
            client = new KuduClient.KuduClientBuilder(host + ":" + port).build();
        } catch (Exception e) {
            logger.error("Database host cannot be resolved, Caused by: " + e.getMessage());
            throw new SchemaGenerationException(
                    "Database host cannot be resolved, Caused by: " + e.getMessage());
        }
    }
    return true;
}