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:com.greenline.guahao.web.module.home.controllers.mobile.user.MobileUserController.java

/**
 * html5???//from   w  ww .ja v  a  2  s.  co  m
 * 
 * @param model
 * @param userDO
 * @return String
 */
@MethodRemark(value = "remark=html5???,method=post")
@RequestMapping(value = MobileConstants.M_USERINFO_UPDATE_PATH, method = RequestMethod.POST)
public String fillInfo(ModelMap model, @ModelAttribute("userInfo") UserDO userDO) {
    Long cuserId = UserCookieUtil.getUserId(request);// ?cookieuserId
    boolean hasError = (null == userDO.getUserId());
    if (!hasError && !userDO.getUserId().equals(cuserId)) {
        UserCookieUtil.logout(request);
        hasError = Boolean.TRUE;
        model.put("message", MobileMsgConstants.USER_ERRO);
    }
    if (hasError) {
        return MobileConstants.M_ERROR;
    }
    if (!hasError && StringUtils.isBlank(userDO.getUserName())) {
        hasError = Boolean.TRUE;
        model.put("message", MobileMsgConstants.USER_NAME_MUST);
    }

    if (!RegexUtil.isIdCard(StringUtils.trim(userDO.getCertNo()))) {
        hasError = Boolean.TRUE;
        model.put("message", MobileMsgConstants.USER_CERNO_ERROR);
        model.put("certNoError", Boolean.TRUE);
    }
    if (userDO.getReg_type() != 1) {
        if (!RegexUtil.isMobile(StringUtils.trim(userDO.getMobile()))) {
            model.put("mobileError", Boolean.TRUE);
            hasError = Boolean.TRUE;
            model.put("message", MobileMsgConstants.USER_MOBILE_ERROR);
        }
    }
    if (!BizCommonUtils.isAllChinese(userDO.getUserName())) {
        model.put("nameError", Boolean.TRUE);
        hasError = Boolean.TRUE;
        model.put("message", MobileMsgConstants.USER_USERNAME_ERROR);
    }
    if (!hasError) {
        // ??
        UserResult ur = userManager.valiCertNo(cuserId, userDO.getCertNo(), userDO.getReg_type());
        if (ur != null && ur.getUserDO() != null) {
            hasError = Boolean.TRUE;
            model.put("message", MobileMsgConstants.USER_CERNO_USERED);
            model.put("certNoError", Boolean.TRUE);
        }
    }
    if (!hasError) {
        // ?
        UserResult ur = userManager.valiMobileNo(cuserId, userDO.getMobile(), userDO.getReg_type());
        if (ur != null && ur.getUserDO() != null) {
            hasError = Boolean.TRUE;
            model.put("message", MobileMsgConstants.USER_MOBILENO_USERED);
            model.put("mobileError", Boolean.TRUE);
        }
    }
    if (!hasError) {
        UserDO updateDO = new UserDO();
        updateDO.setUserId(userDO.getUserId());
        updateDO.setCertNo(userDO.getCertNo());
        updateDO.setUserName(userDO.getUserName());
        if (userDO.getReg_type() != 1) {
            updateDO.setMobile(userDO.getMobile());
        }
        updateDO.setReg_type(userDO.getReg_type());
        BaseJsonObject msgJson = mobileUserProcess.updateUser(updateDO);
        hasError = msgJson.getHasError();
        if (hasError) {
            model.put("message", msgJson.getMessage());
        }
    }
    String target = request.getParameter("target");
    if (hasError) {
        UserDO user = userManager.findUserByUserId(cuserId);
        if (null != user) {
            userDO.setLoginId(user.getLoginId());
        }
        model.put("target", target);
        model.put("userInfo", userDO);
        model.put("hasError", hasError);
        if ("1".equals(request.getParameter("pageId"))) {
            model.put("hasUpdate", UserUtil.isUserProfileImperfection(user));
            model.put("isZFB", DomainIndexEnum.ZFB.equals(request.getAttribute(GlobalConstants.DOMAIN_ENUM)));
            model.put("isM58", DomainIndexEnum.M58.equals(request.getAttribute(GlobalConstants.DOMAIN_ENUM)));
            model.put("isXM",
                    DomainIndexEnum.XIAO_MI.equals(request.getAttribute(GlobalConstants.DOMAIN_ENUM)));
            return MobileConstants.M_USERCENTER;
        }
        model.put("isZFB", DomainIndexEnum.ZFB.equals(request.getAttribute(GlobalConstants.DOMAIN_ENUM)));
        model.put("isM58", DomainIndexEnum.M58.equals(request.getAttribute(GlobalConstants.DOMAIN_ENUM)));
        model.put("isXM", DomainIndexEnum.XIAO_MI.equals(request.getAttribute(GlobalConstants.DOMAIN_ENUM)));
        // ?
        return MobileConstants.M_USERINFO;
    } else {
        if (StringUtils.isNotBlank(target)) {
            try {
                return GlobalConstants.REDIRECT_PER + URLDecoder.decode(target, GlobalConstants.CHARSET_UTF8);
            } catch (Exception e) {
            }
        }
        model.put("title", MobileMsgConstants.M_UPDATE_USER_INFO_SUC);
        model.put("toUrl", MobileConstants.M_USERCENTER_PATH);
        model.put("toTitle", "");
        return MobileConstants.M_SUCCESS;
    }
}

