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

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

Introduction

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

Prototype

public static String trim(String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String, handling null by returning null.

Usage

From source file:edu.sampleu.travel.workflow.EmployeeAttribute.java

public List validateRoutingData(Map paramMap) {
    List errors = new ArrayList();

    String userid = StringUtils.trim((String) paramMap.get(USERID_FORM_FIELDNAME));
    if (isRequired() && StringUtils.isBlank(userid)) {
        errors.add(new WorkflowServiceErrorImpl("userid is required", "uh.accountattribute.userid.required"));
    }/*from   w  ww.  java 2 s.  c om*/

    Principal principal = null;
    if (!StringUtils.isBlank(userid)) {
        principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName(userid);
    }
    if (principal == null) {
        errors.add(new WorkflowServiceErrorImpl("unable to retrieve user for userid '" + userid + "'",
                "uh.accountattribute.userid.invalid"));
    }

    if (errors.size() == 0) {
        traveler = principal.getPrincipalId();
    }

    return errors;
}

From source file:au.edu.anu.portal.portlets.sakaiconnector.PortletDispatcher.java

/**
 * Helper to process EDIT mode actions//from w  w  w  .j  a  v a 2s.  c  o  m
 * @param request
 * @param response
 */
private void processEditAction(ActionRequest request, ActionResponse response) {
    log.debug("processEditAction()");

    replayForm = false;
    isValid = false;

    //get prefs and submitted values
    PortletPreferences prefs = request.getPreferences();
    String portletHeight = request.getParameter("portletHeight");
    String portletTitle = StringEscapeUtils.escapeHtml(StringUtils.trim(request.getParameter("portletTitle")));
    String remoteSiteId = request.getParameter("remoteSiteId");
    String remoteToolId = request.getParameter("remoteToolId");

    //catch a blank remoteSiteId and replay form
    if (StringUtils.isBlank(remoteSiteId)) {
        replayForm = true;
        response.setRenderParameter("portletTitle", portletTitle);
        response.setRenderParameter("portletHeight", portletHeight);
        return;
    }

    //catch a blank remoteToolId and replay form
    if (StringUtils.isBlank(remoteToolId)) {
        replayForm = true;
        response.setRenderParameter("portletTitle", portletTitle);
        response.setRenderParameter("portletHeight", portletHeight);
        response.setRenderParameter("remoteSiteId", remoteSiteId);
        return;
    }

    //portlet title could be blank, set to default
    //if(StringUtils.isBlank(portletTitle)){
    //   portletTitle=Constants.PORTLET_TITLE_DEFAULT;
    //}

    //form ok so validate
    try {
        prefs.setValue("portletHeight", portletHeight);

        //only set title if it is not blank
        if (StringUtils.isNotBlank(portletTitle)) {
            prefs.setValue("portletTitle", portletTitle);
        }

        prefs.setValue("remoteSiteId", remoteSiteId);
        prefs.setValue("remoteToolId", remoteToolId);
    } catch (ReadOnlyException e) {
        replayForm = true;
        response.setRenderParameter("errorMessage", Messages.getString("error.form.readonly.error"));
        log.error(e);
        return;
    }

    //save them
    try {
        prefs.store();
        isValid = true;
    } catch (ValidatorException e) {
        replayForm = true;
        response.setRenderParameter("errorMessage", e.getMessage());
        log.error(e);
        return;
    } catch (IOException e) {
        replayForm = true;
        response.setRenderParameter("errorMessage", Messages.getString("error.form.save.error"));
        log.error(e);
        return;
    }

    //if ok, invalidate cache and return to view
    if (isValid) {

        try {
            response.setPortletMode(PortletMode.VIEW);
        } catch (PortletModeException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.dianping.lion.service.impl.ConfigServiceImpl.java

@Override
public Paginater findConfigVos(ConfigCriteria criteria, Paginater paginater) {
    int projectId = criteria.getProjectId();
    int envId = criteria.getEnvId();
    HasValueEnum hasValue = EnumUtils.fromEnumProperty(HasValueEnum.class, "value", criteria.getHasValue());
    List<Config> configs = configDao.getSearchConfigList(criteria, paginater);
    List<ConfigVo> configVos = new ArrayList<ConfigVo>(configs.size());
    if (!configs.isEmpty()) {
        List<Integer> hasInstanceConfigs = configDao.findHasInstanceConfigs(projectId, envId);
        List<Integer> hasContextInstConfigs = configDao.findHasContextInstConfigs(projectId, envId);
        Map<Integer, ConfigInstance> defaultInsts = configDao.findDefaultInstances(projectId, envId);
        List<Integer> hasReferencedConfigs = isSharedProject(projectId)
                ? configDao.getProjectHasReferencedConfigs(projectId)
                : Collections.<Integer>emptyList();
        for (Config config : configs) {
            //?????
            String key = StringUtils.trim(criteria.getKey());
            String value = StringUtils.trim(criteria.getValue());
            ConfigInstance defaultInst = defaultInsts.get(config.getId());
            if ((StringUtils.isEmpty(key) || config.getKey().contains(key))
                    && (hasValue == HasValueEnum.All || (hasValue == HasValueEnum.Yes && defaultInst != null)
                            || (hasValue == HasValueEnum.No && defaultInst == null))
                    && (StringUtils.isEmpty(value)
                            || (defaultInst != null && defaultInst.getValue().contains(value)))) {
                configVos.add(new ConfigVo(config, hasInstanceConfigs.contains(config.getId()),
                        hasContextInstConfigs.contains(config.getId()),
                        hasReferencedConfigs.contains(config.getId()), defaultInst));
            }/*from   w  ww .ja  va2 s . co  m*/
        }
    }
    long count = configDao.getSearchConfigCount(criteria);
    paginater.setTotalCount(count);
    paginater.setResults(configVos);
    return paginater;
}

From source file:com.microsoft.alm.plugin.idea.git.ui.vcsimport.ImportForm.java

public String getRepositoryName() {
    return StringUtils.trim(repositoryName.getText());
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.elasticExcel.util.ExcelUtils.java

/**
 * get the attribute from the cell. Do basic type conversions.
 * /*w  w w  .jav a 2 s . c  om*/
 * @param cell the cell to read
 * @param convertNumberToDate if true, AND if the cell type is numeric, convert the cell value to Date; use the 
 *        numeric value otherwise.
 * 
 * @return the value from the cell, or null if cell is empty.
 */
@SuppressWarnings({ "PMD.MissingBreakInSwitch", "boxing" })
public static Object getCellValue(Cell cell, boolean convertNumberToDate) {

    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_BLANK:
        return null;
    case Cell.CELL_TYPE_BOOLEAN:
        return cell.getBooleanCellValue();
    case Cell.CELL_TYPE_NUMERIC:
        if (convertNumberToDate) {
            return cell.getDateCellValue();
        } else {
            return cell.getNumericCellValue();
        }
    case Cell.CELL_TYPE_STRING:
        return StringUtils.trim(cell.getStringCellValue());
    case Cell.CELL_TYPE_ERROR:
        LOGGER.error("Error in cell {0}: contains Error", ExcelUtils.getFullCellName(cell));
        return null;
    case Cell.CELL_TYPE_FORMULA:
        return cell.getCellFormula();
    default: // impossible.
        LOGGER.error("Error in cell {0}: contains unknown cell type.", ExcelUtils.getFullCellName(cell));
        return null;
    }
}

From source file:ch.cyberduck.core.aquaticprime.Receipt.java

/**
 * Verifies the App Store Receipt// w w  w.  ja va 2  s. c om
 *
 * @return False if receipt validation failed.
 */
@Override
public boolean verify() {
    try {
        Security.addProvider(new BouncyCastleProvider());
        PKCS7SignedData signature = new PKCS7SignedData(
                IOUtils.toByteArray(new FileInputStream(this.getFile().getAbsolute())));

        signature.verify();
        // For additional security, you may verify the fingerprint of the root CA and the OIDs of the
        // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the
        // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate
        // is (1 2 840 113635 100 6 11 1).

        // Extract the receipt attributes
        CMSSignedData s = new CMSSignedData(new FileInputStream(this.getFile().getAbsolute()));
        CMSProcessable signedContent = s.getSignedContent();
        byte[] originalContent = (byte[]) signedContent.getContent();
        ASN1Object asn = ASN1Object.fromByteArray(originalContent);

        byte[] opaque = null;
        String bundleIdentifier = null;
        String bundleVersion = null;
        byte[] hash = null;

        if (asn instanceof DERSet) {
            // 2 Bundle identifier      Interpret as an ASN.1 UTF8STRING.
            // 3 Application version    Interpret as an ASN.1 UTF8STRING.
            // 4 Opaque value           Interpret as a series of bytes.
            // 5 SHA-1 hash             Interpret as a 20-byte SHA-1 digest value.
            DERSet set = (DERSet) asn;
            Enumeration enumeration = set.getObjects();
            while (enumeration.hasMoreElements()) {
                Object next = enumeration.nextElement();
                if (next instanceof DERSequence) {
                    DERSequence sequence = (DERSequence) next;
                    DEREncodable type = sequence.getObjectAt(0);
                    if (type instanceof DERInteger) {
                        if (((DERInteger) type).getValue().intValue() == 2) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleIdentifier = new String(((DEROctetString) value).getOctets(), "utf-8");
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 3) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleVersion = new String(((DEROctetString) value).getOctets(), "utf-8");
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 4) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                opaque = ((DEROctetString) value).getOctets();
                            }
                        } else if (((DERInteger) type).getValue().intValue() == 5) {
                            DEREncodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                hash = ((DEROctetString) value).getOctets();
                            }
                        }
                    }
                }
            }
        } else {
            log.error(String.format("Expected set of attributes for %s", asn));
            return false;
        }
        if (!StringUtils.equals("ch.sudo.cyberduck", StringUtils.trim(bundleIdentifier))) {
            log.error("Bundle identifier in ASN set does not match");
            return false;
        }
        if (!StringUtils.equals(Preferences.instance().getDefault("CFBundleShortVersionString"),
                StringUtils.trim(bundleVersion))) {
            log.warn("Bundle version in ASN set does not match");
        }

        NetworkInterface en0 = NetworkInterface.getByName("en0");
        if (null == en0) {
            // Interface is not found when link is down #fail
            log.warn("No network interface en0");
        } else {
            byte[] mac = en0.getHardwareAddress();
            if (null == mac) {
                log.error("Cannot determine MAC address");
                // Continue without validation
                return true;
            }
            final String hex = Hex.encodeHexString(mac);
            if (log.isDebugEnabled()) {
                log.debug("Interface en0:" + hex);
            }
            // Compute the hash of the GUID
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(mac);
            digest.update(opaque);
            digest.update(bundleIdentifier.getBytes(Charset.forName("utf-8")));
            byte[] result = digest.digest();
            if (Arrays.equals(result, hash)) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Valid receipt for GUID %s", hex));
                }
                this.name = hex;
            } else {
                log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt",
                        hex));
                return false;
            }
        }
    } catch (Exception e) {
        log.error("Unknown receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    }
    // Always return true to dismiss donation prompt.
    return true;
}

From source file:hudson.plugins.simpleupdatesite.SimpleUpdateSitePlugIn.java

@Override
public void configure(StaplerRequest req, JSONObject json) throws IOException, ServletException, FormException {
    super.configure(req, json);

    String newsRssUrl = req.getParameter("simpleupdatesite.newsRssUrl");
    newsRssUrl = StringUtils.trim(newsRssUrl);
    if (!StringUtils.equals(newsRssUrl, getNewsRssUrl())) {
        diagnoseNewsRssSiteUrl(newsRssUrl);
        setNewsRssUrl(newsRssUrl);//from   w  ww  .  ja  v  a2s .co m
        this.rssEntryReference.invalidate();

    }
    String updateSiteUrl = req.getParameter("simpleupdatesite.updateSiteUrl");
    updateSiteUrl = StringUtils.trim(updateSiteUrl);
    if (!StringUtils.equals(updateSiteUrl, getUpdateSiteUrl())) {
        diagnoseUpdateSiteUrl(updateSiteUrl);
        setUpdateSiteUrl(updateSiteUrl);
        downloadUpdateSiteJSON();
        this.pluginEntryReference.invalidate();
    }

    supportUrl = StringUtils.trimToNull(req.getParameter("simpleupdatesite.supportUrl"));
    save();
}

From source file:com.fengduo.bee.web.controller.account.LoginController.java

/**
 * ?// w  w  w  .j a  v a2  s . c o  m
 * 
 * @param user
 * @param result
 * @param checkCode ??
 * @param confirmPassword
 * @param isRead 1:?? 0:??
 * @return
 * @description: 
 * @author jie.xu
 * @date 201569 ?8:48:23
 */
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@Valid User user, BindingResult result, String checkCode, String confirmPassword,
        String isRead, Model model) {
    if (result.hasErrors()) {
        model.addAttribute("errMsg", showFirstErrors(result));
        return "account/register";
    }
    model.addAttribute("phone", user.getPhone());
    if (isRead == null || StringUtils.equals(isRead, "0")) {
        model.addAttribute("errMsg", "?????!");
        return "account/register";
    }
    confirmPassword = StringUtils.trim(confirmPassword);
    if (StringUtils.isEmpty(confirmPassword)) {
        model.addAttribute("errMsg", "?,?!");
        return "account/register";
    }
    String passwd = StringUtils.trim(user.getPassword());
    if (!StringUtils.equals(confirmPassword, passwd)) {
        model.addAttribute("errMsg", "??!");
        return "account/register";
    }
    // ??
    String phone = StringUtils.trim(user.getPhone());
    String cacheCode = smsService.getCheckCodeCache(phone);
    if (!StringUtils.equals(checkCode, cacheCode)) {
        model.addAttribute("errMsg", "??,?????!");
        return "account/register";
    }

    Parameter query = Parameter.newParameter()//
            .pu("phone", phone);
    User existUser = userService.queryUser(query);
    if (existUser != null) {
        model.addAttribute("errMsg", "?,!");
        return "account/register";
    }
    user.setPhone(phone);
    user.setPassword(passwd);
    user = userService.insertUser(user);
    // 
    updateShiroUser(phone, passwd);
    return "redirect:/user/setting";
}

