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

The following examples show how to use org.apache.commons.lang3.StringUtils#substringBefore() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConfigurationFunction.java    From java-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Object call(Object[] paras, Context ctx) {
	if (paras.length > 0) {
		String parameter = (String) paras[0];
		String db = StringUtils.substringBefore(parameter, ".");
		String key = StringUtils.substringAfter(parameter, ".");

		if (paras.length > 1) {
			configurations.get(db).getString(key, (String) paras[1]);
		} else {
			return configurations.get(db).getString(key);
		}

	}

	return null;
}
 
Example 2
Source File: FStringUtil.java    From Ffast-Java with MIT License 6 votes vote down vote up
/**
 * 将字符串source根据separator分割成字符串数组
 *
 * @param source
 * @param separator
 * @return
 */
public static List<String> listSplit(String source, String separator) {
    if (source == null) {
        return null;
    }
    int i = 0;
    List<String> list = new ArrayList<>(StringUtils.countMatches(source, separator) + 1);
    while (source.length() > 0) {
        String value = StringUtils.substringBefore(source, separator);
        if (!StringUtils.isEmpty(value)) {
            list.add(value);
        }

        source = StringUtils.substringAfter(source, separator);
    }
    return list;
}
 
Example 3
Source File: JsonUtils.java    From ES-Fastloader with Apache License 2.0 6 votes vote down vote up
/**
 * 将一维的kv对转化为嵌套的kv对
 * 例如:
 *  a.b.c:"test"
 *
 *  转化为:
 *
 *    {
 *      "a": {
 *          "b": {
 *              "c": "test"
 *              }
 *          }
 *    }
 *
 * @param map
 * @return
 */
public static Map<String, Object> formatMap(Map<String, Object> map) {
    Map<String, Object> result = new HashMap<>();
    for (String longKey : map.keySet()) {
        if (longKey.contains(".")) {
            String firstKey = StringUtils.substringBefore(longKey, ".");
            Map<String, Object> innerMap;
            if (result.containsKey(firstKey)) {
                innerMap = (Map<String, Object>) result.get(firstKey);
            } else {
                innerMap = new HashMap<>();
            }
            String lastKey = StringUtils.substringAfter(longKey, ".");
            innerMap.put(lastKey, map.get(longKey));
            result.put(firstKey, formatMap(innerMap));
        } else {
            result.put(longKey, map.get(longKey));
        }
    }
    return result;
}
 
Example 4
Source File: SourceOption.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ValidationResult validate(Object values)
{
    if (values != null)
    {
        for (Object value : (Iterable<?>) values)
        {
            if (value instanceof String && ((String) value).contains(":"))
                value = StringUtils.substringBefore((String)value, ":");

            if (!getAvailableValues().contains(value))
                return new ValidationResult(ValidationResult.Level.ERROR,
                            NAME + " value (" + value + ") not found, must be one of: " + getAvailableValues());
        }
    }

    return ValidationResult.SUCCESS;
}
 
Example 5
Source File: TargetOption.java    From windup with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public ValidationResult validate(Object values)
{
    if (values == null)
    {
        return new ValidationResult(ValidationResult.Level.ERROR, NAME + " parameter is required!");
    }

    for (Object value : (Iterable<?>) values)
    {
        if (value instanceof String && ((String) value).contains(":"))
            value = StringUtils.substringBefore((String)value, ":");

        if (!getAvailableValues().contains(value))
            return new ValidationResult(ValidationResult.Level.ERROR,
                        NAME + " value (" + value + ") not found, must be one of: " + getAvailableValues());
    }

    return ValidationResult.SUCCESS;
}
 
Example 6
Source File: PropertyFilters.java    From base-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 通过表达式和对比值创建属性过滤器
 * <p>
 * 	如:
 * </p>
 * <code>
 * 	PropertyFilters.build("EQS_propertyName","maurice")
 * </code>
 * 
 * @param expression 表达式
 * @param matchValue 对比值
 * 
 * @return {@link PropertyFilter}
 */
