Java Code Examples for org.apache.commons.lang3.StringUtils.split()

The following are Jave code examples for showing how to use split() of the org.apache.commons.lang3.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: smarti   File: QueryBuilderService.java   View Source Code Vote up 6 votes
/**
 * Getter for the QueryBuilder for the parsed creator string
 * @param creator the creator string formated as '<code>queryBuilder/{queryBuilder#getName()}/{config#getName()}</code>'
 * where '<code>{queryBuilder#getName()}</code>' is the same as '<code>{config#getType()}</code>'
 * @return the {@link QueryBuilder} or <code>null</code> if not present
 */
public <C extends ComponentConfiguration> Entry<QueryBuilder<C>,C> getQueryBuilder(String creator, Configuration conf) {
    String[] creatorParts = StringUtils.split(creator, ':');
    if(creatorParts.length >= 2){
        QueryBuilder<C> queryBuilder = (QueryBuilder<C>)builders.get(creatorParts[1]);
        if(queryBuilder == null){
            return null;
        }
        if(creatorParts.length >= 3){
            Optional<C> config = conf.getConfiguration(queryBuilder,creatorParts[2]);
            if(config.isPresent()){
                return new ImmutablePair<>(queryBuilder, config.get());
            } else { //the referenced config was not found
                return null;
            }
        } else { //no configuration in the creator string ... so a null configuration is OK
            return new ImmutablePair<>(queryBuilder, null);
        }
    } else {
        return null;
    }
}
 
Example 2
Project: YiDu-Novel   File: AjaxServiceAction.java   View Source Code Vote up 6 votes
/**
 * <p>
 * 取得阅读历史
 * </p>
 */
private void getHistory() {
    logger.debug("getHistory start.");
    // 获得阅读履历
    String historys = CookieUtils.getHistoryCookie(ServletActionContext.getRequest());
    if (StringUtils.isNotEmpty(historys)) {
        String[] acnos = StringUtils.split(historys, ",");
        List<String> articlenoList = new ArrayList<String>();
        for (String articleAndchapterno : acnos) {
            String[] acnoArr = StringUtils.split(articleAndchapterno, "|");
            if (acnoArr.length > 0) {
                articlenoList.add(acnoArr[0]);
            }
        }
        if (articlenoList.size() > 0) {
            ArticleSearchBean searchBean = new ArticleSearchBean();
            searchBean.setArticlenos(StringUtils.join(articlenoList, ","));
            dto.setItems(articleService.find(searchBean));
        }
        dto.setCode(ReturnCode.SUCCESS);
    }
    logger.debug("getHistory normally end.");
}
 
Example 3
Project: Open_Source_ECOA_Toolset_AS5   File: TypesUtil.java   View Source Code Vote up 6 votes
public Library buildLibraryFromRecordType(Record rec) {
	Library ret = new Library();
	DataTypes types = new DataTypes();
	ret.setTypes(types);
	List<Field> fields = new ArrayList<Field>();
	fields.addAll(rec.getField());
	rec.getField().clear();
	for (Field field : fields) {
		if (StringUtils.containsIgnoreCase(field.getType(), ":")) {
			String[] vals = StringUtils.split(field.getType(), ":");
			field.setType(field.getType());
			Use use = new Use();
			use.setLibrary(LibraryUtil.getLibraryUseNameFromName(vals[0]));
			if (!existing(use, ret))
				ret.getUse().add(use);
		}
		rec.getField().add(field);
	}
	ret.getTypes().getSimpleOrRecordOrConstant().add(rec);
	return ret;
}
 
