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.envision.envservice.service.UserService.java

/**
 * TO BO// w ww  .  j  av  a2s  .  co m
 */
private UserBo toBo(SAPUser sapUser, boolean needManager) throws Exception {
    UserBo user = new UserBo();

    user.setUser_id(sapUser.getUserId());
    user.setName(sapUser.getUsername());
    user.setTitle(SAPUtil.toFieldDisplay(sapUser.getTitle()));
    user.setPhoto(PicUtil.getPicPath(user.getUser_id()));
    user.setCn_name(sapUser.getLastName());
    user.setEn_name(sapUser.getFirstName());
    user.setDepartment(SAPUtil.toFieldDisplay(sapUser.getDepartment()));
    user.setDivision(SAPUtil.toFieldDisplay(sapUser.getDivision()));
    user.setEmployee_type(sapUser.getCustom06());
    user.setEmail(sapUser.getEmail());
    user.setLocation(SAPUtil.toFieldDisplay(sapUser.getLocation()));
    user.setHire_date(SAPUtil.formatSAPDate(sapUser.getHireDate()));
    user.setPhone(StringUtils.trim(sapUser.getCustom08()));
    user.setChallenge_level(sapUser.getCustom04());
    user.setLast_performance_assess(sapUser.getCustom01());

    if (needManager) {
        Set<String> hlIds = orgStructureService.queryHigherLevel(user.getUser_id());
        if (hlIds.size() > 0) {
            String hdId = hlIds.toArray(new String[hlIds.size()])[0];

            List<UserBo> managers = queryByIds(false, false, hdId);
            if (managers.size() > 0) {
                UserBo manager = managers.get(0);

                user.setManager_id(hdId);
                user.setManager_cn_name(manager.getCn_name());
                user.setManager_en_name(manager.getEn_name());
            }
        }
    }

    return user;
}

From source file:hydrograph.ui.expression.editor.composites.CategoriesDialogTargetComposite.java

public void loadPackagesFromPropertyFileSettingFolder() {
    Properties properties = new Properties();
    IFolder folder = BuildExpressionEditorDataSturcture.INSTANCE.getCurrentProject()
            .getFolder(PathConstant.PROJECT_RESOURCES_FOLDER);
    IFile file = folder.getFile(PathConstant.EXPRESSION_EDITOR_EXTERNAL_JARS_PROPERTIES_FILES);
    try {//from ww w  .  j  a va  2  s  .c o  m
        LOGGER.debug("Loading property file");
        targetList.removeAll();
        if (file.getLocation().toFile().exists()) {
            FileInputStream inStream = new FileInputStream(file.getLocation().toString());
            properties.load(inStream);
            for (Object key : properties.keySet()) {
                String jarFileName = StringUtils.trim(StringUtils.substringAfter((String) key, Constants.DASH));
                if (BuildExpressionEditorDataSturcture.INSTANCE.getIPackageFragment(jarFileName) != null) {
                    targetList.add((String) key + SWT.SPACE + Constants.DASH + SWT.SPACE
                            + properties.getProperty((String) key));
                }
            }
        }
    } catch (IOException | RuntimeException exception) {
        LOGGER.error("Exception occurred while loading jar files from projects setting folder", exception);
    }

}

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

/**
 * /*from  ww w  .jav a  2s  . c om*/
 * 
 * @param model
 * @return
 */
private String automaticLogin(String telphone) {
    // 1cookie???
    if (RegexUtil.isMobile(StringUtils.trim(telphone))) {
        log.info("______________cookie???" + telphone + "");
        String returl = this.writeUserCookie(telphone);
        log.info("______________cookie????,returl=" + returl);
        return returl;
    }

    // 2???????
    log.info("______________???????");
    String sign = request.getParameter("sign");
    log.info("______________sign=" + sign);
    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);
    // ??
    String mobile = request.getParameter("mob");
    log.info("______________??????:" + mobile);
    if (StringUtils.isNotBlank(mobile)) {
        mobile = CryptoTools.decode(mobile, unicomManager.getSpPassWord());
        log.info("______________???????:" + mobile);
        if (clientSign.equalsIgnoreCase(cookiecode)) {
            return this.writeUserCookie(mobile);
        } else {
            log.error("______________???????:"
                    + CommonUtils.getRequestUrl(request));
        }
    }

    return null;
}