@SuppressWarnings("static-access")
public static PropertyFilter build(String expression,String matchValue) {
	
	Assert.hasText(expression, "表达式不能为空");
	
	String restrictionsNameAndClassType = StringUtils.substringBefore(expression, "_");
	
	String restrictionsName = StringUtils.substring(restrictionsNameAndClassType, 0,restrictionsNameAndClassType.length() - 1);
	String classType = StringUtils.substring(restrictionsNameAndClassType, restrictionsNameAndClassType.length() - 1, restrictionsNameAndClassType.length());
	
	FieldType FieldType = null;
	try {
		FieldType = FieldType.valueOf(classType);
	} catch (Exception e) {
		throw new IllegalAccessError("[" + expression + "]表达式找不到相应的属性类型,获取的值为:" + classType);
	}
	
	String[] propertyNames = null;
	
	if (StringUtils.contains(expression,"_OR_")) {
		String temp = StringUtils.substringAfter(expression, restrictionsNameAndClassType + "_");
		propertyNames = StringUtils.splitByWholeSeparator(temp, "_OR_");
	} else {
		propertyNames = new String[1];
		propertyNames[0] = StringUtils.substringAfterLast(expression, "_");
	}
	
	return new PropertyFilter(restrictionsName, FieldType, propertyNames,matchValue);
}
 
Example 7
Source File: HTMLAnchorElement.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the {@code username} attribute.
 * @return the {@code username} attribute
 */
@JsxGetter({CHROME, FF, FF68, FF60})
public String getUsername() {
    try {
        final String userName = getUrl().getUserInfo();
        if (userName == null) {
            return "";
        }
        return StringUtils.substringBefore(userName, ":");
    }
    catch (final MalformedURLException e) {
        return "";
    }
}
 
Example 8
Source File: AttachmentController.java    From activiti-in-action-codes with Apache License 2.0 5 votes vote down vote up
/**
 * 下载附件
 *
 * @throws IOException
 */
@RequestMapping(value = "download/{attachmentId}")
public void downloadFile(@PathVariable("attachmentId") String attachmentId, HttpServletResponse response) throws IOException {
    Attachment attachment = taskService.getAttachment(attachmentId);
    InputStream attachmentContent = taskService.getAttachmentContent(attachmentId);
    String contentType = StringUtils.substringBefore(attachment.getType(), ";");
    response.addHeader("Content-Type", contentType + ";charset=UTF-8");
    String extensionFileName = StringUtils.substringAfter(attachment.getType(), ";");
    String fileName = attachment.getName() + "." + extensionFileName;
    response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    IOUtils.copy(new BufferedInputStream(attachmentContent), response.getOutputStream());
}
 
Example 9
Source File: GrpcStubClient.java    From saluki with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public AbstractStub getGrpcClient(ChannelCall channelPool, int callType, int callTimeout) {
  String stubClassName = GrpcStubClient.this.getStubClassName();
  Channel channel = null;
  if (StringUtils.contains(stubClassName, "$")) {
    try {
      String parentName = StringUtils.substringBefore(stubClassName, "$");
      Class<?> clzz = ReflectUtils.name2class(parentName);
      Method method;
      switch (callType) {
        case Constants.RPCTYPE_ASYNC:
          method = clzz.getMethod("newFutureStub", io.grpc.Channel.class);
          break;
        case Constants.RPCTYPE_BLOCKING:
          method = clzz.getMethod("newBlockingStub", io.grpc.Channel.class);
          break;
        default:
          method = clzz.getMethod("newFutureStub", io.grpc.Channel.class);
          break;
      }
      channel = channelPool.getChannel(refUrl);
      AbstractStub stubInstance = (AbstractStub) method.invoke(null, channel);
      return stubInstance;
    } catch (Exception e) {
      throw new IllegalArgumentException(
          "stub definition not correct,do not edit proto generat file", e);
    }
  } else {
    throw new IllegalArgumentException(
        "stub definition not correct,do not edit proto generat file");
  }
}
 
Example 10
Source File: RocksDBFlowFileRepository.java    From nifi with Apache License 2.0 5 votes vote down vote up
static String normalizeSwapLocation(final String swapLocation) {
    if (swapLocation == null) {
        return null;
    }

    final String normalizedPath = swapLocation.replace("\\", "/");
    final String withoutTrailing = (normalizedPath.endsWith("/") && normalizedPath.length() > 1) ? normalizedPath.substring(0, normalizedPath.length() - 1) : normalizedPath;
    final String pathRemoved = getLocationSuffix(withoutTrailing);

    return StringUtils.substringBefore(pathRemoved, ".");
}
 
