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.gst.infrastructure.core.serialization.DatatableCommandFromApiJsonDeserializer.java

private void validateType(final DataValidatorBuilder baseDataValidator, final JsonElement column) {
    final String type = this.fromApiJsonHelper.extractStringNamed("type", column);
    baseDataValidator.reset().parameter("type").value(type).notBlank()
            .isOneOfTheseStringValues(this.supportedColumnTypes);

    if (type != null && type.equalsIgnoreCase("String")) {
        if (this.fromApiJsonHelper.parameterExists("length", column)) {
            final String lengthStr = this.fromApiJsonHelper.extractStringNamed("length", column);
            if (lengthStr != null && !StringUtils.isWhitespace(lengthStr) && StringUtils.isNumeric(lengthStr)
                    && StringUtils.isNotBlank(lengthStr)) {
                final Integer length = Integer.parseInt(lengthStr);
                baseDataValidator.reset().parameter("length").value(length).positiveAmount();
            } else if (StringUtils.isBlank(lengthStr) || StringUtils.isWhitespace(lengthStr)) {
                baseDataValidator.reset().parameter("length")
                        .failWithCode("must.be.provided.when.type.is.String");
            } else if (!StringUtils.isNumeric(lengthStr)) {
                baseDataValidator.reset().parameter("length").failWithCode("not.greater.than.zero");
            }/*  www. ja va  2 s.com*/
        } else {
            baseDataValidator.reset().parameter("length").failWithCode("must.be.provided.when.type.is.String");
        }
    } else {
        baseDataValidator.reset().parameter("length").mustBeBlankWhenParameterProvidedIs("type", type);
    }

    final String code = this.fromApiJsonHelper.extractStringNamed("code", column);
    if (type != null && type.equalsIgnoreCase("Dropdown")) {
        if (code != null) {
            baseDataValidator.reset().parameter("code").value(code).notBlank()
                    .matchesRegularExpression(DATATABLE_NAME_REGEX_PATTERN);
        } else {
            baseDataValidator.reset().parameter("code").value(code).cantBeBlankWhenParameterProvidedIs("type",
                    type);
        }
    } else {
        baseDataValidator.reset().parameter("code").value(code).mustBeBlankWhenParameterProvided("type", type);
    }
}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.SubscriptionProductJspBean.java

/**
 * Create the subscription for the user/* w w  w.ja  v  a  2 s  .  c om*/
 * @param request the HTTP request
 * @param currentUser the user who subscribe
 * @return an error if occur, null otherwise
 */
public String doUnsubscribeToProduct(HttpServletRequest request, LuteceUser currentUser) {
    String strIdProduct = request.getParameter(PARAMETER_PRODUCT_ID);

    if (StringUtils.isNotEmpty(strIdProduct) && StringUtils.isNumeric(strIdProduct)) {
        String strEmailHome = currentUser.getUserInfo(LuteceUser.HOME_INFO_ONLINE_EMAIL);
        String strEmailBusiness = currentUser.getUserInfo(LuteceUser.BUSINESS_INFO_ONLINE_EMAIL);
        String strEmail = !strEmailHome.equals("") ? strEmailHome : strEmailBusiness;
        _subscriptionProductService.doDeleteSubscriptionProduct(strEmail, strIdProduct);
    }

    return null;
}

From source file:dk.dma.msiproxy.web.MessageDetailsServlet.java

