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:edu.ku.brc.specify.toycode.mexconabio.MexConvToSQLNew.java

public void convert(final String tableName, final String fileName) {
    String str = "";
    int fldLen = 0;
    int inx = 0;//from www . j av a2 s .  co  m

    Connection conn = null;
    Statement stmt = null;
    try {
        conn = DriverManager.getConnection(
                "jdbc:mysql://localhost/mex?characterEncoding=UTF-8&autoReconnect=true", "root", "root");
        stmt = conn.createStatement();

        int[] fieldLengths = null;

        BasicSQLUtils.deleteAllRecordsFromTable(conn, tableName, SERVERTYPE.MySQL);
        Vector<Integer> types = new Vector<Integer>();
        Vector<String> names = new Vector<String>();

        String selectStr = null;
        String prepareStr = null;
        try {
            prepareStr = FileUtils.readFileToString(new File("prepare_stmt.txt"));
            selectStr = FileUtils.readFileToString(new File("select.txt"));

        } catch (IOException e) {
            e.printStackTrace();
        }

        int idInx = selectStr.indexOf("ID,");
        if (idInx == 0) {
            selectStr = selectStr.substring(3);
        }

        File file = new File("/Users/rods/Documents/" + fileName);
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        //SimpleDateFormat stf = new SimpleDateFormat("k:mm:ss");

        int rowCnt = 0;
        try {
            System.out.println(prepareStr);

            PreparedStatement pStmt = conn.prepareStatement(prepareStr);
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
            str = in.readLine();

            String[] fieldNames = StringUtils.split(str, ",");
            //String[] fieldNamesDB = StringUtils.split(selectStr, ",");

            String sql = "SELECT " + selectStr + " FROM " + tableName;
            System.out.println(sql);

            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();

            fieldLengths = new int[rsmd.getColumnCount()];
            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                fieldLengths[i - 1] = rsmd.getPrecision(i);
                types.add(rsmd.getColumnType(i));
                names.add(rsmd.getColumnName(i));
                System.out.println((i > 1 ? fieldNames[i - 2] : "ID") + " / " + rsmd.getColumnName(i) + " - "
                        + rsmd.getPrecision(i));
            }

            int numCols = rsmd.getColumnCount();
            rs.close();

            System.out.println("Number of Fields: " + numCols);

            str = in.readLine();
            while (str != null) {
                //System.err.println(str);

                str = StringUtils.replace(str.substring(1, str.length() - 1), "\",\"", "|");

                Vector<String> fields = split(str);
                if (fields.size() != numCols) {
                    System.out.println("numCols: " + numCols + " != " + fields.size() + "fields.size()");
                    continue;
                }

                int col = 1;
                inx = 0;
                for (String fld : fields) {
                    String field = fld.trim();
                    //if (field.length() > 1)
                    //{
                    //    field = field.substring(1, field.length()-1);
                    //}
                    //if (inx > 204) break;

                    fldLen = field.length();

                    pStmt.setObject(col, null);

                    switch (types.get(inx)) {
                    case java.sql.Types.LONGVARCHAR:
                    case java.sql.Types.VARCHAR:
                    case java.sql.Types.LONGNVARCHAR: {
                        if (field.length() > 0) {
                            if (field.length() <= fieldLengths[inx]) {
                                pStmt.setString(col, field);
                            } else {
                                System.err.println(String.format("The data for `%s` (%d) is too big %d f[%s]",
                                        names.get(inx), fieldLengths[inx], field.length(), field));
                                pStmt.setString(col, null);
                            }
                        } else {
                            pStmt.setString(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.DOUBLE:
                    case java.sql.Types.FLOAT: {
                        if (StringUtils.isNotEmpty(field)) {
                            if (StringUtils.isNumeric(field)) {
                                pStmt.setDouble(col, field.length() > 0 ? Double.parseDouble(field) : null);
                            } else {
                                System.err.println(col + " Bad Number[" + field + "] ");
                                pStmt.setDate(col, null);
                            }
                        } else {
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.INTEGER: {
                        if (StringUtils.isNotEmpty(field)) {
                            if (StringUtils.isNumeric(field)) {
                                pStmt.setInt(col, field.length() > 0 ? Integer.parseInt(field) : null);
                            } else {
                                System.err.println(col + " Bad Number[" + field + "] ");
                                pStmt.setDate(col, null);
                            }
                        } else {
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    case java.sql.Types.TIME: {
                        Time time = null;
                        try {
                            time = Time.valueOf(field);
                        } catch (Exception ex) {
                        }
                        pStmt.setTime(col, time);
                    }
                        break;

                    case java.sql.Types.DATE: {
                        try {
                            if (StringUtils.isNotEmpty(field)) {
                                if (StringUtils.contains(field, "/")) {
                                    field = StringUtils.replace(field, "/", "-");
                                } else if (StringUtils.contains(field, " ")) {
                                    field = StringUtils.replace(field, " ", "-");
                                }
                                pStmt.setDate(col,
                                        field.length() > 0 ? new java.sql.Date(sdf.parse(field).getTime())
                                                : null);
                            } else {
                                pStmt.setDate(col, null);
                            }
                        } catch (Exception ex) {
                            System.err.println(col + " Bad Date[" + field + "]\n" + str);
                            pStmt.setDate(col, null);
                        }
                    }
                        break;

                    default: {
                        System.err.println("Error - " + types.get(inx));
                    }
                    }
                    inx++;
                    col++;
                }
                pStmt.execute();
                str = in.readLine();
                rowCnt++;
            }
            in.close();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        } catch (Exception e) {
            System.err.println("Row: " + rowCnt);
            System.err.println(str);
            System.err.println(inx + "  " + fieldLengths[inx] + " - Field Len: " + fldLen);
            e.printStackTrace();
        }

        /*BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        while (bis.available() > 0)
        {
        int bytesRead = bis.read(bytes);
        if (bytesRead > 0)
        {
            System.arraycopy(bytes, bytesRead, buffer, bufEndInx, bytesRead);
            bufEndInx += bytesRead;
            int inx = 0;
            while (inx < bufEndInx)
            {
                if (buffer[inx] != '\n')
                {
                    String line = 
                }
                inx++;
            }
        }
        }*/

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            stmt.close();
            conn.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.emergya.persistenceGeo.web.RestFoldersAdminController.java

/**
 * This method saves a folder related with a user
 * /*from w  ww .  ja  v  a 2  s.c  om*/
 * @param user
 */
@RequestMapping(value = "/persistenceGeo/saveFolder/{username}", method = RequestMethod.POST)
public @ResponseBody FolderDto saveFolder(@PathVariable String username, @RequestParam("name") String name,
        @RequestParam("enabled") String enabled, @RequestParam("isChannel") String isChannel,
        @RequestParam("isPlain") String isPlain,
        @RequestParam(value = "parentFolder", required = false) String parentFolder) {
    try {
        /*
         * //TODO: Secure with logged user String username = ((UserDetails)
         * SecurityContextHolder.getContext()
         * .getAuthentication().getPrincipal()).getUsername();
         */
        UserDto user = userAdminService.obtenerUsuario(username);
        if (StringUtils.isEmpty(parentFolder) || !StringUtils.isNumeric(parentFolder)) {
            FolderDto rootFolder = foldersAdminService.getRootFolder(user.getId());
            return saveFolderBy(name, enabled, isChannel, isPlain,
                    rootFolder != null ? rootFolder.getId() : null, user.getId(), null);
        } else {
            return saveFolderBy(name, enabled, isChannel, isPlain, Long.decode(parentFolder), user.getId(),
                    null);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:fr.paris.lutece.plugins.crm.modules.mylutece.web.CRMMyluteceJspBean.java

/**
 * Do remove crm user./*from w w  w .j  a  v a2 s. c o m*/
 *
 * @param request the request
 * @return the string
 */
public String doRemoveCRMUser(HttpServletRequest request) {
    String strIdCRMUser = request.getParameter(PARAMETER_ID_CRM_USER);

    if (StringUtils.isBlank(strIdCRMUser) || !StringUtils.isNumeric(strIdCRMUser)) {
        return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_STOP);
    }

    int nIdCRMUser = Integer.parseInt(strIdCRMUser);
    CRMUser user = _crmUserService.findByPrimaryKey(nIdCRMUser);

    if (user != null) {
        _crmUserService.remove(nIdCRMUser);
        MyLuteceUserManager.doRemoveMyLuteceUser(user.getUserGuid(), request, getLocale());
    }

    return getUrlManageUsers(request, true).getUrl();
}

From source file:fr.paris.lutece.plugins.subscribe.web.SubscribeApp.java

/**
 * Do remove a subscription//  w  w w . ja v  a2  s.  c  om
 * @param request The request
 * @return a XPage
 * @throws SiteMessageException If the user is not allow to modify the
 *             subscription
 */
@Action(ACTION_DO_REMOVE_URL)
public XPage doRemoveSubscription(HttpServletRequest request) throws SiteMessageException {
    String strIdSubscription = request.getParameter(PARAMETER_ID_SUBSCRIPTION);

    if (StringUtils.isNotEmpty(strIdSubscription) && StringUtils.isNumeric(strIdSubscription)) {
        int nIdSubscription = Integer.parseInt(strIdSubscription);
        LuteceUser user = SecurityService.getInstance().getRegisteredUser(request);
        Subscription subscription = SubscriptionService.getInstance().findBySubscriptionId(nIdSubscription);
        if (user != null && subscription != null
                && StringUtils.equals(subscription.getUserId(), user.getName())) {
            SubscriptionService.getInstance().removeSubscription(nIdSubscription, true);
        } else {
            SiteMessageService.setMessage(request, MESSAGE_ACCESS_DENIED, SiteMessage.TYPE_STOP);
        }
    }

    String strReferer = request.getParameter(PARAMETER_FROM_URL);
    String strUrl;
    if (StringUtils.isNotEmpty(strReferer)) {
        strUrl = strReferer;
    } else {
        strUrl = AppPathService.getBaseUrl(request) + JSP_URL_SUBSCRIBE_XPAGE;
    }

    redirect(request, strUrl);
    return new XPage();
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.academicAdministration.executionCourseManagement.InsertExecutionCourseDispatchAction.java

private InfoExecutionCourseEditor fillInfoExecutionCourse(ActionForm form, HttpServletRequest request) {

    DynaActionForm dynaForm = (DynaValidatorForm) form;
    InfoExecutionCourseEditor infoExecutionCourse = new InfoExecutionCourseEditor();

    String name = (String) dynaForm.get("name");
    infoExecutionCourse.setNome(name);//from w  w  w. j a va 2s .com

    String code = (String) dynaForm.get("code");
    infoExecutionCourse.setSigla(code);

    String executionPeriodId = (String) dynaForm.get("executionPeriodId");
    InfoExecutionPeriod infoExecutionPeriod = null;
    if (!StringUtils.isEmpty(executionPeriodId) && StringUtils.isNumeric(executionPeriodId)) {
        infoExecutionPeriod = new InfoExecutionPeriod(
                (ExecutionSemester) FenixFramework.getDomainObject(executionPeriodId));
    }

    infoExecutionCourse.setInfoExecutionPeriod(infoExecutionPeriod);

    String comment = "";
    if ((String) dynaForm.get("comment") != null) {
        comment = (String) dynaForm.get("comment");
    }
    infoExecutionCourse.setComment(comment);

    String entryPhaseString = dynaForm.getString("entryPhase");
    EntryPhase entryPhase = null;
    if (entryPhaseString != null && entryPhaseString.length() > 0) {
        entryPhase = EntryPhase.valueOf(entryPhaseString);
    }
    infoExecutionCourse.setEntryPhase(entryPhase);

    return infoExecutionCourse;
}

From source file:fr.paris.lutece.portal.web.admin.AdminPagePortletJspBean.java

/**
 * Processes the removal of the portlet//from ww w . ja v  a 2s.co m
 *
 * @param request The http request
 * @return The Jsp URL of the process result
 * @throws AccessDeniedException if the user is not authorized to manage the portlet
 */
public String doRemovePortlet(HttpServletRequest request) throws AccessDeniedException {
    String strPortletId = request.getParameter(Parameters.PORTLET_ID);
    if (!StringUtils.isNumeric(strPortletId)) {
        return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS, AdminMessage.TYPE_ERROR);
    }
    int nPortletId = Integer.parseInt(strPortletId);
    Portlet portlet = null;
    try {
        portlet = PortletHome.findByPrimaryKey(nPortletId);
    } catch (NullPointerException e) {
        AppLogService.error("Error looking for portlet with id " + nPortletId, e);
    }
    if (portlet == null || portlet.getId() != nPortletId) {
        return AdminMessageService.getMessageUrl(request, Messages.MESSAGE_INVALID_ENTRY,
                new Object[] { nPortletId }, AdminMessage.TYPE_ERROR);
    }
    AdminUser user = AdminUserService.getAdminUser(request);
    if (!RBACService.isAuthorized(PortletType.RESOURCE_TYPE, portlet.getPortletTypeId(),
            PortletResourceIdService.PERMISSION_MANAGE, user)) {
        throw new AccessDeniedException("User " + user + " is not authorized to permission "
                + PortletResourceIdService.PERMISSION_MANAGE + " on portlet " + nPortletId);
    }
    ArrayList<String> listErrors = new ArrayList<String>();
    Locale locale = AdminUserService.getLocale(request);

    if (PortletRemovalListenerService.getService().checkForRemoval(strPortletId, listErrors, locale)) {
        portlet.remove();
    }

    String strUrl = JSP_ADMIN_SITE + "?" + Parameters.PAGE_ID + "=" + portlet.getPageId();
    return strUrl;
}

From source file:fr.paris.lutece.portal.web.user.attribute.AttributeJspBean.java

/**
 * Get the user attribute modification interface
 * @param request HttpServletRequest//  w  w  w  . j  av  a2s  .  com
 * @return the html form
 */
public String getModifyAttribute(HttpServletRequest request) {
    String strIdAttribute = request.getParameter(PARAMETER_ID_ATTRIBUTE);

    if (StringUtils.isNotBlank(strIdAttribute) && StringUtils.isNumeric(strIdAttribute)) {
        // Check if the ID attribute is correct
        int nIdAttribute = Integer.parseInt(strIdAttribute);

        IAttribute attribute = _attributeService.getAttributeWithFields(nIdAttribute, getLocale());

        setPageTitleProperty(attribute.getPropertyModifyPageTitle());

        HtmlTemplate template;
        Map<String, Object> model = new HashMap<String, Object>();
        model.put(MARK_ATTRIBUTE, attribute);
        model.put(MARK_ATTRIBUTE_FIELDS_LIST, attribute.getListAttributeFields());

        template = AppTemplateService.getTemplate(attribute.getTemplateModifyAttribute(), getLocale(), model);

        return getAdminPage(template.getHtml());
    }

    // Otherwise, we redirect the user to the attribute management interface
    return getManageAttributes(request);
}

From source file:com.thoughtworks.go.server.controller.JobController.java

private boolean isValidCounter(String pipelineCounter) {
    return StringUtils.isNumeric(pipelineCounter) || JobIdentifier.LATEST.equalsIgnoreCase(pipelineCounter);
}

From source file:com.adobe.acs.commons.data.Variant.java

/**
 * Truthiness is any non-empty string that looks like a non-zero number or looks like it is True, Yes, or X
 *
 * @param s String to evaluate/*from  ww w .  j  av a2s. c  o m*/
 * @return True if it is truthy, otherwise false
 */
public boolean isStringTruthy(String s) {
    if (s == null || s.trim().isEmpty()) {
        return false;
    } else if (StringUtils.isNumeric(s)) {
        return Long.parseLong(s) != 0;
    } else {
        char c = s.trim().toLowerCase().charAt(0);
        return (c == 't' || c == 'y' || c == 'x');
    }
}

From source file:com.evolveum.midpoint.web.component.search.Search.java

private ObjectFilter createFilterForSearchValue(SearchItem item, DisplayableValue searchValue,
        PrismContext ctx) {/*from  www . j  a v  a2 s . c o m*/

    ItemDefinition definition = item.getDefinition();
    ItemPath path = item.getPath();

    if (definition instanceof PrismReferenceDefinition) {
        return QueryBuilder.queryFor(ObjectType.class, ctx).item(path, definition)
                .ref((PrismReferenceValue) searchValue.getValue()).buildFilter();
    }

    PrismPropertyDefinition propDef = (PrismPropertyDefinition) definition;
    if ((propDef.getAllowedValues() != null && !propDef.getAllowedValues().isEmpty())
            || DOMUtil.XSD_BOOLEAN.equals(propDef.getTypeName())) {
        //we're looking for enum value, therefore equals filter is ok
        //or if it's boolean value
        DisplayableValue displayableValue = (DisplayableValue) searchValue.getValue();
        Object value = displayableValue.getValue();
        return QueryBuilder.queryFor(ObjectType.class, ctx).item(path, propDef).eq(value).buildFilter();
    } else if (DOMUtil.XSD_INT.equals(propDef.getTypeName())
            || DOMUtil.XSD_INTEGER.equals(propDef.getTypeName())
            || DOMUtil.XSD_LONG.equals(propDef.getTypeName())
            || DOMUtil.XSD_SHORT.equals(propDef.getTypeName())) {

        String text = (String) searchValue.getValue();
        if (!StringUtils.isNumeric(text) && (searchValue instanceof SearchValue)) {
            ((SearchValue) searchValue).clear();
            return null;
        }
        Object value = Long.parseLong((String) searchValue.getValue());
        return QueryBuilder.queryFor(ObjectType.class, ctx).item(path, propDef).eq(value).buildFilter();
    } else if (DOMUtil.XSD_STRING.equals(propDef.getTypeName())) {
        String text = (String) searchValue.getValue();
        return QueryBuilder.queryFor(ObjectType.class, ctx).item(path, propDef).contains(text)
                .matchingCaseIgnore().buildFilter();
    } else if (SchemaConstants.T_POLY_STRING_TYPE.equals(propDef.getTypeName())) {
        //we're looking for string value, therefore substring filter should be used
        String text = (String) searchValue.getValue();
        PolyStringNormalizer normalizer = ctx.getDefaultPolyStringNormalizer();
        String value = normalizer.normalize(text);
        return QueryBuilder.queryFor(ObjectType.class, ctx).item(path, propDef).contains(text).matchingNorm()
                .buildFilter();
    }

    //we don't know how to create filter from search item, should not happen, ha ha ha :)
    //at least we try to cleanup field

    if (searchValue instanceof SearchValue) {
        ((SearchValue) searchValue).clear();
    }

    return null;
}