Example 11
Source File: URLTools.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String getQueryStringParameter(String queryString, String name) {
	String value = StringUtils.substringAfter(queryString, name + "=");
	if (StringUtils.contains(value, "&")) {
		return StringUtils.substringBefore(value, "&");
	} else if (StringUtils.contains(value, "!")) {
		return StringUtils.substringBefore(value, "!");
	} else {
		return value;
	}
}
 
Example 12
Source File: DetailFactory.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
@SuppressWarnings("checkstyle:ParameterNumber")
private Object createFilteredView(final String link, final Run<?, ?> owner, final AnalysisResult result,
        final Report allIssues, final Report newIssues, final Report outstandingIssues, final Report fixedIssues,
        final Charset sourceEncoding, final IssuesDetail parent, final StaticAnalysisLabelProvider labelProvider) {
    String plainLink = removePropertyPrefix(link);
    if (link.startsWith("source.")) {
        Issue issue = allIssues.findById(UUID.fromString(plainLink));
        if (ConsoleLogHandler.isInConsoleLog(issue.getFileName())) {
            try (Stream<String> consoleLog = buildFolder.readConsoleLog(owner)) {
                return new ConsoleDetail(owner, consoleLog, issue.getLineStart(), issue.getLineEnd());
            }
        }
        else {
            String description = labelProvider.getSourceCodeDescription(owner, issue);
            String icon = jenkins.getImagePath(labelProvider.getSmallIconUrl());
            try (Reader affectedFile = buildFolder.readFile(owner, issue.getFileName(), sourceEncoding)) {
                return new SourceDetail(owner, affectedFile, issue, description, icon);
            }
            catch (IOException e) {
                try (StringReader fallback = new StringReader(
                        String.format("%s%n%s", ExceptionUtils.getMessage(e), ExceptionUtils.getStackTrace(e)))) {
                    return new SourceDetail(owner, fallback, issue, description, icon);
                }
            }
        }
    }

    String url = parent.getUrl() + "/" + plainLink;
    String property = StringUtils.substringBefore(link, ".");
    Predicate<Issue> filter = createPropertyFilter(plainLink, property);
    Report selectedIssues = allIssues.filter(filter);
    return new IssuesDetail(owner, result,
            selectedIssues, newIssues.filter(filter), outstandingIssues.filter(filter),
            fixedIssues.filter(filter), getDisplayNameOfDetails(property, selectedIssues), url,
            labelProvider, sourceEncoding);
}
 
Example 13
Source File: GenericInvokeUtils.java    From saluki with Apache License 2.0 5 votes vote down vote up
private static Object generateCollectionType(ServiceDefinition def, String type, MetadataType metadataType,
                                             Set<String> resolvedTypes) {
    type = StringUtils.substringAfter(type, "<");
    type = StringUtils.substringBefore(type, ">");
    if (StringUtils.isEmpty(type)) {
        type = "java.lang.Object";
    }
    return new Object[] { generateType(def, type, metadataType, resolvedTypes) };
}
 
Example 14
Source File: ClassLoaderImpl.java    From cuba with Apache License 2.0 4 votes vote down vote up
private boolean cacheContainsFirstLevelClass(String qualifiedClassName) {
    String outerClassName = StringUtils.substringBefore(qualifiedClassName, "$");
    return proxyClassLoader.contains(outerClassName);
}
 
Example 15
Source File: SearchCondVisitor.java    From syncope with Apache License 2.0 4 votes vote down vote up
private SearchCond transform(final String operator, final String left, final String right) {
    SearchCond result = null;

    if (MULTIVALUE.contains(StringUtils.substringBefore(left, "."))) {
        if (conf.getUserConf() == null) {
            throw new IllegalArgumentException("No " + SCIMUserConf.class.getName() + " provided, cannot continue");
        }

        switch (StringUtils.substringBefore(left, ".")) {
            case "emails":
                result = complex(operator, left, right, conf.getUserConf().getEmails());
                break;

            case "phoneNumbers":
                result = complex(operator, left, right, conf.getUserConf().getPhoneNumbers());
                break;

            case "ims":
                result = complex(operator, left, right, conf.getUserConf().getIms());
                break;

            case "photos":
                result = complex(operator, left, right, conf.getUserConf().getPhotos());
                break;

            case "addresses":
                result = addresses(operator, left, right, conf.getUserConf().getAddresses());
                break;

            default:
        }
    }

    if (result == null) {
        AttrCond attrCond = createAttrCond(left);
        attrCond.setExpression(StringUtils.strip(right, "\""));
        result = setOperator(attrCond, operator);
    }

    if (result == null) {
        throw new IllegalArgumentException(
                "Could not handle (" + left + " " + operator + " " + right + ") for " + resource);
    }
    return result;
}
 