/**
 * Main GET method//www  . j  a v a 2s  . com
 * @param request servlet request
 * @param response servlet response
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Never cache the response
    response = WebUtils.nocache(response);

    // Read the request parameters
    String providerId = request.getParameter("provider");
    String lang = request.getParameter("lang");
    String messageId = request.getParameter("messageId");
    String activeNow = request.getParameter("activeNow");
    String areaHeadingIds = request.getParameter("areaHeadings");

    List<AbstractProviderService> providerServices = providers.getProviders(providerId);

    if (providerServices.size() == 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid 'provider' parameter");
        return;
    }

    // Ensure that the language is valid
    lang = providerServices.get(0).getLanguage(lang);

    // Force the encoding and the locale based on the lang parameter
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    final Locale locale = new Locale(lang);
    request = new HttpServletRequestWrapper(request) {
        @Override
        public Locale getLocale() {
            return locale;
        }
    };

    // Get the messages in the given language for the requested provider
    MessageFilter filter = new MessageFilter().lang(lang);
    Date now = "true".equals(activeNow) ? new Date() : null;
    Integer id = StringUtils.isNumeric(messageId) ? Integer.valueOf(messageId) : null;
    Set<Integer> areaHeadings = StringUtils.isNotBlank(areaHeadingIds) ? Arrays
            .asList(areaHeadingIds.split(",")).stream().map(Integer::valueOf).collect(Collectors.toSet())
            : null;

    List<Message> messages = providerServices.stream().flatMap(p -> p.getCachedMessages(filter).stream())
            // Filter on message id
            .filter(msg -> (id == null || id.equals(msg.getId())))
            // Filter on active messages
            .filter(msg -> (now == null || msg.getValidFrom() == null || msg.getValidFrom().before(now)))
            // Filter on area headings
            .filter(msg -> (areaHeadings == null || areaHeadings.contains(getAreaHeadingId(msg))))
            .collect(Collectors.toList());

    // Register the attributes to be used on the JSP apeg
    request.setAttribute("messages", messages);
    request.setAttribute("baseUri", app.getBaseUri());
    request.setAttribute("lang", lang);
    request.setAttribute("locale", locale);
    request.setAttribute("provider", providerId);

    if (request.getServletPath().endsWith("pdf")) {
        generatePdfFile(request, response);
    } else {
        generateHtmlPage(request, response);
    }
}

From source file:com.qualogy.qafe.web.UploadService.java

public String uploadFile(HttpServletRequest request) {
    ServletFileUpload upload = new ServletFileUpload();
    String errorMessage = "";
    byte[] filecontent = null;
    String appUUID = null;/*  ww w .ja va 2s  .co m*/
    String windowId = null;
    String filename = null;
    String mimeType = null;
    InputStream inputStream = null;
    ByteArrayOutputStream outputStream = null;
    try {
        FileItemIterator fileItemIterator = upload.getItemIterator(request);
        while (fileItemIterator.hasNext()) {
            FileItemStream item = fileItemIterator.next();
            inputStream = item.openStream();
            // Read the file into a byte array.
            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[8192];
            int len = 0;
            while (-1 != (len = inputStream.read(buffer))) {
                outputStream.write(buffer, 0, len);
            }
            if (filecontent == null) {
                filecontent = outputStream.toByteArray();
                filename = item.getName();
                mimeType = item.getContentType();
            }

            if (item.getFieldName().indexOf(APP_UUID) > -1) {
                appUUID = item.getFieldName()
                        .substring(item.getFieldName().indexOf(APP_UUID) + APP_UUID.length() + 1);
            }
            if (item.getFieldName().indexOf(APP_WINDOWID) > -1) {
                windowId = item.getFieldName()
                        .substring(item.getFieldName().indexOf(APP_WINDOWID) + APP_WINDOWID.length() + 1);
            }
        }

        if ((appUUID != null) && (windowId != null)) {
            if (filecontent != null) {
                int maxFileSize = 0;
                if (ApplicationCluster.getInstance()
                        .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE) != null) {
                    String maxUploadFileSzie = ApplicationCluster.getInstance()
                            .getConfigurationItem(Configuration.MAX_UPLOAD_FILESIZE);
                    if (StringUtils.isNumeric(maxUploadFileSzie)) {
                        maxFileSize = Integer.parseInt(maxUploadFileSzie);
                    }
                }

                if ((maxFileSize == 0) || (filecontent.length <= maxFileSize)) {
                    Map<String, Object> fileData = new HashMap<String, Object>();
                    fileData.put(FILE_MIME_TYPE, mimeType);
                    fileData.put(FILE_NAME, filename);
                    fileData.put(FILE_CONTENT, filecontent);

                    String uploadUUID = DataStore.KEY_LOOKUP_DATA + UniqueIdentifier.nextSeed().toString();
                    appUUID = concat(appUUID, windowId);

                    ApplicationLocalStore.getInstance().store(appUUID, uploadUUID, fileData);

                    return filename + "#" + UPLOAD_COMPLETE + "=" + uploadUUID;
                } else {
                    errorMessage = "The maxmimum filesize in bytes is " + maxFileSize;
                }
            }
        } else {
            errorMessage = "Application UUID not specified";
        }
        inputStream.close();
        outputStream.close();
    } catch (Exception e) {
        errorMessage = e.getMessage();
    }

    return UPLOAD_ERROR + "=" + "File can not be uploaded: " + errorMessage;
}