From source file:com.ironiacorp.statistics.r.AbstractRClient.java

/**
 * There is a pretty annoying limitation of this. The file must contain only one statement. You can get around this
 * by using c(x<-1,x<-2). See testScript.R
 * //  w  w w.  jav a 2  s  . com
 * @param is
 */
protected void loadScript(InputStream is) {
    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line = null;
        StringBuilder buf = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("#") || StringUtils.isBlank(line)) {
                continue;
            }
            buf.append(StringUtils.trim(line) + "\n");
        }
        is.close();
        this.voidEval(buf.toString());

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hangum.tadpole.commons.admin.core.editors.sqlaudit.AdminSQLAuditEditor.java

/**
 * search/*from   www.  ja v  a2s.co  m*/
 */
private void search() {
    //  ? ?? .
    clearGrid();
    mapSQLHistory.clear();

    String strEmail = "%" + StringUtils.trim(textEmail.getText()) + "%"; //$NON-NLS-1$ //$NON-NLS-2$

    Calendar cal = Calendar.getInstance();
    cal.set(dateTimeStart.getYear(), dateTimeStart.getMonth(), dateTimeStart.getDay(), 0, 0, 0);
    long startTime = cal.getTimeInMillis();

    cal.set(dateTimeEnd.getYear(), dateTimeEnd.getMonth(), dateTimeEnd.getDay(), 23, 59, 59);
    long endTime = cal.getTimeInMillis();
    int duringExecute = Integer.parseInt(textMillis.getText());

    String strSearchTxt = "%" + StringUtils.trimToEmpty(textSearch.getText()) + "%"; //$NON-NLS-1$ //$NON-NLS-2$

    try {
        List<RequestResultDAO> listSQLHistory = TadpoleSystem_ExecutedSQL.getAllExecuteQueryHistoryDetail(
                strEmail, comboTypes.getText(), startTime, endTime, duringExecute, strSearchTxt);
        for (int i = 0; i < listSQLHistory.size(); i++) {
            RequestResultDAO reqResultDAO = (RequestResultDAO) listSQLHistory.get(i);
            mapSQLHistory.put("" + i, reqResultDAO); //$NON-NLS-1$

            GridItem item = new GridItem(gridHistory, SWT.V_SCROLL | SWT.H_SCROLL);

            String strSQL = StringUtils.strip(reqResultDAO.getStrSQLText());
            int intLine = StringUtils.countMatches(strSQL, "\n"); //$NON-NLS-1$
            if (intLine >= 1) {
                int height = (intLine + 1) * 24;
                if (height > 100)
                    item.setHeight(100);
                else
                    item.setHeight(height);
            }

            item.setText(0, "" + i); //$NON-NLS-1$
            item.setText(1, reqResultDAO.getDbName());
            item.setText(2, reqResultDAO.getUserName());
            item.setText(3, Utils.dateToStr(reqResultDAO.getStartDateExecute()));
            item.setText(4, Utils.convLineToHtml(strSQL));
            item.setToolTipText(4, strSQL);

            item.setText(5, "" + ((reqResultDAO.getEndDateExecute().getTime() //$NON-NLS-1$
                    - reqResultDAO.getStartDateExecute().getTime()) / 1000f));
            item.setText(6, "" + reqResultDAO.getRows()); //$NON-NLS-1$
            item.setText(7, reqResultDAO.getResult());

            item.setText(8, Utils.convLineToHtml(reqResultDAO.getMesssage()));
            item.setToolTipText(8, reqResultDAO.getMesssage());

            item.setText(9, reqResultDAO.getIpAddress());

            if ("F".equals(reqResultDAO.getResult())) { //$NON-NLS-1$
                item.setBackground(SWTResourceManager.getColor(240, 180, 167));
            }
        }
    } catch (Exception ee) {
        logger.error("Executed SQL History call", ee); //$NON-NLS-1$
    }
}