From source file:com.redhat.rhn.common.conf.Config.java

/**
 * get the config entry for string s//  w w  w  . j a  v a  2 s  .co  m
 *
 * @param value string to get the value of
 * @return the value
 */
public String getString(String value) {
    if (logger.isDebugEnabled()) {
        logger.debug("getString() -     getString() called with: " + value);
    }
    if (value == null) {
        return null;
    }

    int lastDot = value.lastIndexOf('.');
    String ns = "";
    String property = value;
    if (lastDot > 0) {
        property = value.substring(lastDot + 1);
        ns = value.substring(0, lastDot);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("getString() -     getString() -> Getting property: " + property);
    }
    String result = configValues.getProperty(property);
    if (logger.isDebugEnabled()) {
        logger.debug("getString() -     getString() -> result: " + result);
    }
    if (result == null) {
        if (!"".equals(ns)) {
            result = configValues.getProperty(ns + "." + property);
        } else {
            for (int i = 0; i < prefixOrder.length; i++) {
                result = configValues.getProperty(prefixOrder[i] + "." + property);
                if (result != null) {
                    break;
                }
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("getString() -     getString() -> returning: " + result);
    }

    if (result == null || result.equals("")) {
        return null;
    }

    return StringUtils.trim(result);
}

From source file:com.reizes.shiva.utils.AddrUtil.java

/**
 * 3 ?   ? ? . /*from ww  w .  ja  v  a  2  s. c o  m*/
 * ?   ? 
 * ?   trim
 * @param addr1 1
 * @param addr2 2
 * @param addr3 3
 * @return
 */
public static String mergeAddrs(String addr1, String addr2, String addr3) {
    StringBuffer address = new StringBuffer();
    address.append(addr1 == null ? "" : StringUtils.trim(addr1));
    if (addr2 != null) {
        String newAddr2 = StringUtils.trim(addr2);
        if (newAddr2.length() > 0) {
            address.append(" ");
            address.append(newAddr2);
        }
    }
    if (addr3 != null) {
        String newAddr3 = StringUtils.trim(addr3);
        if (newAddr3.length() > 0) {
            address.append(" ");
            address.append(newAddr3);
        }
    }
    return StringUtils.trim(address.toString());
}