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.evolveum.midpoint.prism.parser.DomParser.java

private int parseMultiplicity(String maxOccursString, Element element) throws SchemaException {
    if (PrismConstants.MULTIPLICITY_UNBONUNDED.equals(maxOccursString)) {
        return -1;
    }/*from  ww  w .  ja  va 2s  .c om*/
    if (maxOccursString.startsWith("-")) {
        return -1;
    }
    if (StringUtils.isNumeric(maxOccursString)) {
        return Integer.valueOf(maxOccursString);
    } else {
        throw new SchemaException("Expecetd numeric value for " + PrismConstants.A_MAX_OCCURS.getLocalPart()
                + " attribute on " + DOMUtil.getQName(element) + " but got " + maxOccursString);
    }
}

From source file:fr.paris.lutece.plugins.asynchronousupload.web.AsynchronousUploadApp.java

/**
 * Get the main upload JavaScript file. Available HTTP parameters are :
 * <ul>//from   w w  w . ja v  a  2  s.  c o m
 * <li><b>handler</b> : Name of the handler that will manage the
 * asynchronous upload.</li>
 * <li><b>maxFileSize</b> : The maximum size (in bytes) of uploaded files.
 * Default value is 2097152</li>
 * </ul>
 * @param request The request
 * @return The content of the JavaScript file
 */
public String getMainUploadJs(HttpServletRequest request) {
    String strBaseUrl = AppPathService.getBaseUrl(request);

    String strHandlerName = request.getParameter(PARAMETER_HANDLER);
    String strMaxFileSize = request.getParameter(PARAMETER_MAX_FILE_SIZE);
    String strImageMaxWidth = request.getParameter(PARAMETER_IMAGE_MAX_WIDTH);
    String strImageMaxHeight = request.getParameter(PARAMETER_IMAGE_MAX_HEIGHT);
    String strPreviewMaxWidth = request.getParameter(PARAMETER_PREVIEW_MAX_WIDTH);
    String strPreviewMaxHeight = request.getParameter(PARAMETER_PREVIEW_MAX_HEIGHT);
    String strFieldName = request.getParameter(PARAMETER_FIELD_NAME);

    IAsyncUploadHandler handler = getHandler(strHandlerName);

    int nMaxFileSize, nImageMaxHeight, nImageMaxWidth, nPreviewMaxWidth, nPreviewMaxHeight;

    if (StringUtils.isNotEmpty(strMaxFileSize) && StringUtils.isNumeric(strMaxFileSize)) {
        nMaxFileSize = Integer.parseInt(strMaxFileSize);
    } else {
        nMaxFileSize = DEFAULT_MAX_FILE_SIZE;
    }

    if (StringUtils.isNotEmpty(strImageMaxHeight) && StringUtils.isNumeric(strImageMaxHeight)) {
        nImageMaxHeight = Integer.parseInt(strImageMaxHeight);
    } else {
        nImageMaxHeight = DEFAULT_IMAGE_MAX_HEIGHT;
    }

    if (StringUtils.isNotEmpty(strImageMaxWidth) && StringUtils.isNumeric(strImageMaxWidth)) {
        nImageMaxWidth = Integer.parseInt(strImageMaxWidth);
    } else {
        nImageMaxWidth = DEFAULT_IMAGE_MAX_WIDTH;
    }
    if (StringUtils.isNotEmpty(strPreviewMaxWidth) && StringUtils.isNumeric(strPreviewMaxWidth)) {
        nPreviewMaxWidth = Integer.parseInt(strPreviewMaxWidth);
    } else {
        nPreviewMaxWidth = DEFAULT_PREVIEW_MAX_HEIGHT;
    }

    if (StringUtils.isNotEmpty(strPreviewMaxHeight) && StringUtils.isNumeric(strPreviewMaxHeight)) {
        nPreviewMaxHeight = Integer.parseInt(strPreviewMaxHeight);
    } else {
        nPreviewMaxHeight = DEFAULT_PREVIEW_MAX_WIDTH;
    }

    if (!StringUtils.isNotEmpty(strFieldName)) {
        strFieldName = DEFAULT_FIELD_NAME;
    }

    String strKey = ((strHandlerName != null) ? strHandlerName : StringUtils.EMPTY) + strBaseUrl
            + ((strMaxFileSize == null) ? StringUtils.EMPTY : strMaxFileSize)
            + ((strImageMaxWidth == null) ? StringUtils.EMPTY : strImageMaxWidth)
            + ((strImageMaxHeight == null) ? StringUtils.EMPTY : strImageMaxHeight)
            + ((strPreviewMaxWidth == null) ? StringUtils.EMPTY : strPreviewMaxWidth)
            + ((strPreviewMaxHeight == null) ? StringUtils.EMPTY : strPreviewMaxHeight)
            + ((strFieldName == null) ? StringUtils.EMPTY : strFieldName);

    String strContent = (String) UploadCacheService.getInstance().getFromCache(strKey);

    if (strContent == null) {
        Map<String, Object> model = new HashMap<String, Object>();

        model.put(MARK_BASE_URL, strBaseUrl);
        model.put(MARK_UPLOAD_URL, URL_UPLOAD_SERVLET);
        model.put(MARK_HANDLER_NAME, strHandlerName);
        model.put(PARAMETER_MAX_FILE_SIZE, nMaxFileSize);
        model.put(PARAMETER_IMAGE_MAX_WIDTH, nImageMaxWidth);
        model.put(PARAMETER_IMAGE_MAX_HEIGHT, nImageMaxHeight);
        model.put(PARAMETER_PREVIEW_MAX_WIDTH, nPreviewMaxWidth);
        model.put(PARAMETER_PREVIEW_MAX_HEIGHT, nPreviewMaxHeight);
        model.put(MARK_SUBMIT_PREFIX, handler.getUploadSubmitPrefix());
        model.put(MARK_DELETE_PREFIX, handler.getUploadDeletePrefix());
        model.put(MARK_CHECKBOX_PREFIX, handler.getUploadCheckboxPrefix());
        model.put(PARAMETER_FIELD_NAME, strFieldName);

        HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_MAIN_UPLOAD_JS, request.getLocale(),
                model);
        strContent = template.getHtml();
        UploadCacheService.getInstance().putInCache(strKey, strContent);
    }

    return strContent;
}