From source file:edu.ku.brc.util.GeoRefConverter.java

/**
 * @param llText//from  w  w w .j  ava  2 s  .  com
 * @return
 */
public int getDecimalSize(final String llText) {
    if (StringUtils.isBlank(llText)) {
        return 0;
    }

    int decimalFmtLen = 0;
    int decIndex = llText.lastIndexOf(decimalSep);
    if (decIndex > -1 && llText.length() > decIndex) {
        int end = llText.length();
        while (!StringUtils.isNumeric(llText.substring(decIndex + 1, end)) && end >= 0) {
            end--;
        }
        decimalFmtLen = end - decIndex - 1;
    }
    return decimalFmtLen;
}

From source file:com.neusoft.mid.clwapi.service.alarm.AlarmServiceImpl.java

/**
 * ???//from w  w  w . j  a v  a2  s.co m
 * 
 * @param token
 *            token
 * @param body
 *            ?
 * @return
 */
@Override
public Object getAlarmList(String token, String body) {
    logger.info("???");

    String organizationId = context.getHttpHeaders().getHeaderString(UserInfoKey.ORGANIZATION_ID);

    // ??
    AlarmRequ iAlarmRequ = JacksonUtils.fromJsonRuntimeException(body, AlarmRequ.class);
    // ??
    iAlarmRequ.setEndTime(StringUtils.strip(iAlarmRequ.getEndTime()));
    iAlarmRequ.setStartTime(StringUtils.strip(iAlarmRequ.getStartTime()));
    iAlarmRequ.setNum(StringUtils.strip(iAlarmRequ.getNum()));
    iAlarmRequ.setOperat(StringUtils.strip(iAlarmRequ.getOperat()));
    iAlarmRequ.setOrganizationId(organizationId);

    // ??
    logger.info("??");
    if (StringUtils.isEmpty(iAlarmRequ.getOperat()) || StringUtils.isEmpty(iAlarmRequ.getNum())
            || StringUtils.isEmpty(iAlarmRequ.getType())) {
        logger.error("??");
        throw new ApplicationException(ErrorConstant.ERROR10001, Response.Status.BAD_REQUEST);
    } else if (StringUtils.isEmpty(iAlarmRequ.getStartTime()) || StringUtils.isEmpty(iAlarmRequ.getEndTime())) {
        logger.error("????");
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    } else if (HttpConstant.TIME_ZERO.equals(iAlarmRequ.getStartTime())
            && HttpConstant.TIME_ZERO.equals(iAlarmRequ.getEndTime())) {
        logger.error("?????0");
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    } else if (HttpConstant.TIME_24_HOURS_AGO.equalsIgnoreCase(iAlarmRequ.getStartTime())
            && !HttpConstant.TIME_ZERO.equals(iAlarmRequ.getEndTime())) {
        logger.error(
                "??-hh24????0");
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    } else if (!StringUtils.isNumeric(iAlarmRequ.getNum())) {
        logger.error("??num?");
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    } else if (!StringUtils.isEmpty(iAlarmRequ.getPage()) && !StringUtils.isNumeric(iAlarmRequ.getPage())) {
        logger.error("??page?");
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    }
    // page?0
    iAlarmRequ.setPage(StringUtils.isEmpty(iAlarmRequ.getPage()) ? HttpConstant.ZERO : iAlarmRequ.getPage());

    // ???
    int page = Integer.valueOf(iAlarmRequ.getPage());
    int num = Integer.valueOf(iAlarmRequ.getNum());

    // ????
    if (page < 0) {
        logger.error("??page?0");
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    }

    // ?
    // 
    if (iAlarmRequ.getOperat().equals(HttpConstant.ALARMPORT_OPERATE_UNTREATED)) {
        iAlarmRequ.setOperat(HttpConstant.ALARMPORT_OPERATE_UNTREATED_DB);
    } else if (iAlarmRequ.getOperat().equals(HttpConstant.ALARMPORT_OPERATE_TREATED)) {
        iAlarmRequ.setOperat(HttpConstant.ALARMPORT_OPERATE_TREATED_DB);
    } else if (iAlarmRequ.getOperat().equals(HttpConstant.ALARMPORT_OPERATE_ALL)) {
        iAlarmRequ.setOperat(HttpConstant.ALARMPORT_OPERATE_ALL_DB);
    } else {
        logger.error("???operat?0?1?2");
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    }

    if (iAlarmRequ.getType().equals(HttpConstant.ALARMPORT_TYPE_OVERSPEED)) {
        iAlarmRequ.setSpeedFlag(true);
        iAlarmRequ.setOverLoadFlag(null);
    } else if (iAlarmRequ.getType().equals(HttpConstant.ALARMPORT_TYPE_OVERLOAD)) {
        iAlarmRequ.setSpeedFlag(null);
        iAlarmRequ.setOverLoadFlag(true);
    } else if (iAlarmRequ.getType().equals(HttpConstant.ALARMPORT_TYPE_ALL)) {
        iAlarmRequ.setSpeedFlag(null);
        iAlarmRequ.setOverLoadFlag(null);
    } else {
        logger.error("???type?0?1?2");
        throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
    }

    // ????
    if (!HttpConstant.TIME_ZERO.equals(iAlarmRequ.getStartTime())
            && !HttpConstant.TIME_24_HOURS_AGO.equalsIgnoreCase(iAlarmRequ.getStartTime())) {
        try {
            TimeUtil.parseStringToDate(iAlarmRequ.getStartTime(), HttpConstant.TIME_FORMAT);
        } catch (ParseException e) {
            logger.error("????" + e.getMessage());
            throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
        }
    }
    if (!HttpConstant.TIME_ZERO.equals(iAlarmRequ.getEndTime())) {
        try {
            TimeUtil.parseStringToDate(iAlarmRequ.getEndTime(), HttpConstant.TIME_FORMAT);
        } catch (ParseException e) {
            logger.error("?????" + e.getMessage());
            throw new ApplicationException(ErrorConstant.ERROR10002, Response.Status.BAD_REQUEST);
        }
    }

    logger.info("???");

    // ?
    if (HttpConstant.TIME_ZERO.equals(iAlarmRequ.getStartTime())) {
        iAlarmRequ.setStartTime(null);
    } else if (HttpConstant.TIME_24_HOURS_AGO.equalsIgnoreCase(iAlarmRequ.getStartTime())) {
        Date dBTime = iCommonMapper.getDBTime();
        Date oneDayAgo = TimeUtil.get24Ago(dBTime);
        String startTime = TimeUtil.formatDateToString(oneDayAgo, HttpConstant.TIME_FORMAT);
        iAlarmRequ.setStartTime(startTime);
    }

    if (HttpConstant.TIME_ZERO.equals(iAlarmRequ.getEndTime())) {
        iAlarmRequ.setEndTime(null);
    }

    iAlarmRequ.setEnId(context.getHttpHeaders().getHeaderString(UserInfoKey.ENTERPRISE_ID));

    // ?
    if (page != 0) {
        iAlarmRequ.setStartRow(String.valueOf(page * num - num));
        iAlarmRequ.setEndRow(String.valueOf(page * num));
    } else if (num != 0) {
        iAlarmRequ.setStartRow(HttpConstant.ZERO);
        iAlarmRequ.setEndRow(String.valueOf(num));
    } else {
        iAlarmRequ.setStartRow(null);
        iAlarmRequ.setEndRow(null);
    }

    logger.info("????");
    // ?
    List<AlarmInfo> temp = iAlarmMapper.getAlarmList(iAlarmRequ);
    logger.info("??");

    // 
    if (temp == null || temp.size() == 0) {
        logger.info("??");
        return Response.noContent().build();
    }
    logger.info("??");

    if (logger.isDebugEnabled()) {
        logger.debug("List size:" + temp.size());
        Iterator<AlarmInfo> it = temp.iterator();
        while (it.hasNext()) {
            logger.debug(it.next().toString());
        }
    }

    // 
    List<AlarmInfo> content = new ArrayList<AlarmInfo>();
    Iterator<AlarmInfo> it = temp.iterator();
    while (it.hasNext()) {
        AlarmInfo a = it.next();
        if (!StringUtils.isEmpty(a.getSpeeding())) {
            a.setAlarmCont(a.getSpeeding());
        } else if (!StringUtils.isEmpty(a.getPhotoId())) {
            a.setAlarmCont(a.getPhotoId());
        } else {
            a.setAlarmCont(null);
        }
        content.add(a);
    }

    // 
    AlarmResp iAlarmResp = new AlarmResp();
    iAlarmResp.setContent(content);

    logger.info("????");

    return JacksonUtils.toJsonRuntimeException(iAlarmResp);
}