Example 4
Project: xm-commons   File: PrivilegeScanner.java   View Source Code Vote up 6 votes
private Privilege parse(String expression) {
    Privilege privilege = new Privilege();
    privilege.setMsName(appName);
    String[] inputParams = StringUtils.split(expression, ",");

    for (int i = 0; i < inputParams.length; i++) {
        if (i == inputParams.length - 1) {
            if (StringUtils.contains(inputParams[i], "'")) {
                privilege.setKey(StringUtils.substringBetween(inputParams[i], "'")
                    .replace("@msName", appName.toUpperCase()));
            } else {
                privilege.setKey(inputParams[i].replace("@msName", appName.toUpperCase()));
            }
        } else {
            String resource = StringUtils.substringBetween(inputParams[i], "'");
            if (StringUtils.isNotEmpty(resource)) {
                privilege.getResources().add(resource);
            }
        }
    }
    return privilege;
}
 
Example 5
Project: InControl   File: GenericRuleEvaluator.java   View Source Code Vote up 6 votes
private void addMaxCountCheck(AttributeMap map) {
    final String maxcount = map.get(MAXCOUNT);
    String[] splitted = StringUtils.split(maxcount, ',');
    Class<?> entityClass = null;
    int amount;
    try {
        amount = Integer.parseInt(splitted[0]);
    } catch (NumberFormatException e) {
        InControl.logger.log(Level.ERROR, "Bad amount for maxcount '" + splitted[0] + "'!");
        return;
    }
    if (splitted.length > 1) {
        String id = EntityTools.fixEntityId(splitted[1]);
        entityClass = EntityTools.findClassById(id);
        if (entityClass == null) {
            InControl.logger.log(Level.ERROR, "Unknown mob '" + splitted[1] + "'!");
            return;
        }
    }

    Class<?> finalEntityClass = entityClass;
    checks.add((event,query) -> {
        int count = query.getWorld(event).countEntities(finalEntityClass == null ? query.getEntity(event).getClass() : finalEntityClass);
        return count <= amount;
    });
}
 
Example 6
Project: saluki   File: GrpcReferenceRunner.java   View Source Code Vote up 6 votes
private String getGroup(SalukiReference reference, String serviceName, Class<?> referenceClass) {
  Pair<String, String> groupVersion = findGroupAndVersionByServiceName(serviceName);
  if (StringUtils.isNoneBlank(reference.group())) {
    return reference.group();
  } else if (StringUtils.isNoneBlank(groupVersion.getLeft())) {
    String replaceGroup = groupVersion.getLeft();
    Matcher matcher = REPLACE_PATTERN.matcher(replaceGroup);
    if (matcher.find()) {
      String replace = matcher.group().substring(2, matcher.group().length() - 1).trim();
      String[] replaces = StringUtils.split(replace, ":");
      if (replaces.length == 2) {
        String realGroup = env.getProperty(replaces[0], replaces[1]);
        return realGroup;
      } else {
        throw new IllegalArgumentException("replaces formater is #{XXXgroup:groupName}");
      }
    } else {
      return replaceGroup;
    }
  } else if (this.isGenericClient(referenceClass)) {
    return StringUtils.EMPTY;
  }
  throw new java.lang.IllegalArgumentException(String
      .format("reference group can not be null or empty,the servicName is %s", serviceName));

}
 