Example 16
Source File: AbstractHttpRequest.java    From gecco with MIT License 4 votes vote down vote up
@Override
public void setUrl(String url) {
	this.url = StringUtils.substringBefore(url, "#");
}
 
Example 17
Source File: ReflectUtils.java    From supplierShop with MIT License 4 votes vote down vote up
/**
 * 直接调用对象方法, 无视private/protected修饰符,
 * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
 * 只匹配函数名,如果有多个同名函数调用第一个。
 */
@SuppressWarnings("unchecked")
public static <E> E invokeMethodByName(final Object obj, final String methodName, final Object[] args)
{
    Method method = getAccessibleMethodByName(obj, methodName, args.length);
    if (method == null)
    {
        // 如果为空不报错,直接返回空。
        logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
        return null;
    }
    try
    {
        // 类型转换(将参数数据类型转换为目标方法参数类型)
        Class<?>[] cs = method.getParameterTypes();
        for (int i = 0; i < cs.length; i++)
        {
            if (args[i] != null && !args[i].getClass().equals(cs[i]))
            {
                if (cs[i] == String.class)
                {
                    args[i] = Convert.toStr(args[i]);
                    if (StringUtils.endsWith((String) args[i], ".0"))
                    {
                        args[i] = StringUtils.substringBefore((String) args[i], ".0");
                    }
                }
                else if (cs[i] == Integer.class)
                {
                    args[i] = Convert.toInt(args[i]);
                }
                else if (cs[i] == Long.class)
                {
                    args[i] = Convert.toLong(args[i]);
                }
                else if (cs[i] == Double.class)
                {
                    args[i] = Convert.toDouble(args[i]);
                }
                else if (cs[i] == Float.class)
                {
                    args[i] = Convert.toFloat(args[i]);
                }
                else if (cs[i] == Date.class)
                {
                    if (args[i] instanceof String)
                    {
                        args[i] = DateUtils.parseDate(args[i]);
                    }
                    else
                    {
                        args[i] = DateUtil.getJavaDate((Double) args[i]);
                    }
                }
            }
        }
        return (E) method.invoke(obj, args);
    }
    catch (Exception e)
    {
        String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
        throw convertReflectionExceptionToUnchecked(msg, e);
    }
}
 
Example 18
Source File: DefaultQueryItemLocator.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
private String getElement( String dimension, int pos )
{
    String dim = StringUtils.substringBefore(dimension, ITEM_SEP);

    String[] dimSplit = dim.split( "\\" + PROGRAMSTAGE_SEP );

    return dimSplit.length == 1 ? dimSplit[0] : dimSplit[pos];

}
 
Example 19
Source File: HTMLAnchorElement.java    From htmlunit with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the protocol portion of the link's URL.
 * @param protocol the new protocol portion of the link's URL
 * @throws Exception if an error occurs
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms534353.aspx">MSDN Documentation</a>
 */
@JsxSetter
public void setProtocol(final String protocol) throws Exception {
    final String bareProtocol = StringUtils.substringBefore(protocol, ":");
    setUrl(UrlUtils.getUrlWithNewProtocol(getUrl(), bareProtocol));
}
 
Example 20
Source File: DbUsernameConverterService.java    From cloudbreak with Apache License 2.0 2 votes vote down vote up
/**
 * Converts a connection username to a db username.
 * On azure, connection username follows the 'username@short-hostname' pattern.
 * On postgres, however, users have to be in 'username' format, without the '@' sign => code has to take username.
 *
 * @param username a connection username
 * @return returns the username part before the '@' sign
 */
public String toDatabaseUsername(String username) {
    return StringUtils.substringBefore(username, "@");
}