From source file:mp.platform.cyclone.webservices.utils.server.FieldHelper.java

/**
 * Convert an array of FieldValue instances to a collection of CustomFieldValue
 */// w ww. j a  va2  s.  c o m
@SuppressWarnings("unchecked")
public <T extends CustomFieldValue> Collection<T> toValueCollection(
        final Collection<? extends CustomField> fields, final List<? extends FieldValueVO> fieldValues) {
    if (CollectionUtils.isEmpty(fields) || CollectionUtils.isEmpty(fieldValues)) {
        return Collections.emptySet();
    }
    final List<T> customValues = new ArrayList<T>();
    for (final FieldValueVO fieldValue : fieldValues) {
        final String key = fieldValue.getField();
        CustomField field;
        // Check if key is the id or internal name
        if (StringUtils.isNumeric(key)) {
            // By id
            field = CustomFieldHelper.findById(fields, Long.parseLong(key));
        } else {
            field = CustomFieldHelper.findByInternalName(fields, key);
        }
        if (field == null) {
            throw new IllegalArgumentException("Custom field " + key + " not found");
        }
        final T value = (T) ClassHelper.instantiate(field.getNature().getValueType());
        value.setField(field);
        value.setValue(fieldValue.getValue());
        if (StringUtils.isNotEmpty(field.getPattern())) {
            value.setValue(StringHelper.removeMask(field.getPattern(), value.getValue()));
        }
        if (fieldValue instanceof RegistrationFieldValueVO && value instanceof MemberCustomFieldValue) {
            final RegistrationFieldValueVO reg = (RegistrationFieldValueVO) fieldValue;
            final MemberCustomFieldValue memberValue = (MemberCustomFieldValue) value;
            memberValue.setHidden(reg.isHidden());
        }
        customValues.add(value);
    }
    return customValues;
}

