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:ch.entwine.weblounge.kernel.fop.FopEndpoint.java

/**
 * Downloads both XML and XSL document and transforms them to PDF.
 * /*from w  w  w.jav  a 2s .  co m*/
 * @param xmlURL
 *          the URL to the XML document
 * @param xslURL
 *          the URL to the XSL document
 * @return the generated PDF
 * @throws WebApplicationException
 *           if the XML document cannot be downloaded
 * @throws WebApplicationException
 *           if the XSL document cannot be downloaded
 * @throws WebApplicationException
 *           if the PDF creation fails
 */
@POST
@Path("/pdf")
public Response transformToPdf(@FormParam("xml") String xmlURL, @FormParam("xsl") String xslURL,
        @FormParam("parameters") String params) {

    // Make sure we have a service
    if (fopService == null)
        throw new WebApplicationException(Status.SERVICE_UNAVAILABLE);

    final Document xml;
    final Document xsl;

    // Load the xml document
    InputStream xmlInputStream = null;
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        xmlInputStream = new URL(xmlURL).openStream();
        xml = documentBuilder.parse(xmlInputStream);
    } catch (MalformedURLException e) {
        logger.warn("Error creating xml url from '{}'", xmlURL);
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (IOException e) {
        logger.warn("Error accessing xml document at '{}': {}", xmlURL, e.getMessage());
        throw new WebApplicationException(Status.NOT_FOUND);
    } catch (ParserConfigurationException e) {
        logger.warn("Error setting up xml parser: {}", e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (SAXException e) {
        logger.warn("Error parsing xml document from {}: {}", xmlURL, e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } finally {
        IOUtils.closeQuietly(xmlInputStream);
    }

    // Load the XLST stylesheet
    InputStream xslInputStream = null;
    try {
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        xslInputStream = new URL(xslURL).openStream();
        xsl = documentBuilder.parse(xslInputStream);
    } catch (MalformedURLException e) {
        logger.warn("Error creating xsl url from '{}'", xslURL);
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (IOException e) {
        logger.warn("Error accessing xsl stylesheet at '{}': {}", xslURL, e.getMessage());
        throw new WebApplicationException(Status.NOT_FOUND);
    } catch (ParserConfigurationException e) {
        logger.warn("Error setting up xml parser: {}", e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } catch (SAXException e) {
        logger.warn("Error parsing xml document from {}: {}", xslURL, e.getMessage());
        throw new WebApplicationException(Status.BAD_REQUEST);
    } finally {
        IOUtils.closeQuietly(xslInputStream);
    }

    // Create the filename
    String name = FilenameUtils.getBaseName(xmlURL) + ".pdf";

    // Process the parameters
    final List<String[]> parameters = new ArrayList<String[]>();
    if (StringUtils.isNotBlank(params)) {
        for (String param : StringUtils.split(params, ";")) {
            String[] parameterValue = StringUtils.split(param, "=");
            if (parameterValue.length != 2) {
                logger.warn("Parameter for PDF generation is malformed: {}", param);
                throw new WebApplicationException(Status.BAD_REQUEST);
            }
            parameters.add(
                    new String[] { StringUtils.trim(parameterValue[0]), StringUtils.trim(parameterValue[1]) });
        }
    }

    // Write the file contents back
    ResponseBuilder response = Response.ok(new StreamingOutput() {
        public void write(OutputStream os) throws IOException, WebApplicationException {
            try {
                fopService.xml2pdf(xml, xsl, parameters.toArray(new String[parameters.size()][2]), os);
            } catch (IOException e) {
                Throwable cause = e.getCause();
                if (cause == null || !"Broken pipe".equals(cause.getMessage()))
                    logger.warn("Error writing file contents to response", e);
            } catch (TransformerConfigurationException e) {
                logger.error("Error setting up the XSL transfomer: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (FOPException e) {
                logger.error("Error creating PDF document: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (TransformerException e) {
                logger.error("Error transforming to PDF: {}", e.getMessage());
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } finally {
                IOUtils.closeQuietly(os);
            }
        }
    });

    // Set response information
    response.type("application/pdf");
    response.header("Content-Disposition", "inline; filename=" + name);
    response.lastModified(new Date());

    return response.build();
}

From source file:com.adobe.acs.commons.workflow.process.impl.WorkflowDelegationStep.java

@Override
public void execute(WorkItem workItem, WorkflowSession workflowSession, MetaDataMap metadata)
        throws WorkflowException {

    Map<String, String> args = getProcessArgsMap(metadata);

    String propertyName = args.get(WORKFLOW_PROPERTY_NAME);
    String defaultWorkflowModelId = args.get(DEFAULT_WORKFLOW_MODEL);
    boolean terminateOnDelegation = Boolean
            .parseBoolean(StringUtils.lowerCase(args.get(TERMINATE_ON_DELEGATION)));

    if (StringUtils.isBlank(propertyName)) {
        throw new WorkflowException("PROCESS_ARG [ " + WORKFLOW_PROPERTY_NAME + " ] not defined");
    }/*from  w ww .  j av a  2  s .  c o  m*/

    log.debug("Provided PROCESS_ARGS: propertyName = [ {} ], Default Workflow Model = [ {} ]", propertyName,
            defaultWorkflowModelId);

    ResourceResolver resolver = null;
    WorkflowData wfData = workItem.getWorkflowData();

    if (!workflowHelper.isPathTypedPayload(wfData)) {
        log.warn("Could not locate a JCR_PATH payload for this workflow. Skipping delegation.");
        return;
    }

    final String path = wfData.getPayload().toString();

    // Get the resource resolver

    resolver = workflowHelper.getResourceResolver(workflowSession);
    if (resolver == null) {
        throw new WorkflowException(
                "Could not adapt the WorkflowSession to a ResourceResolver. Something has gone terribly wrong!");
    }

    // Derive the Page or Asset resource so we have a normalized entry-point for finding the /jcr:content resource

    final Resource pageOrAssetResource = workflowHelper.getPageOrAssetResource(resolver, path);
    if (pageOrAssetResource == null) {
        log.warn("Could not resolve [ {} ] to an Asset or Page. Skipping delegation.", path);
        return;
    }

    // Get the Asset or Page's jcr:content resource, so we have a common inherited property look-up scheme

    final Resource jcrContentResource = pageOrAssetResource.getChild(JcrConstants.JCR_CONTENT);
    if (jcrContentResource == null) {
        throw new WorkflowException(String.format("Could not find a child jcr:content resource for [ %s ]",
                pageOrAssetResource.getPath()));
    }

    // Look up the content-hierarchy for the delegate workflow model

    final InheritanceValueMap inheritance = new HierarchyNodeInheritanceValueMap(jcrContentResource);
    final String foundWorkflowModelId = StringUtils.trim(inheritance.getInherited(propertyName, String.class));
    final WorkflowModel delegateWorkflowModel = getDelegateWorkflowModel(workflowSession, foundWorkflowModelId,
            defaultWorkflowModelId);

    if (delegateWorkflowModel != null) {
        workflowSession.startWorkflow(delegateWorkflowModel, wfData);
        log.info("Delegating payload [ {} ] to Workflow Model [ {} ]", wfData.getPayload(),
                delegateWorkflowModel.getId());

        if (terminateOnDelegation) {
            log.info("Terminating current workflow due to PROCESS_ARGS[ {} ] = [ {} ]", TERMINATE_ON_DELEGATION,
                    terminateOnDelegation);
            workflowSession.terminateWorkflow(workItem.getWorkflow());
        }
    } else {
        log.warn("No valid delegate Workflow Model could be located. Skipping workflow delegation.");
    }
}

From source file:edu.mayo.cts2.framework.core.xml.DelegatingMarshaller.java

/**
 * Creates the map from properties./*from  w  ww. j  a va  2  s . c  om*/
 *
 * @param resource the resource
 * @return the map
 */
private Map<String, String> createMapFromProperties(Properties props) {
    Map<String, String> returnMap = new HashMap<String, String>();

    for (Entry<Object, Object> entry : props.entrySet()) {
        returnMap.put(StringUtils.trim((String) entry.getKey()), StringUtils.trim((String) entry.getValue()));
    }

    return returnMap;
}

From source file:com.groupon.jenkins.github.services.GithubRepositoryService.java

private void removeDeployKeyIfPreviouslyAdded() throws IOException {
    String configuredDeployKey = StringUtils.trim(getSetupConfig().getDeployKey());
    for (GHDeployKey deployKey : getRepository().getDeployKeys()) {
        // needs startsWith as email address is trimmed out
        if (configuredDeployKey.startsWith(deployKey.getKey())) {
            deployKey.delete();/*from  w  ww.  j  a  v  a2  s.com*/
        }
    }
}

From source file:com.edgenius.wiki.installation.DBLoader.java

public String getURL(String dbType, String driverType, String host, String dbname, boolean admin) {
    log.info("get url by " + dbType + " for driver " + driverType + " on host " + host + " for admin " + admin);
    driverType = StringUtils.isBlank(driverType) ? "" : ("." + StringUtils.trim(driverType));
    String url = prototype.getProperty(dbType + driverType + (admin ? ".admin.url" : ".url"));
    url = url.replaceAll(TOKEN_HOST, host);
    url = url.replaceAll(TOKEN_DBNAME, dbname);
    return url;//from www. j  a  v a 2  s .co  m
}

From source file:ch.entwine.weblounge.security.sql.endpoint.SQLDirectoryProviderEndpoint.java

@POST
@Path("/account")
public Response createAccount(@FormParam("login") String login, @FormParam("password") String password,
        @FormParam("email") String eMail, @Context HttpServletRequest request) {

    // TODO: If not, return a one time pad that needs to be used when verifying
    // the e-mail

    // Check the arguments
    if (StringUtils.isBlank(login))
        return Response.status(Status.BAD_REQUEST).build();

    Response response = null;//from  w w  w .  j  a  va2 s.c o m
    Site site = getSite(request);

    // Hash the password
    if (StringUtils.isNotBlank(password)) {
        logger.debug("Hashing password for user '{}@{}' using md5", login, site.getIdentifier());
        password = PasswordEncoder.encode(StringUtils.trim(password));
    }

    // Create the user
    try {
        JpaAccount account = directory.addAccount(site, login, password);
        account.setEmail(StringUtils.trimToNull(eMail));
        directory.updateAccount(account);
        response = Response
                .created(new URI(UrlUtils.concat(request.getRequestURL().toString(), account.getLogin())))
                .build();
    } catch (UserExistsException e) {
        logger.warn("Error creating account: {}", e.getMessage());
        return Response.status(Status.CONFLICT).build();
    } catch (UserShadowedException e) {
        logger.warn("Error creating account: {}", e.getMessage());
        return Response.status(Status.CONFLICT).build();
    } catch (Throwable t) {
        logger.warn("Error creating account: {}", t.getMessage());
        response = Response.serverError().build();
    }
    return response;
}

From source file:com.allinfinance.struts.system.action.LoginAction.java

@SuppressWarnings("unchecked")
@Override/*w w  w.  j a v  a 2  s  .c o m*/
protected String subExecute() throws Exception {

    TblOprInfoDAO tblOprInfoDAO = (TblOprInfoDAO) ContextUtil.getBean("OprInfoDAO");

    String code = (String) getSessionAttribute("vC");
    if (code == null || !validateCode.equalsIgnoreCase(code)) {
        writeErrorMsg("???");
        return SUCCESS;
    }

    //ID?ID
    boolean authUser = false;
    try {
        String ids = SysParamUtil.getParam("AUTH_USER");
        if (StringUtil.isNull(ids)) {
            writeErrorMsg("?ID");
            return SUCCESS;
        } else {
            String[] id = ids.split(",");
            for (String tmp : id) {
                if (!StringUtil.isNull(tmp) && tmp.equals(oprid)) {
                    authUser = true;
                    break;
                }
            }
        }
    } catch (Exception e) {
        log("??");
        e.printStackTrace();
    }
    //      if (!authUser) {
    //         log("[" + oprid + "]??ID");
    //         writeErrorMsg("[" + oprid + "]??ID??");
    //         return SUCCESS;
    //      }

    TblOprInfo tblOprInfo = tblOprInfoDAO.get(oprid);

    //??
    if (tblOprInfo == null) {
        log("???[ " + oprid + " ]");
        writeErrorMsg("????!"); // ???
        return SUCCESS;
    }

    // ??
    tblOprInfo.setLastLoginTime(tblOprInfo.getCurrentLoginTime());
    tblOprInfo.setLastLoginIp(tblOprInfo.getCurrentLoginIp());
    tblOprInfo.setLastLoginStatus(tblOprInfo.getCurrentLoginStatus());
    tblOprInfo.setCurrentLoginTime(CommonFunction.getCurrentDateTime());
    tblOprInfo.setCurrentLoginIp(getRequest().getRemoteHost());

    // ??
    if ("1".equals(tblOprInfo.getOprSta().trim())) {
        log("??[ " + oprid + " ]");
        writeErrorMsg("????");
        return SUCCESS;
    }

    // ???
    if (SysParamUtil.getParam(SysParamConstants.PWD_WR_TM_CONTINUE)
            .equals(tblOprInfo.getPwdWrTmContinue().trim())) {
        String lockTime = CommonFunction.lockFlag(tblOprInfo.getLastLoginTime(),
                SysParamUtil.getParam(SysParamConstants.LOCK_TIME));
        // ?????
        if ("0".equals(lockTime.split("#")[0])) {
            log("????"
                    + lockTime.split("#")[1] + "?[ " + oprid + " ]");
            writeErrorMsg("??" + lockTime.split("#")[1]);
            return SUCCESS;
        }
    }

    //System.out.println("11:" + tblOprInfo.getPwdOutDate());
    // ??
    if (Integer.parseInt(tblOprInfo.getPwdOutDate().trim()) <= Integer
            .parseInt(CommonFunction.getCurrentDate())) {
        log("???[ " + oprid + " ]");
        writeAlertMsg("??", TblOprInfoConstants.LOGIN_CODE_PWD_OUT);
        return SUCCESS;
    }

    // ??
    if (TblOprInfoConstants.STATUS_INIT.equals(tblOprInfo.getOprSta().trim())) {
        log("?!?[ " + oprid + " ]CODE:[ "
                + TblOprInfoConstants.LOGIN_CODE_INIT + " ]");
        writeAlertMsg("?!", TblOprInfoConstants.LOGIN_CODE_INIT);
        return SUCCESS;
    }

    //??
    String oprPassword = StringUtils.trim(tblOprInfo.getOprPwd());
    password = StringUtils.trim(Encryption.encrypt(password));
    if (!oprPassword.equals(password)) {

        //         if(!CommonFunction.getCurrentDate().equals(tblOprInfo.getPwdWrLastDt())) {
        //            tblOprInfo.setPwdWrLastDt(CommonFunction.getCurrentDate());
        //            tblOprInfo.setPwdWrTm("1");
        //         } else {
        //            tblOprInfo.setPwdWrTm(String.valueOf(Integer.parseInt(tblOprInfo.getPwdWrTm().trim()) + 1));
        //         }
        //         tblOprInfo.setPwdWrTmTotal(String.valueOf(Integer.parseInt(tblOprInfo.getPwdWrTmTotal().trim()) + 1));
        //         
        //         // 53?
        //         if(Integer.parseInt(tblOprInfo.getPwdWrTmTotal().trim()) >= 5 || 
        //               (Integer.parseInt(tblOprInfo.getPwdWrTm().trim()) >= 3 && 
        //                     CommonFunction.getCurrentDate().equals(tblOprInfo.getPwdWrLastDt().trim()))) {
        //            tblOprInfo.setOprSta("1");
        //         }
        //         tblOprInfoDAO.update(tblOprInfo);

        // ???
        if (SysParamUtil.getParam(SysParamConstants.PWD_WR_TM_CONTINUE)
                .equals(tblOprInfo.getPwdWrTmContinue().trim())) {
            tblOprInfo.setPwdWrTmContinue("1");
        } else {
            tblOprInfo.setPwdWrTmContinue(
                    String.valueOf(Integer.parseInt(tblOprInfo.getPwdWrTmContinue().trim()) + 1));
        }
        // ?[0-?1-]
        tblOprInfo.setCurrentLoginStatus("1");
        tblOprInfoDAO.update(tblOprInfo);

        if (SysParamUtil.getParam(SysParamConstants.PWD_WR_TM_CONTINUE)
                .equals(tblOprInfo.getPwdWrTmContinue().trim())) {
            log("?!?[ " + oprid + " ]");
            writeErrorMsg("???"
                    + SysParamUtil.getParam(SysParamConstants.LOCK_TIME) + "?");
            return SUCCESS;
        }

        log("??[ " + oprid + " ]");
        writeErrorMsg("????!");
        return SUCCESS;
    }

    // ????
    tblOprInfo.setPwdWrTmContinue("0");
    // ?[0-?1-]
    tblOprInfo.setCurrentLoginStatus("0");
    tblOprInfoDAO.update(tblOprInfo);

    setSessionAttribute("oprId", oprid);

    //???,??
    String userSingalFlag = SysParamUtil.getParam(SysParamConstants.SINGAL_USER);
    if (userSingalFlag.equals(CommonsConstants.SINGAL_USER)) {
        log("??");

        Map<String, String> userlistMap = (Map<String, String>) ServletActionContext.getServletContext()
                .getAttribute(SysParamConstants.USER_LIST);
        if (userlistMap == null) {
            userlistMap = new HashMap<String, String>();
        }

        if (StringUtil.isNotEmpty(userlistMap.get(oprid))) {
            userlistMap.remove(oprid);
        }

        userlistMap.put(oprid, session.getId());
        log(session.getId());

        ServletActionContext.getServletContext().setAttribute(SysParamConstants.USER_LIST, userlistMap);

    } else {
        log("?");
    }

    writeSuccessMsg("?");
    return SUCCESS;
}

From source file:mitm.djigzo.web.pages.portal.secure.OTP.java

public void setPasswordID(String passwordID) {
    this.passwordID = StringUtils.trim(passwordID);
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.timeseriesExcel.importer.TimeseriesExcelImporter.java

private TypeOfBuildingBlock getTypeOfBuildingBlockFromSheet(Sheet timeseriesSheet) {
    CellReference ref = ExcelUtils.getFullCellReference(timeseriesSheet, BB_TYPE_CELL_REF);

    Row row = timeseriesSheet.getRow(ref.getRow());
    if (row == null) {
        logError(ref, "No Building Block Type name found.");
        return null;
    }/*  w  w w .j av a2 s  .c  o m*/
    Cell bbtCell = row.getCell(ref.getCol());
    if (ExcelUtils.isEmptyCell(bbtCell)) {
        logError(ref, "No Building Block Type name found.");
        return null;
    }

    String buildingBlockName = StringUtils.trim(ExcelUtils.getStringCellValue(bbtCell));
    Class<?> buildingBlockClass = null;
    try {
        buildingBlockClass = Class.forName(BB_PACKAGE_PREFIX + buildingBlockName);
    } catch (ClassNotFoundException e) {
        logError(e, ref, "\"{0}\" is not a valid building block class name.", buildingBlockName);
        return null;
    }

    TypeOfBuildingBlock tobb = TypeOfBuildingBlock.typeOfBuildingBlockForClass(buildingBlockClass);
    if (tobb == null) {
        logError(ref, "No Building Block Type for Class \"{0}\" found.", buildingBlockClass);
    }
    return tobb;
}

From source file:com.greenline.guahao.web.module.home.controllers.mobile.UnicomUtils.java

/**
 * ???url????/*from ww  w  . j ava2s . com*/
 * 
 * @param model
 * @return
 */
public String getPhoneFromUnicomURL() {
    log.info("______________??????");
    String sign = request.getParameter("sign");
    log.info("______________sign=" + sign);
    // ??
    String mobile = request.getParameter("mob");
    log.info("______________??????:" + mobile);
    if (StringUtils.isBlank(sign)) {
        return null;
    }

    String clientSign = DESUtil.DESDecode(sign, MobileConstants.DESC_UNICOM_KEY);
    String cookiecode = codeCacheManager.getCode(VerifyTypeEnum.UNICOM_NET_MOB_CODE, clientSign);
    codeCacheManager.delCode(VerifyTypeEnum.UNICOM_NET_MOB_CODE, clientSign);
    if (StringUtils.isNotBlank(mobile)) {
        mobile = CryptoTools.decode(mobile, unicomManager.getSpPassWord());
        log.info("______________???????:" + mobile);
        log.info("______________cookiecode:" + cookiecode + "___________clientSign:" + clientSign);
        if (clientSign.equalsIgnoreCase(cookiecode)) {
            if (RegexUtil.isMobile(StringUtils.trim(mobile))) {
                // cookie
                UserCookieUtil.writeKey(request, UserCookieUtil.MOBILE, mobile, telphoneCookieTimeOut);
                UserCookieUtil.writeKey(request, UserCookieUtil.LOGIN_ID, mobile, -1);
            }
            return mobile;
        } else {
            log.error("______________???????:"
                    + CommonUtils.getRequestUrl(request));
        }
    }
    return null;
}