From source file:ch.entwine.weblounge.contentrepository.impl.endpoint.PagesEndpoint.java

/**
 * Returns a collection of pages which match the given criteria.
 * /*  w w  w .j  av  a  2s  .  c o  m*/
 * @param request
 *          the request
 * @param path
 *          the page path (e.g. <code>/my/simple/path</code>)
 * @param subjectstring
 *          one ore more subjects, divided by a comma
 * @param searchterms
 *          fulltext search terms
 * @param sort
 *          sort order, possible values are
 *          <code>created-asc, created-desc, published-asc, published-desc, modified-asc & modified-desc</code>
 * @param limit
 *          search result limit
 * @param offset
 *          search result offset (for paging in combination with limit)
 * @param details
 *          switch for providing pages including their bodies
 * @return a collection of matching pages
 */
@GET
@Path("/")
public Response getAllPages(@Context HttpServletRequest request, @QueryParam("path") String path,
        @QueryParam("subjects") String subjectstring, @QueryParam("searchterms") String searchterms,
        @QueryParam("filter") String filter, @QueryParam("sort") @DefaultValue("modified-desc") String sort,
        @QueryParam("version") @DefaultValue("-1") long version,
        @QueryParam("preferredversion") @DefaultValue("-1") long preferredVersion,
        @QueryParam("limit") @DefaultValue("10") int limit, @QueryParam("offset") @DefaultValue("0") int offset,
        @QueryParam("details") @DefaultValue("false") boolean details) {

    // Create search query
    Site site = getSite(request);
    SearchQuery q = new SearchQueryImpl(site);

    q.withTypes(Page.TYPE);
    if (version != -1)
        q.withVersion(version);

    if (preferredVersion != -1)
        q.withPreferredVersion(preferredVersion);

    // Path
    if (StringUtils.isNotBlank(path))
        q.withPath(path);

    // Subjects
    if (StringUtils.isNotBlank(subjectstring)) {
        StringTokenizer subjects = new StringTokenizer(subjectstring, ",");
        while (subjects.hasMoreTokens())
            q.withSubject(subjects.nextToken());
    }

    // Search terms
    if (StringUtils.isNotBlank(searchterms))
        q.withText(true, searchterms);

    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 0);
    today.set(Calendar.MINUTE, 0);
    today.set(Calendar.SECOND, 0);
    today.set(Calendar.MILLISECOND, 0);
    Calendar yesterday = Calendar.getInstance();
    yesterday.add(Calendar.DATE, -1);
    yesterday.set(Calendar.HOUR_OF_DAY, 0);
    yesterday.set(Calendar.MINUTE, 0);
    yesterday.set(Calendar.SECOND, 0);
    yesterday.set(Calendar.MILLISECOND, 0);
    Calendar tomorrow = Calendar.getInstance();
    tomorrow.add(Calendar.DATE, 1);
    tomorrow.set(Calendar.HOUR_OF_DAY, 0);
    tomorrow.set(Calendar.MINUTE, 0);
    tomorrow.set(Calendar.SECOND, 0);
    tomorrow.set(Calendar.MILLISECOND, 0);

    // Filter query
    if (StringUtils.isNotBlank(filter)) {
        if ("/".equals(filter)) {
            q.withPath("/");
        } else if (filter.contains("state:work")) {
            q.withVersion(Resource.WORK);
            q.withPreferredVersion(-1);
        } else if (filter.contains("state:live")) {
            q.withVersion(Resource.LIVE);
            q.withPreferredVersion(-1);
        } else if (filter.contains("state:locked")) {
            q.withLockOwner();
        }

        // by user
        else if (filter.startsWith("locked:") && filter.length() > "locked:".length()) {
            String lockOwner = StringUtils.trim(filter.substring("locked:".length()));
            if ("me".equals(lockOwner))
                q.withLockOwner(securityService.getUser());
            else
                q.withLockOwner(new UserImpl(lockOwner));
        } else if (filter.startsWith("creator:") && filter.length() > "creator:".length()) {
            String creator = StringUtils.trim(filter.substring("creator:".length()));
            if ("me".equals(creator))
                q.withCreator(securityService.getUser());
            else
                q.withCreator(new UserImpl(creator));
        } else if (filter.startsWith("modifier:") && filter.length() > "modifier:".length()) {
            String modifier = StringUtils.trim(filter.substring("modifier:".length()));
            if ("me".equals(modifier))
                q.withModifier(securityService.getUser());
            else
                q.withModifier(new UserImpl(modifier));
        } else if (filter.startsWith("publisher:") && filter.length() > "publisher:".length()) {
            String publisher = StringUtils.trim(filter.substring("publisher:".length()));
            if ("me".equals(publisher))
                q.withPublisher(securityService.getUser());
            else
                q.withPublisher(new UserImpl(publisher));
        }

        // by date

        else if (filter.startsWith("created:") && filter.length() > "created:".length()) {
            String created = StringUtils.trim(filter.substring("created:".length()));
            if ("today".equals(created))
                q.withCreationDateBetween(today.getTime()).and(tomorrow.getTime());
            else if ("yesterday".equals(created))
                q.withCreationDateBetween(yesterday.getTime()).and(today.getTime());
            else
                q.withCreationDate(tomorrow.getTime());
        } else if (filter.startsWith("modified:") && filter.length() > "modified:".length()) {
            String modified = StringUtils.trim(filter.substring("modified:".length()));
            if ("today".equals(modified))
                q.withModificationDateBetween(today.getTime()).and(tomorrow.getTime());
            else if ("yesterday".equals(modified))
                q.withModificationDateBetween(yesterday.getTime()).and(today.getTime());
            else
                q.withCreationDate(tomorrow.getTime());
        } else if (filter.startsWith("publisher:") && filter.length() > "publisher:".length()) {
            String published = StringUtils.trim(filter.substring("published:".length()));
            if ("today".equals(published))
                q.withPublishingDateBetween(today.getTime()).and(tomorrow.getTime());
            else if ("yesterday".equals(published))
                q.withPublishingDateBetween(yesterday.getTime()).and(today.getTime());
            else
                q.withCreationDate(tomorrow.getTime());
        }

        // by id
        else if (filter.contains("id:")) {
            String[] searchTerms = StringUtils.split(filter);
            for (String searchTerm : searchTerms) {
                if (searchTerm.startsWith("id:") && filter.length() > "id:".length()) {
                    q.withIdentifier(StringUtils.trim(searchTerm.substring("id:".length())));
                }
            }
        }

        // simple filter
        else if (filter.contains("/")) {
            q.withPathPrefix(filter);
        } else {
            q.withFulltext(true, filter);
        }

    }

    // Limit and Offset
    q.withLimit(limit);
    q.withOffset(offset);

    // Sort order
    if (StringUtils.equalsIgnoreCase("modified-asc", sort)) {
        q.sortByModificationDate(Order.Ascending);
    } else if (StringUtils.equalsIgnoreCase("modified-desc", sort)) {
        q.sortByModificationDate(Order.Descending);
    } else if (StringUtils.equalsIgnoreCase("created-asc", sort)) {
        q.sortByCreationDate(Order.Ascending);
    } else if (StringUtils.equalsIgnoreCase("created-desc", sort)) {
        q.sortByCreationDate(Order.Descending);
    } else if (StringUtils.equalsIgnoreCase("published-asc", sort)) {
        q.sortByPublishingDate(Order.Ascending);
    } else if (StringUtils.equalsIgnoreCase("published-desc", sort)) {
        q.sortByPublishingDate(Order.Descending);
    }

    // Load the result
    String result = loadResultSet(q, details);

    return Response.ok(result).build();
}