From source file:fr.paris.lutece.plugins.directory.service.record.DirectoryRecordExtendableResourceService.java

/**
 * {@inheritDoc}//from   w w w  .j a  v  a  2  s  .co m
 */
@Override
public String getResourceUrl(String strIdResource, String strResourceType) {
    if (StringUtils.isNotBlank(strIdResource) && StringUtils.isNumeric(strIdResource)) {
        Record record = RecordHome.findByPrimaryKey(Integer.parseInt(strIdResource),
                PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME));
        UrlItem urlItem = new UrlItem(AppPathService.getPortalUrl());
        urlItem.addParameter(PARAMETER_PAGE, CONSTANT_DIRECTORY);
        urlItem.addParameter(PARAMETER_ID_DIRECTORY, record.getDirectory().getIdDirectory());
        urlItem.addParameter(PARAMETER_ID_DIRECTORY_RECORD, strIdResource);

        return urlItem.getUrl();
    }

    return null;
}

From source file:com.greenline.hrs.admin.cache.redis.util.RedisInfoParser.java

/**
 * RedisInfoMapT?RedisInfoMapRedis?//  w  ww.  j  av  a 2  s . co m
 *
 * @param redisInfoMap Map
 * @return instanceTypeinfomapnullinfoMap?instancenullRedisServerInfoPO
 */