From source file:com.naver.timetable.bo.TableParsingBO.java

/**
 * @param lectures /*  w  w w.  ja v a  2 s.c  o m*/
 * @return ??  ? <, ?>?  .
 */
public List<LectureTime> makeTimeList(List<Lecture> lectures) {
    List<LectureTime> lectureTimeList = Lists.newArrayList();
    for (Lecture lecture : lectures) {
        String[] result = StringUtils.split(lecture.getRoom(), " ");
        String weekDay = "";
        for (String t : result) {
            // ? ?? .
            if (StringUtils.isNumeric(t)) {
                LectureTime ct = new LectureTime();
                ct.setLectureID(lecture.getLectureID());
                ct.setWeekDay(weekDay + t);
                lectureTimeList.add(ct);
            } else if (t.length() < 4) {
                weekDay = WEEKDAY.get(t);
            }
        }
    }
    return lectureTimeList;
}

From source file:com.nridge.ds.solr.SolrParentChild.java

private String extractOffset(String aValue) {
    String startingOffset = FIELD_FETCH_OFFSET_DEFAULT;
    if (StringUtils.isNotEmpty(aValue)) {
        int offset1 = aValue.lastIndexOf("(");
        int offset2 = aValue.lastIndexOf(")");
        if ((offset1 != -1) && (offset2 != -1)) {
            String countString = aValue.substring(offset1 + 1, offset2);
            if (StringUtils.contains(countString, StrUtl.CHAR_COMMA)) {
                ArrayList<String> offsetLimitList = StrUtl.expandToList(countString, StrUtl.CHAR_COMMA);
                if (offsetLimitList.size() > 0) {
                    String offsetValue = offsetLimitList.get(0);
                    if (StringUtils.isNumeric(offsetValue))
                        startingOffset = offsetValue;
                }//from ww w  . j a v  a  2 s. co  m
            }
        }
    }

    return startingOffset;
}

From source file:eu.eidas.auth.commons.EIDASUtil.java

/**
 * Gets the Eidas error code in the error message if exists!
 *
 * @param errorMessage The message to get the error code if exists;
 * @return the error code if exists. Returns null otherwise.
 *//*  ww  w  .j ava2  s  .c  o m*/