From source file:mitm.djigzo.web.pages.dlp.patterns.PatternsEdit.java

public Object onSuccess() {
    Object result = null;/*from w ww . j  av a 2  s.  c o  m*/

    try {
        String name = StringUtils.trim(this.name);

        PolicyPatternNodeDTO node = !isEditing() ? policyPatternManagerWS.createPattern(name)
                : policyPatternNode;

        if (node != null) {
            PolicyPatternDTO pattern = new PolicyPatternDTO();

            pattern.setName(name);
            pattern.setDescription(StringUtils.trim(description));
            pattern.setMatchFilter(matchFilter);
            pattern.setRegExp(regExp);
            pattern.setThreshold(threshold);
            pattern.setPriority(priority);

            policyPatternNodeWS.setPattern(node.getName(), pattern);

            result = PatternsView.class;
        }
    } catch (WebServiceCheckedException e) {
        logger.error("Error during submit.", e);

        errorMessage = e.getMessage();
        error = true;
    }

    return result;
}

From source file:cn.orignzmn.shopkepper.common.utils.excel.ImportExcel.java

/**
 * ??/*w  w  w.j ava  2 s .  c  o m*/
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, Map<String, Object> inportInfo, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    ExcelSheet esarr = cls.getAnnotation(ExcelSheet.class);
    String annTitle = "";
    if (esarr == null)
        return Lists.newArrayList();
    annTitle = esarr.value();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    //log.debug("Import column count:"+annotationList.size());
    // Get excel data
    List<E> dataList = Lists.newArrayList();
    //???
    if (!"".equals(annTitle)) {
        String title = StringUtils.trim(this.getCellValue(this.getRow(0), 0).toString());
        if (!annTitle.equals(title)) {
            inportInfo.put("success", false);
            inportInfo.put("message", "??");
            return Lists.newArrayList();
        }
    }
    for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
        E e = (E) cls.newInstance();
        int column = 0;
        Row row = this.getRow(i);

        StringBuilder sb = new StringBuilder();
        for (Object[] os : annotationList) {
            Object val = this.getCellValue(row, column++);
            if (val != null) {
                ExcelField ef = (ExcelField) os[0];
                // If is dict type, get dict value
                //               if (StringUtils.isNotBlank(ef.dictType())){
                //                  val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
                //                  //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
                //               }
                // Get param type and type cast
                Class<?> valType = Class.class;
                if (os[1] instanceof Field) {
                    valType = ((Field) os[1]).getType();
                } else if (os[1] instanceof Method) {
                    Method method = ((Method) os[1]);
                    if ("get".equals(method.getName().substring(0, 3))) {
                        valType = method.getReturnType();
                    } else if ("set".equals(method.getName().substring(0, 3))) {
                        valType = ((Method) os[1]).getParameterTypes()[0];
                    }
                }
                //log.debug("Import value type: ["+i+","+column+"] " + valType);
                try {
                    if (valType == String.class) {
                        String s = String.valueOf(val.toString());
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            val = String.valueOf(val.toString());
                        }
                    } else if (valType == Integer.class) {
                        val = Double.valueOf(val.toString()).intValue();
                    } else if (valType == Long.class) {
                        val = Double.valueOf(val.toString()).longValue();
                    } else if (valType == Double.class) {
                        val = Double.valueOf(val.toString());
                    } else if (valType == Float.class) {
                        val = Float.valueOf(val.toString());
                    } else if (valType == Date.class) {
                        val = DateUtil.getJavaDate((Double) val);
                    } else {
                        if (ef.fieldType() != Class.class) {
                            val = ef.fieldType().getMethod("getValue", String.class).invoke(null,
                                    val.toString());
                        } else {
                            val = Class
                                    .forName(this.getClass().getName().replaceAll(
                                            this.getClass().getSimpleName(),
                                            "fieldtype." + valType.getSimpleName() + "Type"))
                                    .getMethod("getValue", String.class).invoke(null, val.toString());
                        }
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                if (os[1] instanceof Field) {
                    Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
                } else if (os[1] instanceof Method) {
                    String mthodName = ((Method) os[1]).getName();
                    if ("get".equals(mthodName.substring(0, 3))) {
                        mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
                    }
                    Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val });
                }
            }
            sb.append(val + ", ");
        }
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}

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