public static List<RedisKeyspaceInfo> parserToKeySpaceInfo(Map<String, String> redisInfoMap) {
    if (redisInfoMap == null || redisInfoMap.isEmpty()) {
        return Collections.EMPTY_LIST;
    }
    int dbSize = 16;
    String dbSizeStr = redisInfoMap.get(RedisCommonConst.DB_SIZE);
    if (StringUtils.isNumeric(dbSizeStr)) {
        dbSize = Integer.valueOf(dbSizeStr);
    }
    List<RedisKeyspaceInfo> result = new ArrayList<RedisKeyspaceInfo>(dbSize * 2);
    for (int i = 0; i < dbSize; i++) {
        RedisKeyspaceInfo keyspaceInfo = new RedisKeyspaceInfo();
        // TODO createTime??
        keyspaceInfo.setCreateTime(DateTime.now().toDate());
        keyspaceInfo.setDbIndex(i);
        keyspaceInfo.setKeys(0L);
        keyspaceInfo.setExpires(0L);
        String keyspaceStr = redisInfoMap.get("db" + i);
        if (keyspaceStr != null) {
            String[] properties = StringUtils.split(keyspaceStr, KS_PROPERTY_DELIMITER);
            if (properties.length >= KS_PROPERTY_MIN_SIZE) {
                keyspaceInfo.setKeys(Long.valueOf(properties[1]));
                keyspaceInfo.setExpires(Long.valueOf(properties[3]));
                result.add(keyspaceInfo);
            }
        }
    }
    return result;
}

From source file:com.flexive.shared.content.FxPK.java

/**
 * Construct a primary key from a String
 *
 * @param value string value/* ww w .j  av  a  2 s. c o m*/
 * @return primary key
 * @throws IllegalArgumentException if the string does not represent a valid PK value
 * @see #toString()
 */
public static FxPK fromString(String value) {
    if (StringUtils.isNumeric(value)) {
        return new FxPK(Long.parseLong(value));
    } else if (value == null || "NEW".equals(value) || value.indexOf('.') <= 0) {
        return new FxPK();
    }
    String[] pk = value.split("\\.");
    if (pk == null || pk.length != 2)
        throw new IllegalArgumentException("Invalid PK value: " + value);
    long _id, _ver;
    try {
        _id = Long.parseLong(pk[0]);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException(e);
    }
    try {
        _ver = Integer.parseInt(pk[1]);
    } catch (NumberFormatException e) {
        if ("MAX".equals(pk[1]))
            _ver = MAX;
        else if ("LIVE".equals(pk[1]))
            _ver = LIVE;
        else
            throw new IllegalArgumentException("Illegal version: " + pk[1]);
    }
    return new FxPK(_id, (int) _ver);
}