public static String getEidasErrorCode(final String errorMessage) {
    if (StringUtils.isNotBlank(errorMessage)
            && errorMessage.indexOf(EIDASValues.ERROR_MESSAGE_SEP.toString()) >= 0) {
        final String[] msgSplitted = errorMessage.split(EIDASValues.ERROR_MESSAGE_SEP.toString());
        if (msgSplitted.length == 2 && StringUtils.isNumeric(msgSplitted[0])) {
            return msgSplitted[0];
        }
    }
    return null;
}

From source file:com.criticalsoftware.mobics.presentation.action.account.EditInformationContactActionBean.java

/**
 * Validates the NIF// w  ww .  ja v  a 2 s  .c om
 * 
 * @param nif
 * @return true if valid
 */
private boolean isValidNIF(final String nif) {
    // Verifica se  nulo, se  numrico e se tem 9 dgitos
    if ((nif != null) && StringUtils.isNumeric(nif) && (nif.length() == 9)) {
        // Obtem o primeiro nmero do NIF
        char c = nif.charAt(0);
        // Verifica se o primeiro nmero  (1, 2, 5, 6, 8 ou 9)
        if ((c == '1') || (c == '2') || (c == '5') || (c == '6') || (c == '8') || (c == '9')) {
            // Calculo do Digito de Controle
            int checkDigit = c * 9;
            for (int i = 2; i <= 8; i++) {
                checkDigit += nif.charAt(i - 1) * (10 - i);
            }
            checkDigit = 11 - (checkDigit % 11);

            // Se o digito de controle  maior que dez, coloca-o a zero
            if (checkDigit >= 10) {
                checkDigit = 0;
            }

            // Compara o digito de controle com o ltimo numero do NIF
            // Se igual, o NIF  vlido.
            if (Character.forDigit(checkDigit, 10) == nif.charAt(8)) {
                return true;
            }
        }
    }
    return false;
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/* w w w . j  a  v  a  2  s  .  c o m*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static ErrorType sendMsg(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, final String port, final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;

    if (StringUtils.isEmpty(toEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR");
        return ErrorType.Error;
    }

    if (StringUtils.isEmpty(fromEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR");
        return ErrorType.Error;
    }

    //if (isGmailEmail())
    //{
    //    return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment);
    //}

    Boolean fail = false;
    ArrayList<String> userAndPass = new ArrayList<String>();

    boolean isSSL = security.equals("SSL");

    String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable",
            "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback",
            "mail.imap.auth.plain.disable", };
    Properties props = System.getProperties();
    for (String key : keys) {
        props.remove(key);
    }

    props.put("mail.smtp.host", host); //$NON-NLS-1$

    if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) {
        props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        props.remove("mail.smtp.port");
    }

    if (StringUtils.isNotEmpty(security)) {
        if (security.equals("TLS")) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

        } else if (isSSL) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$

            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.imap.auth.plain.disable", "true");
        }
    }

    Session session = null;
    if (isSSL) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uName, pWord);
            }
        });

    } else {
        session = Session.getInstance(props, null);
    }

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
        log.debug("Port:     " + port); //$NON-NLS-1$
        log.debug("Security: " + security); //$NON-NLS-1$
    }

    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));

        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            try {
                InternetAddress[] address = { new InternetAddress(toEMailAddr) };
                msg.setRecipients(Message.RecipientType.TO, address);

            } catch (javax.mail.internet.AddressException ex) {
                UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr);
                return ErrorType.Error;
            }
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        final int TRIES = 1;

        // set the Date: header
        msg.setSentDate(new Date());

        Exception exception = null;
        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                if (isSSL) {
                    Transport.send(msg);

                } else {
                    t.connect(host, userName, password);
                    t.sendMessage(msg, msg.getAllRecipients());
                }

                fail = false;

            } catch (SendFailedException mex) {
                mex.printStackTrace();
                exception = mex;

            } catch (MessagingException mex) {
                if (mex.getCause() instanceof UnknownHostException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host);

                } else if (mex.getCause() instanceof ConnectException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError(
                            "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port);

                } else {
                    mex.printStackTrace();
                    exception = mex;
                }

            } catch (Exception mex) {
                mex.printStackTrace();
                exception = mex;

            } finally {
                if (t != null) {
                    log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                    t.close();
                }
            }

            if (exception != null) {
                fail = true;

                instance.lastErrorMsg = exception.toString();

                //wrong username or password, get new one
                if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName);

                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) { //the user is done
                        instance.lastErrorMsg = null;
                        return ErrorType.Cancel;
                    }
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }

            }
            exception = null;

        } while (fail && cnt < TRIES);

    } catch (Exception mex) {
        //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        mex.printStackTrace();
        Exception ex = null;
        if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return ErrorType.Error;

    }

    if (fail) {
        return ErrorType.Error;
    } //else

    return ErrorType.OK;
}

From source file:fr.paris.lutece.portal.service.admin.DefaultImportAdminUserService.java

/**
 * {@inheritDoc}/*from w ww .j  av a  2s  .  c  om*/
 */
@Override
protected List<CSVMessageDescriptor> readLineOfCSVFile(String[] strLineDataArray, int nLineNumber,
        Locale locale, String strBaseUrl) {
    List<CSVMessageDescriptor> listMessages = new ArrayList<CSVMessageDescriptor>();
    int nIndex = 0;

    String strAccessCode = strLineDataArray[nIndex++];
    String strLastName = strLineDataArray[nIndex++];
    String strFirstName = strLineDataArray[nIndex++];
    String strEmail = strLineDataArray[nIndex++];

    boolean bUpdateUser = getUpdateExistingUsers();
    int nUserId = 0;

    if (bUpdateUser) {
        int nAccessCodeUserId = AdminUserHome.checkAccessCodeAlreadyInUse(strAccessCode);
        int nEmailUserId = AdminUserHome.checkEmailAlreadyInUse(strEmail);

        if (nAccessCodeUserId > 0) {
            nUserId = nAccessCodeUserId;
        } else if (nEmailUserId > 0) {
            nUserId = nEmailUserId;
        }

        bUpdateUser = nUserId > 0;
    }

    String strStatus = strLineDataArray[nIndex++];
    int nStatus = 0;

    if (StringUtils.isNotEmpty(strStatus) && StringUtils.isNumeric(strStatus)) {
        nStatus = Integer.parseInt(strStatus);
    } else {
        Object[] args = { strLastName, strFirstName, nStatus };
        String strMessage = I18nService.getLocalizedString(MESSAGE_NO_STATUS, args, locale);
        CSVMessageDescriptor message = new CSVMessageDescriptor(CSVMessageLevel.INFO, nLineNumber, strMessage);
        listMessages.add(message);
    }

    String strLocale = strLineDataArray[nIndex++];
    String strLevelUser = strLineDataArray[nIndex++];
    int nLevelUser = 3;

    if (StringUtils.isNotEmpty(strLevelUser) && StringUtils.isNumeric(strLevelUser)) {
        nLevelUser = Integer.parseInt(strLevelUser);
    } else {
        Object[] args = { strLastName, strFirstName, nLevelUser };
        String strMessage = I18nService.getLocalizedString(MESSAGE_NO_LEVEL, args, locale);
        CSVMessageDescriptor message = new CSVMessageDescriptor(CSVMessageLevel.INFO, nLineNumber, strMessage);
        listMessages.add(message);
    }

    // We ignore the reset password attribute because we set it to true anyway.
    // String strResetPassword = strLineDataArray[nIndex++];
    nIndex++;

    boolean bResetPassword = true;
    String strAccessibilityMode = strLineDataArray[nIndex++];
    boolean bAccessibilityMode = Boolean.parseBoolean(strAccessibilityMode);
    // We ignore the password max valid date attribute because we changed the password.
    // String strPasswordMaxValidDate = strLineDataArray[nIndex++];
    nIndex++;

    Timestamp passwordMaxValidDate = null;
    // We ignore the account max valid date attribute
    // String strAccountMaxValidDate = strLineDataArray[nIndex++];
    nIndex++;

    Timestamp accountMaxValidDate = AdminUserService.getAccountMaxValidDate();
    String strDateLastLogin = strLineDataArray[nIndex++];
    Timestamp dateLastLogin = new Timestamp(AdminUser.DEFAULT_DATE_LAST_LOGIN.getTime());

    if (StringUtils.isNotBlank(strDateLastLogin)) {
        DateFormat dateFormat = new SimpleDateFormat();
        Date dateParsed;

        try {
            dateParsed = dateFormat.parse(strDateLastLogin);
        } catch (ParseException e) {
            AppLogService.error(e.getMessage(), e);
            dateParsed = null;
        }

        if (dateParsed != null) {
            dateLastLogin = new Timestamp(dateParsed.getTime());
        }
    }

    AdminUser user = null;

    if (bUpdateUser) {
        user = AdminUserHome.findByPrimaryKey(nUserId);
    } else {
        user = new LuteceDefaultAdminUser();
    }

    user.setAccessCode(strAccessCode);
    user.setLastName(strLastName);
    user.setFirstName(strFirstName);
    user.setEmail(strEmail);
    user.setStatus(nStatus);
    user.setUserLevel(nLevelUser);
    user.setLocale(new Locale(strLocale));
    user.setAccessibilityMode(bAccessibilityMode);

    if (bUpdateUser) {
        user.setUserId(nUserId);
        // We update the user
        AdminUserHome.update(user);
    } else {
        // We create the user
        user.setPasswordReset(bResetPassword);
        user.setPasswordMaxValidDate(passwordMaxValidDate);
        user.setAccountMaxValidDate(accountMaxValidDate);
        user.setDateLastLogin(dateLastLogin);

        if (AdminAuthenticationService.getInstance().isDefaultModuleUsed()) {
            LuteceDefaultAdminUser defaultAdminUser = (LuteceDefaultAdminUser) user;
            String strPassword = AdminUserService.makePassword();
            defaultAdminUser.setPassword(AdminUserService.encryptPassword(strPassword));
            AdminUserHome.create(defaultAdminUser);
            AdminUserService.notifyUser(AppPathService.getProdUrl(strBaseUrl), user, strPassword,
                    PROPERTY_MESSAGE_EMAIL_SUBJECT_NOTIFY_USER, TEMPLATE_NOTIFY_USER);
        } else {
            AdminUserHome.create(user);
        }
    }

    // We remove any previous right, roles, workgroup and attributes of the user
    AdminUserHome.removeAllRightsForUser(user.getUserId());
    AdminUserHome.removeAllRolesForUser(user.getUserId());

    AdminUserFieldFilter auFieldFilter = new AdminUserFieldFilter();
    auFieldFilter.setIdUser(user.getUserId());
    AdminUserFieldHome.removeByFilter(auFieldFilter);

    // We get every attribute, role, right and workgroup of the user
    Map<Integer, List<String>> mapAttributesValues = new HashMap<Integer, List<String>>();
    List<String> listAdminRights = new ArrayList<String>();
    List<String> listAdminRoles = new ArrayList<String>();
    List<String> listAdminWorkgroups = new ArrayList<String>();

    while (nIndex < strLineDataArray.length) {
        String strValue = strLineDataArray[nIndex];

        if (StringUtils.isNotBlank(strValue) && (strValue.indexOf(getAttributesSeparator()) > 0)) {
            int nSeparatorIndex = strValue.indexOf(getAttributesSeparator());
            String strLineId = strValue.substring(0, nSeparatorIndex);

            if (StringUtils.isNotBlank(strLineId)) {
                if (StringUtils.equalsIgnoreCase(strLineId, CONSTANT_RIGHT)) {
                    listAdminRights.add(strValue.substring(nSeparatorIndex + 1));
                } else if (StringUtils.equalsIgnoreCase(strLineId, CONSTANT_ROLE)) {
                    listAdminRoles.add(strValue.substring(nSeparatorIndex + 1));
                } else if (StringUtils.equalsIgnoreCase(strLineId, CONSTANT_WORKGROUP)) {
                    listAdminWorkgroups.add(strValue.substring(nSeparatorIndex + 1));
                } else {
                    int nAttributeId = Integer.parseInt(strLineId);

                    String strAttributeValue = strValue.substring(nSeparatorIndex + 1);
                    List<String> listValues = mapAttributesValues.get(nAttributeId);

                    if (listValues == null) {
                        listValues = new ArrayList<String>();
                    }

                    listValues.add(strAttributeValue);
                    mapAttributesValues.put(nAttributeId, listValues);
                }
            }
        }

        nIndex++;
    }

    // We create rights
    for (String strRight : listAdminRights) {
        AdminUserHome.createRightForUser(user.getUserId(), strRight);
    }

    // We create roles
    for (String strRole : listAdminRoles) {
        AdminUserHome.createRoleForUser(user.getUserId(), strRole);
    }

    // We create workgroups
    for (String strWorkgoup : listAdminWorkgroups) {
        AdminWorkgroupHome.addUserForWorkgroup(user, strWorkgoup);
    }

    List<IAttribute> listAttributes = _attributeService.getAllAttributesWithoutFields(locale);
    Plugin pluginCore = PluginService.getCore();

    // We save the attributes found
    for (IAttribute attribute : listAttributes) {
        if (attribute instanceof ISimpleValuesAttributes) {
            List<String> listValues = mapAttributesValues.get(attribute.getIdAttribute());

            if ((listValues != null) && (listValues.size() > 0)) {
                int nIdField = 0;
                boolean bCoreAttribute = (attribute.getPlugin() == null)
                        || StringUtils.equals(pluginCore.getName(), attribute.getPlugin().getName());

                for (String strValue : listValues) {
                    int nSeparatorIndex = strValue.indexOf(getAttributesSeparator());

                    if (nSeparatorIndex >= 0) {
                        nIdField = 0;

                        try {
                            nIdField = Integer.parseInt(strValue.substring(0, nSeparatorIndex));
                        } catch (NumberFormatException e) {
                            nIdField = 0;
                        }

                        strValue = strValue.substring(nSeparatorIndex + 1);
                    } else {
                        nIdField = 0;
                    }

                    String[] strValues = { strValue };

                    try {
                        List<AdminUserField> listUserFields = ((ISimpleValuesAttributes) attribute)
                                .getUserFieldsData(strValues, user);

                        for (AdminUserField userField : listUserFields) {
                            if (userField != null) {
                                userField.getAttributeField().setIdField(nIdField);
                                AdminUserFieldHome.create(userField);
                            }
                        }

                        if (!bCoreAttribute) {
                            for (AdminUserFieldListenerService adminUserFieldListenerService : SpringContextService
                                    .getBeansOfType(AdminUserFieldListenerService.class)) {
                                adminUserFieldListenerService.doCreateUserFields(user, listUserFields, locale);
                            }
                        }
                    } catch (Exception e) {
                        AppLogService.error(e.getMessage(), e);

                        String strErrorMessage = I18nService
                                .getLocalizedString(MESSAGE_ERROR_IMPORTING_ATTRIBUTES, locale);
                        CSVMessageDescriptor error = new CSVMessageDescriptor(CSVMessageLevel.ERROR,
                                nLineNumber, strErrorMessage);
                        listMessages.add(error);
                    }
                }
            }
        }
    }

    return listMessages;
}

From source file:fr.paris.lutece.plugins.search.solr.web.SolrConfigurationJspBean.java

public String doSort(HttpServletRequest request) {
    String strDefaultSort = request.getParameter(PARAMETER_DEFAULT_SORT);
    for (Field field : SolrFieldManager.getFieldList()) {
        if (request.getParameter(Integer.toString(field.getIdField())) != null) {
            field.setEnableSort(true);//from w  w  w  . j  ava 2 s .  com
        } else {
            field.setEnableSort(false);
        }
        if (StringUtils.isNotBlank(strDefaultSort) && StringUtils.isNumeric(strDefaultSort)) {
            if (Integer.parseInt(strDefaultSort) == field.getIdField()) {
                field.setDefaultSort(true);
            } else {
                field.setDefaultSort(false);
            }
        }

        FieldHome.update(field);
    }

    return this.validMessage(request);
}

From source file:fr.paris.lutece.plugins.extend.service.ExtendableResourceResourceIdService.java

/**
 * {@inheritDoc}//from ww w. j av a 2s. co  m
 */
@Override
public String getTitle(String strId, Locale locale) {
    if (StringUtils.isNotBlank(strId) && StringUtils.isNumeric(strId)) {
        int nId = Integer.parseInt(strId);
        IResourceExtenderService resourceExtenderService = SpringContextService
                .getBean(ResourceExtenderService.BEAN_SERVICE);
        ResourceExtenderDTO resource = resourceExtenderService.findByPrimaryKey(nId);

        if (resource != null) {
            return resource.getName();
        }
    }

    return null;
}