/**
 * //from  www  .ja va  2 s. c  o m
 * @param properties
 * @return
 */
private static RepositoryClient newRepositoryClient(Properties properties) {
    String factoryClassName = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_FACTORY));
    if (StringUtils.isBlank(factoryClassName)) {
        throw new IllegalArgumentException(String.format("Please set %s", REPOSITORY_CLIENT_FACTORY));
    }
    // cache
    boolean eableLocalCache = false;
    String value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_LOCAL_CACHE_ENABLE));
    if (StringUtils.isNotBlank(value)) {
        if (StringUtils.equals(Boolean.TRUE.toString(), value)) {
            eableLocalCache = true;
        } else if (StringUtils.equals(Boolean.FALSE.toString(), value)) {
            eableLocalCache = false;
        } else {
            throw new IllegalArgumentException(String.format("Only %s or %s allowed for %s",
                    Boolean.TRUE.toString(), Boolean.FALSE.toString(), REPOSITORY_CLIENT_LOCAL_CACHE_ENABLE));
        }
    }
    Cache.Type type = Cache.Type.MEMORY_LRU;
    int maxEntries = Cache.DEFAULT_MAX_ENTRIES;
    int maxEntriesInMemory = maxEntries / 5;
    String cacheFileName = "/tmp/diamond-repository-local-cache.cache";
    if (eableLocalCache) {
        value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_LOCAL_CACHE_TYPE));
        if (StringUtils.isNotBlank(value)) {
            type = Cache.Type.valueOf(value);
            if (null == type) {
                throw new IllegalArgumentException(String.format("Only %s allowed for %s",
                        StringUtils.join(Cache.Type.values(), ","), REPOSITORY_CLIENT_LOCAL_CACHE_TYPE));
            }
        }
        value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_LOCAL_CACHE_MAX_ENTRIES));
        if (StringUtils.isNotBlank(value)) {
            try {
                maxEntries = Integer.valueOf(value);
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException(String.format("Only Positive integer allowed for %s",
                        REPOSITORY_CLIENT_LOCAL_CACHE_MAX_ENTRIES));
            }
            if (maxEntries <= 0) {
                throw new IllegalArgumentException(String.format("Only Positive integer allowed for %s",
                        REPOSITORY_CLIENT_LOCAL_CACHE_MAX_ENTRIES));
            }
        }
        if (Cache.Type.HYBRID_LRU == type) {
            value = StringUtils
                    .trim(properties.getProperty(REPOSITORY_CLIENT_LOCAL_CACHE_MAX_ENTRIES_IN_MEMORY));
            if (StringUtils.isNotBlank(value)) {
                try {
                    maxEntriesInMemory = Integer.valueOf(value);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException(
                            String.format("Only Positive integer and less then %s allowed for %s",
                                    REPOSITORY_CLIENT_LOCAL_CACHE_MAX_ENTRIES_IN_MEMORY,
                                    REPOSITORY_CLIENT_LOCAL_CACHE_MAX_ENTRIES));
                }
                if (maxEntriesInMemory <= 0 || maxEntriesInMemory >= maxEntries) {
                    throw new IllegalArgumentException(
                            String.format("Only Positive integer and less then %s allowed for %s",
                                    REPOSITORY_CLIENT_LOCAL_CACHE_MAX_ENTRIES_IN_MEMORY,
                                    REPOSITORY_CLIENT_LOCAL_CACHE_MAX_ENTRIES));
                }
            }
        }

        if (Cache.Type.FILE_LRU == type || Cache.Type.HYBRID_LRU == type) {
            value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_LOCAL_CACHE_FILE_NAME));
            if (StringUtils.isBlank(value)) {
                cacheFileName = value;
            }
        }
    }

    // certificate
    Certificate certificate = null;
    value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_CERTIFICATE_TYPE));
    if (StringUtils.isBlank(value)) {
        throw new IllegalArgumentException(String.format("Please set %s, value: %s or %s",
                REPOSITORY_CLIENT_CERTIFICATE_TYPE, REPOSITORY_CLIENT_CERTIFICATE_TYPE_DATABASE,
                REPOSITORY_CLIENT_CERTIFICATE_TYPE_ZOOKEEPER));
    }
    if (StringUtils.equals(REPOSITORY_CLIENT_CERTIFICATE_TYPE_DATABASE, value)) {
        certificate = new DatabaseCertificate();
        DatabaseCertificate dc = (DatabaseCertificate) certificate;
        value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_CERTIFICATE_USER_NAME));
        if (StringUtils.isBlank(value)) {
            throw new IllegalArgumentException(String.format("Please set %s, value type: string",
                    REPOSITORY_CLIENT_CERTIFICATE_USER_NAME));
        }
        dc.setUsername(value);

        value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_CERTIFICATE_PASSWORD));
        if (StringUtils.isBlank(value)) {
            throw new IllegalArgumentException(
                    String.format("Please set %s, value type: string", REPOSITORY_CLIENT_CERTIFICATE_PASSWORD));
        }
        dc.setPassword(value);

        value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_CERTIFICATE_URL));
        if (StringUtils.isBlank(value)) {
            throw new IllegalArgumentException(
                    String.format("Please set %s, value type: string", REPOSITORY_CLIENT_CERTIFICATE_URL));
        }
        dc.setUrl(value);

        value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_CERTIFICATE_DRIVER_CLASS_NAME));
        if (StringUtils.isBlank(value)) {
            throw new IllegalArgumentException(String.format("Please set %s, value type: string",
                    REPOSITORY_CLIENT_CERTIFICATE_DRIVER_CLASS_NAME));
        }
        dc.setDriverClassName(value);

        // TODO pool setting
    } else if (StringUtils.equals(REPOSITORY_CLIENT_CERTIFICATE_TYPE_ZOOKEEPER, value)) {
        throw new IllegalArgumentException(
                String.format("At now we not supported %s", REPOSITORY_CLIENT_CERTIFICATE_TYPE_ZOOKEEPER));
    } else {
        throw new IllegalArgumentException(
                String.format("Only %s or %s allowed for %s", REPOSITORY_CLIENT_CERTIFICATE_TYPE_DATABASE,
                        REPOSITORY_CLIENT_CERTIFICATE_TYPE_ZOOKEEPER, REPOSITORY_CLIENT_CERTIFICATE_TYPE));
    }

    value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_CERTIFICATE_APP_NAME));
    if (StringUtils.isBlank(value)) {
        throw new IllegalArgumentException(
                String.format("Please set %s, value type: string", REPOSITORY_CLIENT_CERTIFICATE_APP_NAME));
    }
    certificate.setAppName(value);

    value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_CERTIFICATE_SECRET));
    if (StringUtils.isBlank(value)) {
        throw new IllegalArgumentException(
                String.format("Please set %s, value type: string", REPOSITORY_CLIENT_CERTIFICATE_SECRET));
    }
    certificate.setSecret(value);

    value = StringUtils.trim(properties.getProperty(REPOSITORY_CLIENT_CERTIFICATE_NAMESPACE));
    if (StringUtils.isBlank(value)) {
        throw new IllegalArgumentException(
                String.format("Please set %s, value type: string", REPOSITORY_CLIENT_CERTIFICATE_NAMESPACE));
    }
    certificate.setNamespace(value);

    try {
        Class<?> clazz = Class.forName(factoryClassName);
        AbstractRepositoryClientFactory factory = (AbstractRepositoryClientFactory) clazz.newInstance();
        if (eableLocalCache) {
            factory.enableCache().withCacheType(type);
            factory.withMaxEntries(maxEntries);
            if (Cache.Type.FILE_LRU == type) {
                factory.withCacheFileName(cacheFileName);
            } else if (Cache.Type.HYBRID_LRU == type) {
                factory.withMaxEntriesInMemory(maxEntriesInMemory).withCacheFileName(cacheFileName);
            }
        } else {
            factory.disableCache();
        }
        return factory.withCertificate(certificate).newInstace();
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("OOPS, new repository client failed", e);
    } catch (InstantiationException e) {
        throw new IllegalArgumentException("OOPS, new repository client failed", e);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException("OOPS, new repository client failed", e);
    }
}