Example 7
Project: pravega-samples   File: NoopReader.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws InterruptedException {
    Options options = getOptions();
    try {
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        String[] streamId = StringUtils.split(cmd.getOptionValue("stream", DEFAULT_STREAM_ID), '/');
        if(streamId.length != 2) {
            throw new IllegalArgumentException("Stream spec must be in the form [scope]/[stream]");
        }

        final URI controllerURI = URI.create(cmd.getOptionValue("uri", DEFAULT_CONTROLLER_URI));
        new NoopReader().run(streamId[0], streamId[1], controllerURI);
    }
    catch (ParseException e) {
        System.out.format("%s.%n", e.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("NoopReader", options);
        System.exit(1);
    }
}
 
Example 8
Project: SparkSeq   File: AbstractTestCase.java   View Source Code Vote up 6 votes
protected static java.util.List<GenomeLoc> getIntervals(RefContigInfo refContigInfo, String filePath) {
    String intervalPath = TestRealignerTargetCreator.class.getResource(filePath).getFile();
    java.util.List<GenomeLoc> intervals = new ArrayList<>();
    try (BufferedReader reader = new BufferedReader(new FileReader(new File(intervalPath)))) {
        String line = reader.readLine();
        while (line != null) {
            if(line.length() > 0 && !line.startsWith("@")) {
                String[] split = StringUtils.split(line, '\t');
                String contigName = split[0];
                int contigId = refContigInfo.getId(contigName);
                int start = Integer.parseInt(split[1]);
                int stop = Integer.parseInt(split[2]);
                intervals.add(new GenomeLoc(contigName, contigId, start, stop));
            }
            line = reader.readLine();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return intervals;
}
 
Example 9
Project: plugin-bt-jira   File: JiraImportPluginResource.java   View Source Code Vote up 5 votes
/**
 * Add and return not blank values from a string split with ',' separator.
 */
private Set<String> getItems(final String rawValue) {
	final Set<String> result = new HashSet<>();
	for (final String rawItem : StringUtils.split(StringUtils.trimToEmpty(rawValue), ',')) {
		result.add(StringUtils.trim(rawItem));
	}
	return result;
}
 
Example 10
Project: Open_Source_ECOA_Toolset_AS5   File: TypesUtil.java   View Source Code Vote up 5 votes
public Library buildLibraryFromArrayType(Array arr) {
	Library ret = new Library();
	DataTypes types = new DataTypes();
	ret.setTypes(types);
	if (StringUtils.containsIgnoreCase(arr.getItemType(), ":")) {
		String[] vals = StringUtils.split(arr.getItemType(), ":");
		arr.setItemType(arr.getItemType());
		Use use = new Use();
		use.setLibrary(LibraryUtil.getLibraryUseNameFromName(vals[0]));
		if (!existing(use, ret))
			ret.getUse().add(use);
	}
	ret.getTypes().getSimpleOrRecordOrConstant().add(arr);
	return ret;
}
 
Example 11
Project: cyberduck   File: LaxHostnameDelegatingTrustManager.java   View Source Code Vote up 5 votes
@Override
public void setTarget(final String hostname) {
    final String simple;
    final String[] parts = StringUtils.split(hostname, '.');
    if(parts.length > 4) {
        ArrayUtils.reverse(parts);
        // Rewrite c.cyberduck.s3.amazonaws.com which does not match wildcard certificate *.s3.amazonaws.com
        simple = StringUtils.join(parts[3], ".", parts[2], ".", parts[1], ".", parts[0]);
        log.warn(String.format("Rewrite hostname target to %s", simple));
    }
    else {
        simple = hostname;
    }
    super.setTarget(simple);
}
 
Example 12
Project: saluki   File: GrpcServiceRunner.java   View Source Code Vote up 5 votes
private void addRegistyAddress(RpcServiceConfig rpcSerivceConfig) {
  String registryAddress = grpcProperties.getRegistryAddress();
  if (StringUtils.isBlank(registryAddress)) {
    throw new java.lang.IllegalArgumentException("registry address can not be null or empty");
  } else {
    String[] registryHostAndPort = StringUtils.split(registryAddress, ":");
    if (registryHostAndPort.length < 2) {
      throw new java.lang.IllegalArgumentException(
          "the pattern of registry address is host:port");
    }
    rpcSerivceConfig.setRegistryAddress(registryHostAndPort[0]);
    rpcSerivceConfig.setRegistryPort(Integer.valueOf(registryHostAndPort[1]));
  }
}
 
Example 13
Project: Open_Source_ECOA_Toolset_AS5   File: PluginUtil.java   View Source Code Vote up 5 votes
public ArrayList<String> getResourcesWithExtension(String ext, String containerName) {
	ArrayList<String> ret = new ArrayList<String>();
	if (containerName != null) {
		String[] names = StringUtils.split(containerName, "/");
		IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
		IResource resource = wsRoot.findMember(new Path("/" + names[0]));
		IPath loc = resource.getLocation();
		File prjLoc = new File(loc.toString());
		Collection<File> res = FileUtils.listFiles(prjLoc, FileFilterUtils.suffixFileFilter(ext, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE);
		for (File file : res)
			ret.add(file.getAbsolutePath());
	}
	return ret;
}
 
Example 14
Project: esup-sgc   File: ShibAuthenticatedUserDetailsService.java   View Source Code Vote up 5 votes
public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws AuthenticationException {
	Set<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
	String credentials = (String)token.getCredentials();
	for(String credential : StringUtils.split(credentials, ";")) {
		if(mappingGroupesRoles != null && mappingGroupesRoles.containsKey(credential)){ 
			authorities.add(new SimpleGrantedAuthority(mappingGroupesRoles.get(credential)));
		}
	}
	for(String roleFromLdap : ldapGroup2UserRoleService.getRoles(token.getName())) {
		authorities.add(new SimpleGrantedAuthority(roleFromLdap));
	}
	log.info("Shib & Ldap Credentials for " + token.getName() + " -> " + authorities);
	return createUserDetails(token, authorities);
}
 
Example 15
Project: InControl   File: SummonAidRule.java   View Source Code Vote up 5 votes
private void addPotionsAction(AttributeMap map) {
    List<PotionEffect> effects = new ArrayList<>();
    for (String p : map.getList(ACTION_POTION)) {
        String[] splitted = StringUtils.split(p, ',');
        if (splitted == null || splitted.length != 3) {
            InControl.logger.log(Level.ERROR, "Bad potion specifier '" + p + "'! Use <potion>,<duration>,<amplifier>");
            continue;
        }
        Potion potion = ForgeRegistries.POTIONS.getValue(new ResourceLocation(splitted[0]));
        if (potion == null) {
            InControl.logger.log(Level.ERROR, "Can't find potion '" + p + "'!");
            continue;
        }
        int duration = 0;
        int amplifier = 0;
        try {
            duration = Integer.parseInt(splitted[1]);
            amplifier = Integer.parseInt(splitted[2]);
        } catch (NumberFormatException e) {
            InControl.logger.log(Level.ERROR, "Bad duration or amplifier integer for '" + p + "'!");
            continue;
        }
        effects.add(new PotionEffect(potion, duration, amplifier));
    }
    if (!effects.isEmpty()) {
        actions.add(event -> {
            EntityLivingBase living = getHelper(event);
            for (PotionEffect effect : effects) {
                PotionEffect neweffect = new PotionEffect(effect.getPotion(), effect.getDuration(), effect.getAmplifier());
                living.addPotionEffect(neweffect);
            }
        });
    }
}
 
Example 16
Project: jvm-sandbox   File: WebSocketAcceptorServlet.java   View Source Code Vote up 5 votes
private String parseUniqueId(final String pathInfo) {
    final String[] pathSegmentArray = StringUtils.split(pathInfo, "/");
    if (null != pathSegmentArray
            && pathSegmentArray.length >= 1) {
        return pathSegmentArray[0];
    }
    return null;
}
 
Example 17
Project: theskeleton   File: OAuth2ClientEntity.java   View Source Code Vote up 4 votes
@Override
public Set<String> getRegisteredRedirectUri() {
	String[] redirectUris = StringUtils.split(registeredRedirectUris, SEPARATOR);
	return redirectUris == null ? new HashSet<>() : new HashSet<>(Arrays.asList(redirectUris));
}
 
Example 18
Project: mybatis-generator-tool   File: StatusTextPlugin.java   View Source Code Vote up 4 votes
/**
 * 解析处理注释,增加 getXxxText() 方法
 *    注释格式范例:
 *      @enum 0: 有效期; 1: 无效
 */
@Override
public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass,
                                          IntrospectedColumn introspectedColumn,
                                          IntrospectedTable introspectedTable,
                                          ModelClassType modelClassType) {

    String remarks = introspectedColumn.getRemarks();
    int jdbcType = introspectedColumn.getJdbcType();

    remarks = StringUtils.trimToNull(remarks);

    if (remarks == null) {
        return true;
    }

    if (!remarks.contains("@enum")) {
        return true;
    }

    String annotation = remarks.substring(remarks.indexOf("@enum") + 5);
    String[] items = StringUtils.split(annotation, ';');

    StringBuilder mapInitSb = new StringBuilder("new HashMap<Object, String>(){{");
    for (String item : items) {
        if (!item.contains(":")) {
            continue;
        }
        String[] kv = item.split(":");
        String k = StringUtils.trim(kv[0]);
        String v = StringUtils.trim(kv[1]);
        mapInitSb.append("put(");
        if (jdbcType == Types.TINYINT) {
            mapInitSb.append("(byte)");
        }
        mapInitSb.append(k).append(",")
                .append("\"").append(v).append("\");");
    }
    mapInitSb.append("}}");

    // 增加常量
    String fieldName = String.format("%sMap", introspectedColumn.getJavaProperty());

    Field field = new Field(
            fieldName,
            new FullyQualifiedJavaType("java.util.HashMap<Object, String>")
    );
    field.setVisibility(JavaVisibility.PRIVATE);
    field.setStatic(true);
    field.setFinal(true);
    field.setInitializationString(mapInitSb.toString());

    topLevelClass.addField(field);


    // 增加方法
    Method textMethod = new Method(String.format("%sText", method.getName()));
    textMethod.setReturnType(new FullyQualifiedJavaType(String.class.getCanonicalName()));
    textMethod.setVisibility(JavaVisibility.PUBLIC);
    if (jdbcType == Types.TINYINT) {
        textMethod.addBodyLine(String.format("return %s.get((byte)this.%s);", fieldName, introspectedColumn.getJavaProperty()));
    } else {
        textMethod.addBodyLine(String.format("return %s.get(this.%s);", fieldName, introspectedColumn.getJavaProperty()));
    }

    remarks = remarks.replaceAll("\n", "\\\\n").replaceAll("\"", "\\\\\"");
    textMethod.addAnnotation(
        String.format("@ApiModelProperty(value = \"%s\")", remarks)
    );

    topLevelClass.addImportedType(new FullyQualifiedJavaType(HashMap.class.getCanonicalName()));
    topLevelClass.addMethod(textMethod);

    return true;
}
 
Example 19
Project: SVNAutoMerger   File: Merger.java   View Source Code Vote up 2 votes
/**
 * Return last revision to merge
 * @param eligibleRevisions
 * @return
 */
public int getToRevision(String eligibleRevisions) {
  String[] revisions = StringUtils.split(eligibleRevisions, System.getProperty("line.separator"));
  return Integer.parseInt(StringUtils.remove( revisions[revisions.length - 1], "r"));
}
 
Example 20
Project: uroborosql   File: StringFunction.java   View Source Code Vote up 2 votes
/**
 * 文字列を指定した区切り文字で区切って配列に格納します。
 * {@code null} が入力された場合は {@code null} を返します
 *
 * <pre>
 * split(null, *)         = null
 * split("", *)           = []
 * split("a.b.c", '.')    = ["a", "b", "c"]
 * split("a..b.c", '.')   = ["a", "b", "c"]
 * split("a:b:c", '.')    = ["a:b:c"]
 * split("a b c", ' ')    = ["a", "b", "c"]
 * </pre>
 *
 * @param str 変換元文字列 または {@code null}
 * @param separatorChar 区切り文字
 * @return 区切り文字で区切った文字列配列
 */
public String[] split(final String str, final char separatorChar) {
	return StringUtils.split(str, separatorChar);
}