Java Code Examples for org.apache.commons.lang.StringUtils#startsWithAny()

The following examples show how to use org.apache.commons.lang.StringUtils#startsWithAny() . 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: MetaDumpUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
public static void dumpResources(KylinConfig kylinConfig, String metaOutDir, Set<String> dumpList)
        throws IOException {
    long startTime = System.currentTimeMillis();

    ResourceStore from = ResourceStore.getStore(kylinConfig);
    KylinConfig localConfig = KylinConfig.createInstanceFromUri(metaOutDir);
    ResourceStore to = ResourceStore.getStore(localConfig);
    final String[] tolerantResources = { "/table_exd" };

    for (String path : dumpList) {
        RawResource res = from.getResource(path);
        if (res == null) {
            if (StringUtils.startsWithAny(path, tolerantResources)) {
                continue;
            } else {
                throw new IllegalStateException("No resource found at -- " + path);
            }
        }
        to.putResource(path, res.content(), res.lastModified());
        res.content().close();
    }

    logger.debug("Dump resources to {} took {} ms", metaOutDir, System.currentTimeMillis() - startTime);
}
 
Example 2
Source File: KafkaTimelineMetricsReporter.java    From ambari-metrics with Apache License 2.0 6 votes vote down vote up
protected boolean isExcludedMetric(String metricName) {
  if (excludedMetrics.contains(metricName)) {
    return true;
  }
  if (LOG.isTraceEnabled()) {
    LOG.trace("metricName => " + metricName +
      ", exclude: " + StringUtils.startsWithAny(metricName, excludedMetricsPrefixes) +
      ", include: " + StringUtils.startsWithAny(metricName, includedMetricsPrefixes));
  }
  if (StringUtils.startsWithAny(metricName, excludedMetricsPrefixes)) {
    if (!(StringUtils.startsWithAny(metricName, includedMetricsPrefixes) || Arrays.stream(includedMetricsRegex).anyMatch(metricName::matches))) {
      excludedMetrics.add(metricName);
      return true;
    }
  }
  return false;
}
 
Example 3
Source File: WebUtils.java    From ymate-platform-v2 with Apache License 2.0 6 votes vote down vote up
/**
 * @param request HttpServletRequest对象
 * @return 获取当前站点基准URL
 */
public static String baseURL(HttpServletRequest request) {
    StringBuilder basePath = new StringBuilder();
    String _serverName = __doGetSafeServerName(request);
    if (!StringUtils.startsWithAny(StringUtils.lowerCase(_serverName), new String[]{"http://", "https://"})) {
        basePath.append(request.getScheme()).append("://").append(_serverName);
        if (request.getServerPort() != 80 && request.getServerPort() != 443) {
            basePath.append(":").append(request.getServerPort());
        }
        if (StringUtils.isNotBlank(request.getContextPath())) {
            basePath.append(request.getContextPath());
        }
    } else {
        basePath.append(_serverName);
    }
    if (basePath.charAt(basePath.length() - 1) != '/') {
        basePath.append("/");
    }
    return basePath.toString();
}
 