From source file:com.liveramp.hank.coordinator.Hosts.java

public static List<String> splitHostFlags(String flags) {
    String[] flagArray = StringUtils.split(flags, ",");
    List<String> results = new ArrayList<String>(flagArray.length);
    for (String flag : flagArray) {
        results.add(StringUtils.trim(flag));
    }/*from  w  ww.  j  a  v a 2 s .c o  m*/
    Collections.sort(results);
    return results;
}

From source file:com.openteach.diamond.rpc.impl.DefaultRPCProtocolProvider.java

/**
 * //  w ww.ja  va 2s. c o m
 * @param protocol
 * @return
 */
private RPCProtocol4Server loadRPCProtocol4Server(String protocol) {
    try {
        String factoryClassName = StringUtils
                .trim(properties.getProperty(String.format("%s.server.factory", protocol)));
        if (StringUtils.isBlank(factoryClassName)) {
            return null;
        }
        Class clazz = Class.forName(factoryClassName);
        if (!RPCProtocol4ServerFactory.class.isAssignableFrom(clazz)) {
            throw new IllegalArgumentException(
                    String.format("RPC protocol 4 client factory:%s must implements %s", factoryClassName,
                            RPCProtocol4ServerFactory.class.getName()));
        }
        RPCProtocol4ServerFactory factory = (RPCProtocol4ServerFactory) clazz.newInstance();
        return factory.newProtocol(handler);
    } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException(e);
    } catch (InstantiationException e) {
        throw new IllegalArgumentException(e);
    } catch (IllegalAccessException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:mitm.common.security.ca.CSVRequestConverter.java

/**
 * Converts the CSV to a list of RequestParameters. The first row should contain the column order. The CSV is 
 * considered to be US-ASCII encoded unless a Byte Ordering Mark (BOM) is used. 
 *  /* w ww. j  a  v a2 s  .co m*/
 * 
 * The following columns are supported:
 * 
 * EMAIL, ORGANISATION, COMMONNAME, FIRSTNAME, LASTNAME
 * 
 * Multiple aliases for the columns are available and names are case insensitive.
 * 
 * EMAIL        : [email, e]
 * ORGANISATION : [organisation, org, o]
 * COMMONNAME   : [commonname, cn]
 * FIRSTNAME    : [firstname, fn, givenname, gn]
 * LASTNAME     : [lastname, ln, surname, sn]
 * 
 * NOTE: all other fields, or fields that are not specified in the CSV, of the returned RequestParameters are 
 * NOT set.
 */
public List<RequestParameters> convertCSV(InputStream csv) throws IOException, RequestConverterException {
    Check.notNull(csv, "csv");

    foundEmails = new HashSet<String>();

    CSVReader reader = new CSVReader(new UnicodeReader(csv, CharacterEncoding.US_ASCII));

    readHeader(reader);

    checkRequiredColumns();

    List<RequestParameters> result = new LinkedList<RequestParameters>();

    String[] line;

    int currentLine = 0;

    while ((line = reader.readNext()) != null) {
        currentLine++;

        if (currentLine > maxLines) {
            throw new RequestConverterException("Maximum number of lines exceeded (" + maxLines + ").");
        }

        if (line == null || (line.length == 1 && StringUtils.isBlank(line[0]))) {
            /*
             * Skip empty lines 
             */
            continue;
        }

        if (line.length != columnOrder.length) {
            throw new RequestConverterException("Line " + currentLine + " does not contain the correct "
                    + "number of columns: " + StringUtils.join(line, ", "));
        }

        RequestParameters request = new RequestParametersImpl();

        X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder();

        for (int column = 0; column < line.length; column++) {
            String value = StringUtils.trim(line[column]);

            /*
             * Length sanity check
             */
            if (StringUtils.length(value) > maxValueLength) {
                throw new RequestConverterException("The column value " + StringUtils.defaultString(value)
                        + " at line " + currentLine + " and column " + column + " exceeds the maximum number of"
                        + " characters (" + maxValueLength + ").");
            }

            switch (columnOrder[column]) {
            case EMAIL:
                setEmail(value, request, subjectBuilder, column, currentLine);
                break;
            case ORGANISATION:
                subjectBuilder.setOrganisation(value);
                break;
            case COMMONNAME:
                setCommonName(value, subjectBuilder, column, currentLine);
                break;
            case FIRSTNAME:
                subjectBuilder.setGivenName(value);
                break;
            case LASTNAME:
                subjectBuilder.setSurname(value);
                break;

            default:
                throw new RequestConverterException("Unsupported column " + columnOrder[column]);
            }

            request.setSubject(subjectBuilder.buildPrincipal());
        }

        result.add(request);
    }

    return result;
}