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.impetus.kundera.rest.common.EntityUtils.java

/**
 * @param queryString/*from   www . j  a v  a 2  s  .c o m*/
 * @param q
 */
public static void setQueryParameters(String queryString, String parameterString, Query q) {
    Map<String, String> paramsMap = new HashMap<String, String>();

    StringTokenizer st = new StringTokenizer(parameterString, "&");
    while (st.hasMoreTokens()) {
        String element = st.nextToken();
        paramsMap.put(element.substring(0, element.indexOf("=")),
                element.substring(element.indexOf("=") + 1, element.length()));
    }
    KunderaQuery kq = ((QueryImpl) q).getKunderaQuery();
    Set<Parameter<?>> parameters = kq.getParameters();
    for (String paramName : paramsMap.keySet()) {
        String value = paramsMap.get(paramName);
        if (paramName.equalsIgnoreCase("firstResult")) {
            q.setFirstResult(Integer.parseInt(value));
        } else if (paramName.equalsIgnoreCase("maxResult")) {
            q.setMaxResults(Integer.parseInt(value));
        } else if (StringUtils.isNumeric(paramName)) {
            for (Parameter param : parameters) {
                if (param.getPosition() == Integer.parseInt(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    q.setParameter(Integer.parseInt(paramName), paramValue);
                    break;
                }
            }
        } else {
            for (Parameter param : parameters) {
                if (param.getName().equals(paramName)) {
                    Class<?> paramClass = param.getParameterType();
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor(paramClass);
                    Object paramValue = accessor.fromString(paramClass, value);
                    q.setParameter(paramName, paramValue);

                    break;
                }
            }

        }
    }
}

From source file:com.alibaba.dubboadmin.web.mvc.RouterController.java

@RequestMapping("/governance/applications/{app}/{elements}/{element}/{type}")
public String appRouter(@PathVariable("app") String app, @PathVariable("elements") String elements,
        @PathVariable("element") String element, @PathVariable("type") String type, HttpServletRequest request,
        HttpServletResponse response, Model model) {
    if (app != null) {
        model.addAttribute("app", app);
    }//from ww  w .j  a v  a  2s  .c om
    if (StringUtils.isNumeric(element)) {
        //service action, shield, recover..
        Long[] ids = new Long[1];
        ids[0] = Long.valueOf(element);
        model.addAttribute("service", request.getParameter("service"));
        try {
            Method m = servicesController.getClass().getDeclaredMethod(type, Long[].class,
                    HttpServletRequest.class, HttpServletResponse.class, Model.class);
            Object result = m.invoke(servicesController, ids, request, response, model);
            return (String) result;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (elements.equals("services")) {
        model.addAttribute("service", element);
    } else if (elements.equals("addresses")) {
        model.addAttribute("address", element);
    }

    String name = WebConstants.mapper.get(type);
    if (name != null) {
        Object controller = SpringUtil.getBean(name);
        if (controller != null) {
            try {
                Method index = controller.getClass().getDeclaredMethod("index", HttpServletRequest.class,
                        HttpServletResponse.class, Model.class);
                Object result = index.invoke(controller, request, response, model);
                return (String) result;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return "";
}

From source file:com.tuncaysenturk.jira.plugins.compatibility.servlet.ConfigureServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (userManager.getRemoteUsername() == null) {
        redirectToLogin(req, resp);/*from w w  w . ja  v a 2 s  . co m*/
        return;
    } else if (!hasAdminPermission()) {
        handleUnpermittedUser(req, resp);
        return;
    }
    logger.info(JTPConstants.LOG_PRE + "setting are being changed");

    PropertySet propSet = ComponentManager.getComponent(PropertiesManager.class).getPropertySet();
    propSet.setString("projectId", req.getParameter("projectId"));
    propSet.setString("userId", req.getParameter("userId"));
    propSet.setString("issueTypeId", req.getParameter("issueTypeId"));
    propSet.setBoolean("onlyFollowers", "on".equalsIgnoreCase(req.getParameter("onlyFollowers")));

    final Map<String, Object> context = initVelocityContext(resp);
    @SuppressWarnings("unchecked")
    List<String> errorMessages = (List<String>) context.get("errorMessages");
    if (userManager.getUserProfile(req.getParameter("userId")) == null)
        errorMessages.add(i18nResolver.getText("jtp.configuration.userid.invalid"));
    if (StringUtils.isEmpty(req.getParameter("projectId"))
            || !StringUtils.isNumeric(req.getParameter("projectId")))
        errorMessages.add(i18nResolver.getText("jtp.configuration.projectId.invalid"));
    context.put("errorMessages", errorMessages);
    if (!StringUtils.isEmpty(req.getParameter("projectId"))
            && StringUtils.isNumeric(req.getParameter("projectId"))) {
        if (projectManager.getProjectObj(Long.parseLong(req.getParameter("projectId"))) == null)
            errorMessages.add(i18nResolver.getText("jtp.configuration.projectId.invalid"));
    }

    renderer.render(TEMPLATE, context, resp.getWriter());

}

From source file:edu.ku.brc.specify.toycode.mexconabio.MakeGBIFProcessHash.java

@Override
public void process(final int type, final int options) {
    final double HRS = 1000.0 * 60.0 * 60.0;
    final long PAGE_CNT = 1000000;

    totalRecs = BasicSQLUtils.getCount(dbGBIFConn, "SELECT COUNT(*) FROM raw");

    int minIndex = BasicSQLUtils.getCount(dbGBIFConn, "SELECT MIN(id) FROM raw");
    //int maxIndex = BasicSQLUtils.getCount(dbGBIFConn, "SELECT MAX(id) FROM raw");

    int segs = (int) (totalRecs / PAGE_CNT) + 1;

    try {//w  ww.  j  av a2s. c om
        pw = new PrintWriter("GroupHash.log");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    long procRecs = 0;
    long startTime = System.currentTimeMillis();
    int secsThreshold = 0;

    try {
        String idsInsert = "INSERT INTO group_hash_ids (GrpID, RawID) VALUES (?,?)";
        insertIds = dbDstConn.prepareStatement(idsInsert);

        String gbifsnibInsert = "INSERT INTO group_hash (collnum, genus, year, mon, cnt) VALUES (?,?,?,?,?)";
        insertStmt = dbDstConn.prepareStatement(gbifsnibInsert);

        String gbifsnibUpdate = "UPDATE group_hash SET cnt=? WHERE id = ?";
        updateStmt = dbDstConn.prepareStatement(gbifsnibUpdate);

        String gbifsnibCheck = "SELECT id FROM group_hash WHERE collnum=? AND genus=? AND year=?";
        checkStmt = dbDstConn.prepareStatement(gbifsnibCheck);

    } catch (SQLException ex) {
        ex.printStackTrace();
    }

    for (int pc = 0; pc < segs; pc++) {
        try {
            String clause = String.format(" FROM raw WHERE id > %d AND id < %d", (pc * PAGE_CNT) + minIndex,
                    ((pc + 1) * PAGE_CNT) + minIndex + 1);
            String gbifSQL = "SELECT  id, collector_num, genus, year, month " + clause;

            System.out.println(gbifSQL);
            pw.println(gbifSQL);

            stmt = dbGBIFConn.createStatement(ResultSet.FETCH_FORWARD, ResultSet.CONCUR_READ_ONLY);
            stmt.setFetchSize(Integer.MIN_VALUE);

            String msg = "Starting Query... " + totalRecs;
            System.out.println(msg);
            pw.println(msg);

            ResultSet rs = stmt.executeQuery(gbifSQL);

            msg = String.format("Starting Processing... Total Records %d  Max Score: %d  Threshold: %d",
                    totalRecs, maxScore, thresholdScore);
            System.out.println(msg);
            pw.println(msg);

            while (rs.next()) {
                procRecs++;

                String year = rs.getString(4);

                year = StringUtils.isNotEmpty(year) ? year.trim() : null;

                if (StringUtils.isNotEmpty(year) && !StringUtils.isNumeric(year)) {
                    continue;
                }

                int rawId = rs.getInt(1);
                String collnum = rs.getString(2);
                String genus = rs.getString(3);
                String mon = rs.getString(5);

                collnum = StringUtils.isNotEmpty(collnum) ? collnum.trim() : null;
                genus = StringUtils.isNotEmpty(genus) ? genus.trim() : null;
                mon = StringUtils.isNotEmpty(mon) ? mon.trim() : null;

                int c = 0;
                if (collnum == null)
                    c++;
                if (genus == null)
                    c++;
                if (year == null)
                    c++;

                if (c == 2) {
                    continue;
                }

                collnum = collnum != null ? collnum : "";
                genus = genus != null ? genus : "";
                year = year != null ? year : "";
                mon = mon != null ? mon : "";

                if (collnum.length() > 64) {
                    collnum = collnum.substring(0, 63);
                }

                if (genus.length() > 64) {
                    genus = genus.substring(0, 63);
                }

                if (year.length() > 8) {
                    year = year.substring(0, 8);
                }

                if (mon.length() > 8) {
                    mon = year.substring(0, 8);
                }

                String name = String.format("%s_%s_%s", collnum, genus, year);
                DataEntry de = groupHash.get(name);
                if (de != null) {
                    de.cnt++;
                } else {
                    de = getDataEntry(collnum, genus, year, mon);
                    groupHash.put(name, de);
                }
                de.ids.add(rawId);

                if (groupHash.size() > MAX_RECORDS_SEG) {
                    writeHash();
                }
            }
            rs.close();

            if (groupHash.size() > 0) {
                writeHash();
            }

            System.out.println("Done with seg " + pc);
            pw.println("Done with seg " + pc);

        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (Exception ex) {
            }
        }

        long endTime = System.currentTimeMillis();
        long elapsedTime = endTime - startTime;

        double timePerRecord = (elapsedTime / procRecs);

        double hrsLeft = ((totalRecs - procRecs) * timePerRecord) / HRS;

        int seconds = (int) (elapsedTime / 60000.0);
        if (secsThreshold != seconds) {
            secsThreshold = seconds;

            String msg = String.format("Elapsed %8.2f hr.mn   Percent: %6.3f  Hours Left: %8.2f ",
                    ((double) (elapsedTime)) / HRS, 100.0 * ((double) procRecs / (double) totalRecs), hrsLeft);
            System.out.println(msg);
            pw.println(msg);
            pw.flush();
        }
    }

    try {
        if (insertStmt != null) {
            insertStmt.close();
        }
        if (updateStmt != null) {
            updateStmt.close();
        }
        if (checkStmt != null) {
            checkStmt.close();
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    }

    String msg = String.format("Done - Writes: %d  Updates: %d", writeCnt, updateCnt);
    System.out.println(msg);
    pw.println(msg);
    pw.flush();
    pw.close();
}

From source file:fr.paris.lutece.plugins.genericalert.web.NotifyReminderTaskComponent.java

@Override
public String getDisplayConfigForm(HttpServletRequest request, Locale locale, ITask task) {

    String strIdForm = request.getParameter(PARAMETER_ID_FORM) == null ? StringUtils.EMPTY
            : request.getParameter(PARAMETER_ID_FORM);
    int nIdForm = 0;
    TaskNotifyReminderConfig config = null;
    if (StringUtils.isNotEmpty(strIdForm) && StringUtils.isNumeric(strIdForm)) {
        nIdForm = Integer.parseInt(strIdForm);
    }/*w w  w . j a  v  a 2s.co  m*/
    if (StringUtils.isNotEmpty(strIdForm)) {
        config = TaskNotifyReminderConfigHome.findByIdForm(task.getId(), nIdForm);
    }

    List<AppointmentForm> listForms = AppointmentFormHome.getActiveAppointmentFormsList();
    List<String> listTel = getListPhoneEntries(nIdForm);
    List<State> listStates = null;

    AppointmentForm tmpForm = AppointmentFormHome.findByPrimaryKey(nIdForm);
    if (tmpForm != null) {
        StateFilter stateFilter = new StateFilter();
        stateFilter.setIdWorkflow(tmpForm.getIdWorkflow());
        listStates = _stateService.getListStateByFilter(stateFilter);
    }
    //initialiser la configuration
    if (config == null) {
        config = new TaskNotifyReminderConfig();
        config.setIdTask(task.getId());
        config.setListReminderAppointment(new ArrayList<ReminderAppointment>());
    }

    String strMaxLenght = DatastoreService.getDataValue(PROPERTY_MAX_LENGTH_SMS_TEXT, StringUtils.EMPTY);

    if (!DatastoreService.existsKey(PROPERTY_MAX_LENGTH_SMS_TEXT)) {
        DatastoreService.setDataValue(PROPERTY_MAX_LENGTH_SMS_TEXT,
                AppPropertiesService.getProperty(PROPERTY_MAX_LENGTH_SMS_TEXT));
    }

    Map<String, Object> model = new HashMap<String, Object>();
    model.put(MARK_CONFIG, config);
    model.put(MARK_LIST_FORM, listForms);
    model.put(MARK_LIST_PHONE_NUMBERS, listTel);
    model.put(MARK_LIST_STATUS_WORKFLOW, listStates);
    model.put(MARK_WEBAPP_URL, AppPathService.getBaseUrl(request));
    model.put(MARK_LOCALE, locale);
    model.put(MARK_LOCALE_TINY, locale);
    model.put(MARK_SMS_TEXT_LENGTH, strMaxLenght);

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_TASK_NOTIFY_REMINDER_CONFIG, locale, model);

    return template.getHtml();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.resourceAllocationManager.ExecutionPeriodDA.java

public ActionForward chooseStudent(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    final StudentContextSelectionBean studentContextSelectionBean = getRenderedObject();

    final String number = studentContextSelectionBean.getNumber();
    if (number != null && !number.isEmpty()) {
        final AcademicInterval academicInterval = studentContextSelectionBean.getAcademicInterval();
        final ExecutionInterval executionInterval = ExecutionInterval.getExecutionInterval(academicInterval);

        final SearchParameters searchParameters = new SearchParameters();
        if (StringUtils.isNumeric(number)) {
            searchParameters.setStudentNumber(Integer.valueOf(number));
        } else {/* www .  ja  v  a2 s .c  o  m*/
            searchParameters.setUsername(number);
        }
        final CollectionPager<Person> people = new SearchPerson().run(searchParameters,
                new SearchPerson.SearchPersonPredicate(searchParameters));
        final Collection<Registration> registrations = new ArrayList<Registration>();
        for (final Person person : people.getCollection()) {
            if (person.getStudent() != null) {
                for (final Registration registration : person.getStudent().getRegistrationsSet()) {
                    if (registration.hasAnyActiveState((ExecutionSemester) executionInterval)) {
                        registrations.add(registration);
                    }
                }
            }
        }

        if (studentContextSelectionBean.getToEdit()) {
            request.setAttribute("toEditScheduleRegistrations", registrations);
        } else {
            request.setAttribute("registrations", registrations);
            request.setAttribute("timeTableExecutionSemester", executionInterval);
        }

    }

    return prepare(mapping, form, request, response);
}

From source file:edu.ku.brc.dbsupport.DatabaseDriverInfo.java

public Integer getPortAsInt() {
    return port != null && StringUtils.isNumeric(this.port) ? Integer.parseInt(this.port) : null;
}

From source file:fr.paris.lutece.plugins.identitystore.modules.indexer.service.IdentityIndexerService.java

/**
 * Build an identity to a customer./*from w  w  w  .j av  a  2  s  . co  m*/
 *
 * @param identity
 *            the identity
 * @return the customer
 */
private Customer buildCustomer(Identity identity) {
    Customer customer = new Customer();

    customer.setId(identity.getCustomerId());
    customer.setConnectionId(identity.getConnectionId());

    if (identity.getAttributes() != null) {

        for (IdentityAttribute attribute : identity.getAttributes().values()) {
            String strKeyName = attribute.getAttributeKey().getKeyName();

            if (ATTRIBUTE_IDENTITY_USER_GENDER.equals(strKeyName)) {
                String strGender = getAttributeValue(attribute);
                customer.setIdTitle(StringUtils.isBlank(strGender) || !StringUtils.isNumeric(strGender) ? 0
                        : Integer.parseInt(strGender));
                continue;
            }

            if (ATTRIBUTE_IDENTITY_USER_NAME_GIVEN.equals(strKeyName)) {
                customer.setFirstname(getAttributeValue(attribute));
                continue;
            }

            if (ATTRIBUTE_IDENTITY_USER_NAME_PREFERRED_NAME.equals(strKeyName)) {
                customer.setLastname(getAttributeValue(attribute));
                continue;
            }

            if (ATTRIBUTE_IDENTITY_USER_NAME_FAMILY_NAME.equals(strKeyName)) {
                customer.setFamilyname(getAttributeValue(attribute));
                continue;
            }

            if (ATTRIBUTE_IDENTITY_USER_HOMEINFO_ONLINE_EMAIL.equals(strKeyName)) {
                customer.setEmail(getAttributeValue(attribute));
                continue;
            }

            if (ATTRIBUTE_IDENTITY_USER_HOMEINFO_TELECOM_TELEPHONE_NUMBER.equals(strKeyName)) {
                customer.setFixedPhoneNumber(getAttributeValue(attribute));
                continue;
            }

            if (ATTRIBUTE_IDENTITY_USER_HOMEINFO_TELECOM_MOBILE_NUMBER.equals(strKeyName)) {
                customer.setMobilePhone(getAttributeValue(attribute));
                continue;
            }

            if (ATTRIBUTE_IDENTITY_USER_BDATE.equals(strKeyName)) {
                customer.setBirthDate(getAttributeValue(attribute));
                continue;
            }

            customer.addAttributes(strKeyName, getAttributeValue(attribute));
        }

    }

    return customer;
}

From source file:eu.eidas.node.auth.connector.AUCONNECTORUtil.java

/**
 * Checks if the requested SP's QAALevel is less than configured SP's QAALevel.
 *
 * @param spQAALevel The QAA Level of the SP.
 * @param confQAALevel The QAA Level from the configurations.
 * @return True if spQAALevel is valid. False otherwise.
 *///from   ww  w .j  a  va 2s . c o m
private boolean isValidSPQAALevel(final String spQAALevel, final String confQAALevel) {

    return StringUtils.isNumeric(spQAALevel) && StringUtils.isNumeric(confQAALevel)
            && Integer.parseInt(confQAALevel) >= Integer.parseInt(spQAALevel);
}

From source file:net.sourceforge.fenixedu.domain.studentCurriculum.ExternalEnrolment.java

@Override
public Integer getFinalGrade() {
    final String grade = getGradeValue();
    return (StringUtils.isEmpty(grade) || !StringUtils.isNumeric(grade)) ? null : Integer.valueOf(grade);
}