Example 4
Source File: DefaultBeanLoader.java    From ymate-platform-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public void load(IBeanFactory beanFactory, IBeanFilter filter) throws Exception {
    if (!beanFactory.getPackageNames().isEmpty()) {
        String[] _excludedPackages = beanFactory.getExcludedPackageNames().toArray(new String[0]);
        for (String _packageName : beanFactory.getPackageNames()) {
            List<Class<?>> _classes = __doLoad(beanFactory, _packageName, filter);
            for (Class<?> _class : _classes) {
                if (!StringUtils.startsWithAny(_class.getPackage().getName(), _excludedPackages)) {
                    // 不扫描注解、枚举类,被声明@Ingored注解的类也将被忽略,因为需要处理package-info信息,所以放开接口限制
                    if (!_class.isAnnotation() && !_class.isEnum() && !_class.isAnnotationPresent(Ignored.class)) {
                        Annotation[] _annotations = _class.getAnnotations();
                        if (_annotations != null && _annotations.length > 0) {
                            for (Annotation _anno : _annotations) {
                                IBeanHandler _handler = beanFactory.getBeanHandler(_anno.annotationType());
                                if (_handler != null) {
                                    Object _instance = _handler.handle(_class);
                                    if (_instance != null) {
                                        if (_instance instanceof BeanMeta) {
                                            beanFactory.registerBean((BeanMeta) _instance);
                                        } else {
                                            beanFactory.registerBean(_class, _instance);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example 5
Source File: MessageStructureUtils.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Process a piece of the message that is assumed to have a valid html tag
 *
 * @param messagePiece String piece with html tag content
 * @param currentMessageComponent the state of the current text based message being built
 * @param view current View
 * @return currentMessageComponent with the new textual content generated by this method appended to its
 *         messageText
 */
private static Message processHtmlContent(String messagePiece, Message currentMessageComponent, View view) {
    //raw html
    messagePiece = messagePiece.trim();

    if (StringUtils.startsWithAny(messagePiece, KRADConstants.MessageParsing.UNALLOWED_HTML) || StringUtils
            .endsWithAny(messagePiece, KRADConstants.MessageParsing.UNALLOWED_HTML)) {
        throw new RuntimeException("The following html is not allowed in Messages: " + Arrays.toString(
                KRADConstants.MessageParsing.UNALLOWED_HTML));
    }

    messagePiece = "<" + messagePiece + ">";

    return concatenateStringMessageContent(currentMessageComponent, messagePiece, view);
}
 
Example 6
Source File: CreateI18NKeysForConnectionHandler.java    From rapidminer-studio with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Writes all properties to the given {@code newPath} after reading in {@code backupPath}. Adds all connection
 * related keys in one block which might be appended to the end of the file if it did not exist before. Will keep
 * an existing block in the same space and expand on it. Also will remove all keys that are outside of that block.
 *
 * @param namespace
 * 		the namespace of the affected handlers
 * @param connectionPropertyValues
 * 		the key/value pair lines, in blocks and sorted
 * @param backupPath
 * 		the original file to expand on
 * @param newPath
 * 		the new file to write to
 * @throws IOException
 * 		if an I/O error occurs
 * @see #writeProperties(BufferedWriter, Map)
 */
private static void writeProperties(String namespace, Map<String, List<List<String>>> connectionPropertyValues,
									Path backupPath, Path newPath) throws IOException {
	String[] prefixes = Stream.of(TYPE_PREFIX, GROUP_PREFIX, PARAMETER_PREFIX)
			.map(p -> p + '.' + namespace).toArray(String[]::new);
	try (BufferedReader reader = Files.newBufferedReader(backupPath);
		 BufferedWriter writer = Files.newBufferedWriter(newPath, CREATE, TRUNCATE_EXISTING)) {
		int status = 0;
		String line;
		while ((line = reader.readLine()) != null) {
			switch (status) {
				case 0:
					if (StringUtils.startsWithAny(line, prefixes)) {
						// skip connection keys that are not collected in the proper area
						// they will be added again later
						break;
					}
					writer.write(line);
					writer.newLine();
					if (line.equals(CONNECTION_HEADER)) {
						status = 1;
					}
					break;
				case 1:
					writer.write(line);
					writer.newLine();
					writeProperties(writer, connectionPropertyValues);
					while ((line = reader.readLine()) != null && !line.startsWith("##")) {
						//skip existing connection entries
					}
					if (line != null) {
						writer.newLine();
						writer.write(line);
						writer.newLine();
					}
					status = 2;
					break;
				case 2:
					writer.write(line);
					writer.newLine();
					break;
				default:
					break;
			}
		}
		if (status == 0) {
			// no connections so far, append it all
			writer.newLine();
			writer.write(HEADER_LINE);
			writer.newLine();
			writer.write(CONNECTION_HEADER);
			writer.newLine();
			writer.write(HEADER_LINE);
			writer.newLine();
			writeProperties(writer, connectionPropertyValues);
		}
	}
}
 
Example 7
Source File: AbstractOperator.java    From ymate-platform-v2 with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws Exception {
    if (!this.executed) {
        StopWatch _time = new StopWatch();
        _time.start();
        int _effectCounts = 0;
        try {
            _effectCounts = __doExecute();
            // 执行过程未发生异常将标记已执行,避免重复执行
            this.executed = true;
        } finally {
            _time.stop();
            this.expenseTime = _time.getTime();
            //
            if (_LOG.isInfoEnabled()) {
                DataSourceCfgMeta _meta = this.connectionHolder.getDataSourceCfgMeta();
                if (_meta.isShowSQL()) {
                    String _logStr = ExpressionUtils.bind("[${sql}]${param}[${count}][${time}]")
                            .set("sql", StringUtils.defaultIfBlank(this.sql, "@NULL"))
                            .set("param", __doSerializeParameters())
                            .set("count", _effectCounts + "")
                            .set("time", this.expenseTime + "ms").getResult();
                    StringBuilder _stackSB = new StringBuilder(_logStr);
                    if (_meta.isStackTraces()) {
                        String[] _tracePackages = StringUtils.split(_meta.getStackTracePackage(), "|");
                        StackTraceElement[] _stacks = new Throwable().getStackTrace();
                        if (_stacks != null && _stacks.length > 0) {
                            int _depth = _meta.getStackTraceDepth() <= 0 ? _stacks.length : (_meta.getStackTraceDepth() > _stacks.length ? _stacks.length : _meta.getStackTraceDepth());
                            if (_depth > 0) {
                                for (int _idx = 0; _idx < _depth; _idx++) {
                                    if (_tracePackages != null && _tracePackages.length > 0) {
                                        if (StringUtils.contains(_stacks[_idx].getClassName(), "$$EnhancerByCGLIB$$") || !StringUtils.startsWithAny(_stacks[_idx].getClassName(), _tracePackages)) {
                                            continue;
                                        }
                                    }
                                    _stackSB.append("\n\t--> ").append(_stacks[_idx]);
                                }
                            }
                        }
                    }
                    _LOG.info(_stackSB.toString());
                }
            }
        }
    }
}
 
Example 8
Source File: QuerySuggestionSource.java    From otroslogviewer with Apache License 2.0 4 votes vote down vote up
protected String getLastNotFinishedCondition(String s) {
    if (s.matches("\\s*(&&\\|\\|)?\\s*\\(.*")) {
      final int closingIndex = closingParenthesisPosition(s);
      if (closingIndex > 0) {
        String substring = s.substring(closingIndex + 1);
        if (substring.matches("\\s*(&&\\|\\|)?\\s*(.*)")) {
          substring = substring.replaceFirst("\\s*(&&|\\|\\|)?\\s*(.*)", "$2");
        }
        return getLastNotFinishedCondition(substring);
      }
    }
    //pattern field operator value
    // level == INFO
    // message != exception
    final String fieldOperatorValue = fieldsPattern + "\\s*" + operatorsPattern + "\\s*(\\S+.*)";
    final Pattern pattern = Pattern.compile(fieldOperatorValue);
//    System.out.println("Pattern is " + fieldOperatorValue);
    //get last not finished query =>
    // level>INFO && message ~= ala  =>
    // level>INFO && message ~=   => message ~=
    String rest = s;
    if (rest.matches(fieldOperatorValue)) {
//      System.out.println("rest is: " + rest);
      final Matcher matcher = pattern.matcher(rest);
      matcher.find();
      for (int i = 0; i <= matcher.groupCount(); i++) {
        System.out.printf("Group %d=\"%s\"%n", i, matcher.group(i));
      }

      String group3 = matcher.group(3);
      group3 = trimLeading(group3);
      if (isLastValue(group3)) {
        return rest;
      }
      //rest can be:
      // value && level>INFO
      // 'message with &&' || .....
      // "message with &&" || .....
      String anotherQuery = "";
      if (group3.matches("\\w+")) {
        anotherQuery = "";
      } else if (group3.matches("\\w+\\s*(\\S+.*)")) {
        anotherQuery = group3.replaceFirst("\\w+\\s*(\\S+.*\\s)", "$1");
      } else if (group3.matches("'.+?'(.*)")) {
        anotherQuery = group3.replaceFirst("'.+?'(.*)", "$1");
      } else if (group3.matches("\".+?\"(.*)")) {
        anotherQuery = group3.replaceFirst("\".+?\"(.*)", "$1");
      }
      rest = anotherQuery;

      rest = trimLeading(rest);
      boolean operatorFound = StringUtils.startsWithAny(rest, new String[]{"&&", "||"});
      if (operatorFound) {
        rest = rest.substring(2);
        rest = trimLeading(rest);
      }
      rest = getLastNotFinishedCondition(rest);
    }

    return rest;
  }
 
Example 9
Source File: GamaType.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String asPattern() {
	final boolean vowel = StringUtils.startsWithAny(name, vowels);
	return "${" + (vowel ? "an_" : "a_") + name + "}";
}
 
Example 10
Source File: ParametricType.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String asPattern() {
	final boolean vowel = StringUtils.startsWithAny(type.getName(), vowels);
	return "${" + (vowel ? "an_" : "a_") + serialize(true) + "}";
}
 
Example 11
Source File: RepositoryDetailsController.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * @return 'true' if the course is a campuskurs and the the appropriate flag indicating the synchronization of the description and the title is true and 'false'
 *         otherwise.
 */
private boolean isCampusCourseAndSynchronizeTitleAndDescriptionEnabled() {
    String[] descriptionStartWithArray = campusConfiguration.getDescriptionStartWithStringAsArray();
    return campusConfiguration.isSynchronizeTitleAndDescriptionEnabled() && repositoryEntry.getDescription() != null
            && StringUtils.startsWithAny(repositoryEntry.getDescription().toLowerCase(), descriptionStartWithArray);
}