From source file:com.bluexml.xforms.actions.WorkflowTransitionAction.java

/**
 * Updates the next task(s) so that the workflow instance appears as
 * assigned to a user and/or//from  ww  w .j  a v a 2s . c  o  m
 * group. <br/>
 * This updating is COMPULSORY: Alfresco will not do it automatically as one
 * could expect.
 * 
 * @param transaction
 * @param taskProperties
 */
private TransitionResultBean reassignWorkflow(AlfrescoTransaction transaction,
        HashMap<QName, Serializable> taskProperties) {
    TransitionResultBean result = new TransitionResultBean();
    HashMap<QName, Serializable> properties;
    List<String> tasks;
    try {
        tasks = controller.workflowGetCurrentTasksInfo(transaction, currentPage.getWkflwInstanceId());
    } catch (Exception e) {
        logger.debug("Error getting the current tasks", e);
        tasks = null;
    }
    if (tasks == null) {
        navigationPath.setStatusMsg(MsgPool.getMsg(MsgId.MSG_STATUS_WKFLW_FAIL_SERVER));
        return result;
    }
    if (tasks.size() == 0) {
        // the workflow is completed, no more tasks are available
        navigationPath.setStatusMsg(MsgPool.getMsg(MsgId.MSG_STATUS_WKFLW_SUCCESS_END));
        result.setSuccess(true);
        return result;
    }

    List<String> failedAssignmentTasks = new Vector<String>();

    for (String taskInfoString : tasks) {
        String taskId = getIdFromTaskIdNameTitle(taskInfoString);
        String taskName = getNameFromTaskIdNameTitle(taskInfoString);
        WorkflowTaskInfoBean taskBean = controller.getWorkflowTaskInfoBeanByTaskId(taskName);
        if (taskBean == null) {
            // oups sorry try to get it 
            taskBean = controller.getWorkflowTaskInfoBean(taskName);
        }
        String pooledActors = taskBean.getPooledActors();
        String actorIds = taskBean.getActorId();

        if ((StringUtils.trimToNull(pooledActors) != null) || (StringUtils.trimToNull(actorIds) != null)) {
            // we got some user(s)/group(s) to assign the task to

            // the list of users/groups allowed to manage the task
            List<NodeRef> refToActors = new Vector<NodeRef>();
            properties = new HashMap<QName, Serializable>();
            if (StringUtils.trimToNull(actorIds) == null && StringUtils.trimToNull(pooledActors) == null) {
                navigationPath.setStatusMsg(MsgPool.getMsg(MsgId.MSG_STATUS_WKFLW_FAIL_NO_ACTOR));
                return result;
            }
            if (StringUtils.trimToNull(pooledActors) != null) {
                // #1514: support for multiple groups/users via comma-separated list
                String[] actors = StringUtils.split(pooledActors, ",");
                for (String anActor : actors) {
                    anActor = StringUtils.trim(anActor);
                    anActor = resolveActorId(anActor, taskProperties);
                    NodeRef nodeRef = controller.systemGetNodeRefForGroup(transaction, anActor);
                    addActor(refToActors, nodeRef);
                }
            }
            if (StringUtils.trimToNull(actorIds) != null) {
                String[] actors = StringUtils.split(actorIds, ",");
                for (String anActor : actors) {
                    anActor = StringUtils.trim(anActor);
                    anActor = resolveActorId(anActor, taskProperties);
                    NodeRef nodeRef = controller.systemGetNodeRefForUser(transaction, anActor);
                    addActor(refToActors, nodeRef);
                }
            }
            if (refToActors.size() == 0) {
                navigationPath.setStatusMsg(MsgPool.getMsg(MsgId.MSG_STATUS_WKFLW_FAIL_ASSIGN));
                return result;
            }

            // perform the task assignment to the user(s)/group(s)
            properties.put(WorkflowModel.ASSOC_POOLED_ACTORS, (Serializable) refToActors);
            try {
                controller.workflowUpdateTask(transaction, taskId, properties);
            } catch (Exception e) {
                logger.debug("Error affecting the next tasks (id=" + taskId + ", name=" + taskName + ")", e);
                failedAssignmentTasks.add(taskInfoString);
            }
        }
    }

    // all workflow tasks except the end task should lead to at least one successful rea
    int nbFailedAssignments = failedAssignmentTasks.size();
    if (nbFailedAssignments > 0) {
        String names = StringUtils.join(failedAssignmentTasks, ", ");
        navigationPath.setStatusMsg(MsgPool.getMsg(MsgId.MSG_STATUS_WKFLW_FAIL_ASSIGN_TASKS,
                "" + nbFailedAssignments, "" + tasks.size(), names));
        return result;
    }
    String nextTasksTitles = buildNextTasksTitles(tasks);
    String msg = MsgPool.getMsg(MsgId.MSG_STATUS_WKFLW_SUCCESS, nextTasksTitles,
            currentPage.getWkflwInstanceId());
    navigationPath.setStatusMsg(msg);
    result.setTasks(tasks);
    result.setSuccess(true);
    logger.debug("Workflow reassignment of task(s) '" + nextTasksTitles + "' is successful.");
    return result;
}

From source file:com.ibm.jaggr.service.impl.modulebuilder.css.CSSModuleBuilder.java

/**
 * Processes the input CSS to replace &#064;import statements with the
 * contents of the imported CSS.  The imported CSS is minified, image
 * URLs in-lined, and this method recursively called to in-line nested
 * &#064;imports./*from w w w.j a  v  a 2s  .  c o m*/
 * 
 * @param css
 *            The current CSS containing &#064;import statements to be
 *            processed
 * @param uri
 *            The URI for the current CSS
 * @param path
 *            The path, as specified in the &#064;import statement used to
 *            import the current CSS, or null if this is the top level CSS.
 * 
 * @return The input CSS with &#064;import statements replaced with the
 *         contents of the imported files.
 * 
 * @throws IOException
 */
protected String inlineImports(HttpServletRequest req, String css, IResource res, String path)
        throws IOException {

    // In-lining of imports can be disabled by request parameter for debugging
    if (!TypeUtil.asBoolean(req.getParameter(INLINEIMPORTS_REQPARAM_NAME), true)) {
        return css;
    }

    StringBuffer buf = new StringBuffer();
    IAggregator aggregator = (IAggregator) req.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME);
    IOptions options = aggregator.getOptions();
    /*
     * True if we should include the name of imported CSS files in a comment at
     * the beginning of the file.
     */
    boolean includePreamble = TypeUtil.asBoolean(req.getAttribute(IHttpTransport.SHOWFILENAMES_REQATTRNAME))
            && (options.isDebugMode() || options.isDevelopmentMode());
    if (includePreamble && path != null && path.length() > 0) {
        buf.append("/* @import " + path + " */\r\n"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    Matcher m = importPattern.matcher(css);
    while (m.find()) {
        String fullMatch = m.group(0);
        String importNameMatch = m.group(2);
        String mediaTypes = m.group(4);

        /*
         * CSS rules require that all @import statements appear before any
         * style definitions within a document. Most browsers simply ignore
         * @import statements which appear following any styles definitions.
         * This means that once we've inlined an @import, then we can't not
         * inline any subsequent @imports. The implication is that all
         * @imports which cannot be inlined (i.e. non-relative url or device
         * specific media types) MUST appear before any @import that is
         * inlined. For this reason, we throw an error if we encounter an
         * @import which we cannot inline if we have already inlined a
         * previous @import.
         */

        //Only process media type "all" or empty media type rules.
        if (mediaTypes.length() > 0 && !"all".equals(StringUtils.trim(mediaTypes))) { //$NON-NLS-1$
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }
        // remove quotes.
        importNameMatch = quotedStringTrimPattern.matcher(importNameMatch).replaceAll(""); //$NON-NLS-1$
        importNameMatch = forwardSlashPattern.matcher(importNameMatch).replaceAll("/"); //$NON-NLS-1$

        // if name is not relative, then bail
        if (importNameMatch.startsWith("/") || protocolPattern.matcher(importNameMatch).find()) { //$NON-NLS-1$
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append(fullMatch);
            continue;
        }

        IResource importRes = res.resolve(importNameMatch);
        String importCss = null;
        importCss = readToString(new CommentStrippingReader(
                new InputStreamReader(importRes.getURI().toURL().openStream(), "UTF-8" //$NON-NLS-1$
                )));
        importCss = minify(importCss, importRes);
        // Inline images
        importCss = inlineImageUrls(req, importCss, importRes);

        if (inlineImports) {
            importCss = inlineImports(req, importCss, importRes, importNameMatch);
        }
        m.appendReplacement(buf, ""); //$NON-NLS-1$
        buf.append(importCss);
    }
    m.appendTail(buf);

    css = buf.toString();
    /*
     * Now re-write all relative URLs in url(...) statements to make them relative
     * to the importing CSS
     */
    if (path != null && path.length() > 0) {
        int idx = path.lastIndexOf("/"); //$NON-NLS-1$
        //Make a file path based on the last slash.
        //If no slash, so must be just a file name. Use empty string then.
        path = (idx != -1) ? path.substring(0, idx + 1) : ""; //$NON-NLS-1$
        buf = new StringBuffer();
        m = urlPattern.matcher(css);
        while (m.find()) {
            String fullMatch = m.group(0);
            String urlMatch = m.group(1);

            urlMatch = StringUtils.trim(urlMatch.replace("\\", "/")); //$NON-NLS-1$ //$NON-NLS-2$
            String quoted = ""; //$NON-NLS-1$
            if (urlMatch.charAt(0) == '"' && urlMatch.charAt(urlMatch.length() - 1) == '"') {
                quoted = "\""; //$NON-NLS-1$
                urlMatch = urlMatch.substring(1, urlMatch.length() - 1);
            } else if (urlMatch.charAt(0) == '\'' && urlMatch.charAt(urlMatch.length() - 1) == '\'') {
                quoted = "'"; //$NON-NLS-1$
                urlMatch = urlMatch.substring(1, urlMatch.length() - 1);
            }

            // Don't modify non-relative URLs
            if (urlMatch.startsWith("/") || urlMatch.startsWith("#") //$NON-NLS-1$//$NON-NLS-2$
                    || protocolPattern.matcher(urlMatch).find()) {
                m.appendReplacement(buf, ""); //$NON-NLS-1$
                buf.append(fullMatch);
                continue;
            }

            String fixedUrl = path + ((path.endsWith("/") || path.length() == 0) ? "" : "/") + urlMatch; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            //Collapse '..' and '.'
            String[] parts = fixedUrl.split("/"); //$NON-NLS-1$
            for (int i = parts.length - 1; i > 0; i--) {
                if (".".equals(parts[i])) { //$NON-NLS-1$
                    parts = (String[]) ArrayUtils.remove(parts, i);
                } else if ("..".equals(parts[i])) { //$NON-NLS-1$
                    if (i != 0 && !"..".equals(parts[i - 1])) { //$NON-NLS-1$
                        parts = (String[]) ArrayUtils.remove(parts, i - 1);
                        parts = (String[]) ArrayUtils.remove(parts, i - 1);
                    }
                }
            }
            m.appendReplacement(buf, ""); //$NON-NLS-1$
            buf.append("url(") //$NON-NLS-1$
                    .append(quoted).append(StringUtils.join(parts, "/")) //$NON-NLS-1$
                    .append(quoted).append(")"); //$NON-NLS-1$
        }
        m.appendTail(buf);
        css = buf.toString();
    }
    return css;
}

From source file:com.taobao.tdhs.jdbc.TDHSStatement.java

private void doInsert(com.taobao.tdhs.client.statement.Statement s, ParseSQL parseSQL, String tableName,
        String dbName) throws SQLException {
    Insert insert = s.insert().use(dbName).from(tableName);
    List<Entry<String, String>> insertEntries = parseSQL.getInsertEntries();
    if (insertEntries == null || insertEntries.isEmpty()) {
        throw new TDHSSQLException("no value to insert!", parseSQL.getSql());
    }//w w w.  jav  a  2  s.  c  om
    for (Entry<String, String> e : insertEntries) {
        if (StringUtils.isBlank(e.getKey()) || StringUtils.isBlank(e.getValue())) {
            throw new TDHSSQLException("insert column and values can't be empty!", parseSQL.getSql());
        }
        String field = StringUtil.escapeField(StringUtils.trim(e.getKey()));
        if (field == null) {
            throw new TDHSSQLException("insert column is error!", parseSQL.getSql());
        }
        String value = StringUtils.trim(e.getValue());
        if (StringUtils.equalsIgnoreCase("null", value)) {
            insert.valueSetNull(field);
        } else if (StringUtils.equalsIgnoreCase("now()", value)) {
            insert.valueSetNow(field);
        } else {
            value = StringUtil.escapeValue(value);
            if (value == null) {
                throw new TDHSSQLException("insert value is error!", parseSQL.getSql());
            }
            if (StringUtils.startsWith(value, BYTE_PARAMETER_PREFIX)) {
                int pidx = ConvertUtil
                        .safeConvertInt(StringUtils.substring(value, BYTE_PARAMETER_PREFIX.length()), -1);
                if (byteParameters.containsKey(pidx)) {
                    insert.value(field, byteParameters.get(pidx));
                } else {
                    insert.value(field, value);
                }
            } else {
                insert.value(field, value);
            }
        }
    }
    TDHSResponse response = null;
    try {
        response = insert.insert();
    } catch (TDHSException e) {
        throw new SQLException(e);
    }
    processResponse(response, null, true, true);
}

From source file:com.openteach.diamond.service.DiamondServiceFactory.java

/**
 * //from w ww  .j av a  2  s  .  c o  m
 * @param properties
 * @param repositoryClient
 * @return
 */
private static MetadataReadService newMetadataReadService(Properties properties,
        RepositoryClient repositoryClient) {
    String factoryClassName = StringUtils.trim(properties.getProperty(METADATA_READ_FACTORY));
    if (StringUtils.isBlank(factoryClassName)) {
        throw new IllegalArgumentException(String.format("Please set %s", METADATA_READ_FACTORY));
    }
    try {
        Class<?> clazz = Class.forName(factoryClassName);
        MetadataReadServiceFactory factory = (MetadataReadServiceFactory) clazz.newInstance();
        return factory.newMetadataReadService(repositoryClient);
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("OOPS, new metadata read service failed", e);
    } catch (InstantiationException e) {
        throw new IllegalArgumentException("OOPS, new metadata read service failed", e);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException("OOPS, new metadata read service failed", e);
    }
}

From source file:mitm.application.djigzo.james.mailets.SMIMEHandlerTest.java

@Test
public void testDecryptOL2010WithMissingSKIInSubjectWorkaroundEnabled() throws Exception {
    boolean skiWorkaroundEnabled = SecurityConstants.isOutlook2010SKIWorkaroundEnabled();

    try {/* w  w w  . j  av a2s  . co  m*/
        SecurityConstants.setOutlook2010SKIWorkaroundEnabled(true);

        importKeyStore(keyAndCertificateWorkflow,
                new File("test/resources/testdata/keys/outlook2010_cert_missing_subjkeyid.p12"), "");

        SMIMEHandler mailet = new SMIMEHandler();

        mailetConfig.setInitParameter("handledProcessor", "handled");

        mailet.init(mailetConfig);

        MockMail mail = new MockMail();

        MimeMessage message = MailUtils
                .loadMessage(new File(testBase, "mail/outlook2010_cert_missing_subjkeyid.eml"));

        mail.setMessage(message);

        Set<MailAddress> recipients = new HashSet<MailAddress>();

        recipients.add(new MailAddress("m.brinkers@pobox.com"));

        mail.setRecipients(recipients);

        mail.setSender(new MailAddress("test@example.com"));

        mailet.service(mail);

        assertEquals(1, sendMailEventListener.getMails().size());

        Mail newMail = sendMailEventListener.getMails().get(0);

        MimeMessage decrypted = newMail.getMessage();

        assertTrue(decrypted.isMimeType("text/plain"));
        assertEquals("A broken S/MIME encrypted message", decrypted.getSubject());
        assertEquals("<000c01cadd1e$d8e3b700$8aab2500$@Domain>", decrypted.getMessageID());
        assertEquals(message.getMessageID(), decrypted.getMessageID());
        assertEquals("3DES, Key size: 168", decrypted.getHeader("X-Djigzo-Info-Encryption-Algorithm-0", ","));
        assertEquals("//2219E504D5750B37D20CC930B14129E1A2E583B1/1.2.840.113549.1.1.1",
                decrypted.getHeader("X-Djigzo-Info-Encryption-Recipient-0-0", ","));
        assertEquals("Created with Outlook 2010 Beta (14.0.4536.1000)",
                StringUtils.trim((String) decrypted.getContent()));

        assertEquals(Mail.GHOST, mail.getState());
    } finally {
        SecurityConstants.setOutlook2010SKIWorkaroundEnabled(skiWorkaroundEnabled);
    }
}

From source file:info.magnolia.templating.functions.TemplatingFunctions.java

/**
 * Util method to create html attributes <code>name="value"</code>. If the value is empty an empty string will be returned.
 * This is mainly helpful to avoid empty attributes.
 *//*from w  ww.j a v  a  2  s. com*/
public String createHtmlAttribute(String name, String value) {
    value = StringUtils.trim(value);
    if (StringUtils.isNotEmpty(value)) {
        return new StringBuffer().append(name).append("=\"").append(value).append("\"").toString();
    }
    return StringUtils.EMPTY;
}

From source file:net.sf.eclipsecs.core.config.meta.MetadataFactory.java

@SuppressWarnings("unchecked")
private static void processProperties(Element moduleElement, RuleMetadata moduleMetadata,
        ResourceBundle metadataBundle) throws CheckstylePluginException {

    List<Element> propertyElements = moduleElement.elements(XMLTags.PROPERTY_METADATA_TAG);
    for (Element propertyEl : propertyElements) {

        ConfigPropertyType type = ConfigPropertyType.valueOf(propertyEl.attributeValue(XMLTags.DATATYPE_TAG));

        String name = propertyEl.attributeValue(XMLTags.NAME_TAG).trim();
        String defaultValue = StringUtils.trim(propertyEl.attributeValue(XMLTags.DEFAULT_VALUE_TAG));
        String overrideDefaultValue = StringUtils
                .trim(propertyEl.attributeValue(XMLTags.DEFAULT_VALUE_OVERRIDE_TAG));

        ConfigPropertyMetadata property = new ConfigPropertyMetadata(type, name, defaultValue,
                overrideDefaultValue);/*from   w ww.ja v a  2s.  com*/

        moduleMetadata.getPropertyMetadata().add(property);

        // get description
        String description = propertyEl.elementTextTrim(XMLTags.DESCRIPTION_TAG);
        description = localize(description, metadataBundle);
        property.setDescription(description);

        // get property enumeration values
        Element enumEl = propertyEl.element(XMLTags.ENUMERATION_TAG);
        if (enumEl != null) {
            String optionProvider = enumEl.attributeValue(XMLTags.OPTION_PROVIDER);
            if (optionProvider != null) {

                try {
                    Class<?> providerClass = CheckstylePlugin.getDefault().getAddonExtensionClassLoader()
                            .loadClass(optionProvider);

                    if (IOptionProvider.class.isAssignableFrom(providerClass)) {

                        IOptionProvider provider = (IOptionProvider) providerClass.newInstance();
                        property.getPropertyEnumeration().addAll(provider.getOptions());
                    } else if (Enum.class.isAssignableFrom(providerClass)) {

                        EnumSet<?> values = EnumSet.allOf((Class<Enum>) providerClass);
                        for (Enum e : values) {
                            property.getPropertyEnumeration().add(e.name().toLowerCase());
                        }
                    }
                } catch (ClassNotFoundException e) {
                    CheckstylePluginException.rethrow(e);
                } catch (InstantiationException e) {
                    CheckstylePluginException.rethrow(e);
                } catch (IllegalAccessException e) {
                    CheckstylePluginException.rethrow(e);
                }
            }

            // get explicit enumeration option values
            for (Element optionEl : (List<Element>) enumEl.elements(XMLTags.PROPERTY_VALUE_OPTIONS_TAG)) {
                property.getPropertyEnumeration().add(optionEl.attributeValue(XMLTags.VALUE_TAG));
            }
        }
    }
}