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

The following examples show how to use org.apache.commons.lang3.StringUtils#endsWith() . These examples are extracted from open source projects. 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
public static String url(String... strs) throws Exception {
	List<String> os = new ArrayList<>();
	for (String str : strs) {
		String value = str;
		if (StringUtils.endsWith(value, "/")) {
			value = StringUtils.substring(value, 0, value.length() - 1);
		}
		if (StringUtils.startsWith(value, "/")) {
			value = value.substring(1);
		}
		if (StringUtils.isNotEmpty(value)) {
			if (StringUtils.containsIgnoreCase(value, "http://")
					|| StringUtils.containsIgnoreCase(value, "https://")) {
				os.add(value);
			} else {
				os.add(URLEncoder.encode(value, "UTF-8"));
			}
		}
	}
	return StringUtils.join(os, "/");

}
 
Example 2
private void configureHome() {
    String path = home;
    if (StringUtils.isBlank(path)) {
        // if the root path is not specified use sakai.home/ignite/
        path = serverConfigurationService.getSakaiHomePath();
        path = path + File.separator + "ignite";
    }

    if (StringUtils.isNotBlank(node)) {
        if (!StringUtils.endsWith(path, File.separator)) {
            path = path + File.separator;
        }
        path = path + node;
    }

    File igniteHome = new File(path);
    if (!igniteHome.exists()) igniteHome.mkdirs();

    // return the absolute path
    home = igniteHome.getAbsolutePath();
}
 
Example 3
@Override
public PaginatedListImpl<MailinglistEntry> getMailinglists(@VelocityCheck int companyId, int adminId, String sort, String direction, int page, int rownums) {
	if(!SORTABLE_FIELDS.contains(sort)) {
		sort = "shortname";
	}

	final String selectQuery = "SELECT m.mailinglist_id, m.shortname, m.description, m.creation_date, m.change_date FROM mailinglist_tbl m " +
			"   WHERE m.company_id = ? AND m.deleted = 0";
	
	final boolean sortAscending = AgnUtils.sortingDirectionToBoolean(direction, true);

	if(StringUtils.endsWith(sort, "_date")) {
		final String sortClause = "ORDER BY " + formatDateClause("m." + sort) + " " + (sortAscending ? "ASC" : "DESC");

		return selectPaginatedListWithSortClause(logger, selectQuery, sortClause, sort, sortAscending, page, rownums, MAILING_LIST_ENTRY_ROW_MAPPER, companyId);
	} else {
		return selectPaginatedList(logger, selectQuery, "mailinglist_tbl", sort, sortAscending, page, rownums, MAILING_LIST_ENTRY_ROW_MAPPER, companyId);
	}
}
 
Example 4
Source Project: DBus   File: GrafanaDashBoardService.java    License: Apache License 2.0 6 votes vote down vote up
public void init() throws Exception {
    if (!inited) {
        try {
            Properties properties = zkService.getProperties(Constants.COMMON_ROOT + "/" + Constants.GLOBAL_PROPERTIES);
            host = properties.getProperty(KeeperConstants.GLOBAL_CONF_KEY_GRAFANA_DBUS_URL);
            if (StringUtils.endsWith(host, "/")) {
                host = StringUtils.substringBeforeLast(host, "/");
            }
            token = properties.getProperty(KeeperConstants.GLOBAL_CONF_KEY_GRAFANA_TOKEN);
            api = "/api/dashboards/db/";
            inited = true;
        } catch (Exception e) {
            logger.error("init grafana param error", e);
            throw e;
        }
    }
}
 
Example 5
protected Map<String, String> info0(final String info) {
    final String[] attributes = info.split("\n");
    final Map<String, String> decodeInfo = Maps.newLinkedHashMap();
    for (final String attribute : attributes) {
        if (!StringUtils.isEmpty(StringUtils.trim(attribute)) && !StringUtils.startsWith(attribute, "#")) {
            final String[] keyvalue = attribute.substring(0, attribute.length() - 1).split(":");
            if (keyvalue.length == 2) {
                final String key = keyvalue[0];
                final String value = StringUtils.endsWith(keyvalue[1], "\r") ? StringUtils.substring(keyvalue[1], 0, keyvalue[1].length() - 1)
                        : keyvalue[1];
                decodeInfo.put(key, value);
            } else {
                decodeInfo.put(keyvalue[0], "");
            }
        }
    }

    return decodeInfo;
}
 
Example 6
Source Project: cuba   File: AbstractDataGridLoader.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
protected Integer loadSizeInPx(Element element, String propertyName) {
    String value = loadThemeString(element.attributeValue(propertyName));
    if (!StringUtils.isBlank(value)) {
        if (StringUtils.endsWith(value, "px")) {
            value = StringUtils.substring(value, 0, value.length() - 2);
        }
        try {
            // Only integer allowed in XML
            return Integer.parseInt(value);
        } catch (NumberFormatException e) {
            throw new GuiDevelopmentException("Property '" + propertyName + "' must contain only numeric value",
                    context, propertyName, element.attributeValue(propertyName));
        }
    }
    return null;
}
 
Example 7
Source Project: mojito   File: AndroidFilter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Should cover the main cases mention in doc:
 * https://developer.android.com/guide/topics/resources/string-resource#FormattingAndStyling
 *
 * @param sourceString
 * @return
 */
String unescape(String sourceString) {
    String unescapedSourceString;

    unescapedSourceString = sourceString.trim();

    if (StringUtils.startsWith(unescapedSourceString, "\"") && StringUtils.endsWith(unescapedSourceString, "\"")) {
        unescapedSourceString = unescapedSourceString.substring(1, unescapedSourceString.length() - 1);
    } else {
        unescapedSourceString = unescapeUtils.replaceLineFeedWithSpace(unescapedSourceString);
        unescapedSourceString = unescapeUtils.collapseSpaces(unescapedSourceString).trim();
    }

    unescapedSourceString = unescapeUtils.replaceEscapedLineFeed(unescapedSourceString);
    unescapedSourceString = unescapeUtils.replaceEscapedCarriageReturn(unescapedSourceString);
    unescapedSourceString = unescapeUtils.replaceEscapedCharacters(unescapedSourceString);

    return unescapedSourceString;
}
 
Example 8
/**
 * Helper to create the name of the ICS file we are to write
 * @param filename
 * @return
 */
private String generateFilePath(String filename) {
	StringBuilder sb = new StringBuilder();
	
	String base = sakaiProxy.getCalendarFilePath();
	sb.append(base);
	
	//add slash if reqd
	if(!StringUtils.endsWith(base, File.separator)) {
		sb.append(File.separator);
	}
	
	sb.append(filename);
	sb.append(".ics");
	return sb.toString();
}
 
Example 9
private void configureHome() {
    String path = home;
    if (StringUtils.isBlank(path)) {
        // if the root path is not specified use sakai.home/ignite/
        path = serverConfigurationService.getSakaiHomePath();
        path = path + File.separator + "ignite";
    }

    if (StringUtils.isNotBlank(node)) {
        if (!StringUtils.endsWith(path, File.separator)) {
            path = path + File.separator;
        }
        path = path + node;
    }

    File igniteHome = new File(path);
    if (!igniteHome.exists()) igniteHome.mkdirs();

    // return the absolute path
    home = igniteHome.getAbsolutePath();
}
 
Example 10
Source Project: para   File: App.java    License: Apache License 2.0 5 votes vote down vote up
final boolean isAllowed(String subjectid, String resourcePath, String httpMethod) {
	boolean allowed = false;
	if (subjectid != null && resourcePath != null && getResourcePermissions().containsKey(subjectid)) {
		httpMethod = StringUtils.upperCase(httpMethod);
		String wildcard = ALLOW_ALL;
		String exactPathToMatch = resourcePath;
		if (fromString(httpMethod) == GUEST) {
			// special case where we have wildcard permissions * but public access is not allowed
			wildcard = httpMethod;
		}
		if (StringUtils.contains(resourcePath, '/')) {
			// we assume that a full resource path is given like: 'users/something/123'
			// so we check to see if 'users/something' is in the list of resources.
			// we don't want 'users/someth' to match, but only the exact full path
			String fragment = resourcePath.substring(0, resourcePath.lastIndexOf('/'));
			for (String resource : getResourcePermissions().get(subjectid).keySet()) {
				if (StringUtils.startsWith(fragment, resource) &&
						pathMatches(subjectid, resource, httpMethod, wildcard)) {
					allowed = true;
					break;
				}
				// allow basic wildcard matching
				if (StringUtils.endsWith(resource, "/*") &&
						resourcePath.startsWith(resource.substring(0, resource.length() - 1))) {
					exactPathToMatch = resource;
					break;
				}
			}
		}
		if (!allowed && getResourcePermissions().get(subjectid).containsKey(exactPathToMatch)) {
			// check if exact resource path is accessible
			allowed = pathMatches(subjectid, exactPathToMatch, httpMethod, wildcard);
		} else if (!allowed && getResourcePermissions().get(subjectid).containsKey(ALLOW_ALL)) {
			// check if ALL resources are accessible
			allowed = pathMatches(subjectid, ALLOW_ALL, httpMethod, wildcard);
		}
	}
	return allowed;
}
 
Example 11
/**
	* {@inheritDoc}
	*/
public String getCalendarFilePath() {
	String path = serverConfigurationService.getString("calendar.ics.generation.path", System.getProperty("java.io.tmpdir"));
	//ensure trailing slash
	if(!StringUtils.endsWith(path, File.separator)) {
		path = path + File.separator;
	}
	return path;
}
 
Example 12
Source Project: gecco   File: JsonFieldRender.java    License: MIT License 5 votes vote down vote up
private String jsonp2Json(String jsonp) {
	if (jsonp == null) {
		return null;
	}
	jsonp = StringUtils.trim(jsonp);

	if(jsonp.startsWith("try")||StringUtils.endsWith(jsonp, ")")){
		if(jsonp.indexOf("catch")!=-1){
			jsonp = jsonp.substring(0,jsonp.indexOf("catch"));
		}
		int fromIndex = jsonp.indexOf('(');
		int toIndex = jsonp.lastIndexOf(')');
		if(fromIndex!=-1&&toIndex!=-1){
			jsonp = jsonp.substring(fromIndex+1,toIndex).trim();
			return jsonp;
		}
	}

	if (StringUtils.endsWith(jsonp, ";")) {
		jsonp = StringUtils.substringBeforeLast(jsonp, ";");
		jsonp = StringUtils.trim(jsonp);
	}
	/*if (StringUtils.endsWith(jsonp, ")")) {
		String jsonStr = StringUtils.substring(jsonp, "(", ")");
		jsonStr = StringUtils.trim(jsonStr);
		return jsonStr;
	}*/
	return jsonp;
}
 
Example 13
/**
 * URL encode a path
 *
 * @param input Path
 * @return URI encoded
 * @see java.net.URLEncoder#encode(String, String)
 */
public static String encode(final String input) {
    try {
        final StringBuilder b = new StringBuilder();
        final StringTokenizer t = new StringTokenizer(input, "/");
        if(!t.hasMoreTokens()) {
            return input;
        }
        if(StringUtils.startsWith(input, String.valueOf(Path.DELIMITER))) {
            b.append(Path.DELIMITER);
        }
        while(t.hasMoreTokens()) {
            b.append(URLEncoder.encode(t.nextToken(), StandardCharsets.UTF_8.name()));
            if(t.hasMoreTokens()) {
                b.append(Path.DELIMITER);
            }
        }
        if(StringUtils.endsWith(input, String.valueOf(Path.DELIMITER))) {
            b.append(Path.DELIMITER);
        }
        // Because URLEncoder uses <code>application/x-www-form-urlencoded</code> we have to replace these
        // for proper URI percented encoding.
        return StringUtils.replaceEach(b.toString(),
            new String[]{"+", "*", "%7E", "%40"},
            new String[]{"%20", "%2A", "~", "@"});
    }
    catch(UnsupportedEncodingException e) {
        log.warn(String.format("Failure %s encoding input %s", e, input));
        return input;
    }
}
 
Example 14
Source Project: DBus   File: ProjectTopologyService.java    License: Apache License 2.0 5 votes vote down vote up
private ResultEntity start(Map<String, Object> param, Session session, SimpMessagingTemplate smt) throws Exception {
    if (session != null) session.getBasicRemote().sendText("请稍等,启动中...");
    if (smt != null) smt.convertAndSendToUser((String) param.get("uid"), "/log", "请稍等,启动中...");
    String topologyName = (String) param.get("topoName");
    String projectName = (String) param.get("projectName");
    String jarFilePath = (String) param.get("jarPath");
    String alias = (String) param.get("alias");

    Properties props = zkService.getProperties(Constants.COMMON_ROOT + "/" + Constants.GLOBAL_PROPERTIES);
    String stormHomePath = props.getProperty(KeeperConstants.GLOBAL_CONF_KEY_STORM_NIMBUS_HOME_PATH);
    if (StringUtils.endsWith(stormHomePath, "/"))
        stormHomePath = StringUtils.substringBeforeLast(stormHomePath, "/");

    String routerJarsBasePath = props.getProperty(KeeperConstants.GLOBAL_CONF_KEY_JARS_PATH);
    if (StringUtils.endsWith(routerJarsBasePath, "/")) {
        routerJarsBasePath = StringUtils.substringBeforeLast(routerJarsBasePath, "/");
    }

    String zkUrl = props.getProperty(KeeperConstants.GLOBAL_CONF_KEY_ZK_STR);
    String user = props.getProperty(KeeperConstants.GLOBAL_CONF_KEY_CLUSTER_SERVER_SSH_USER);
    String stormNimbusHost = props.getProperty(KeeperConstants.GLOBAL_CONF_KEY_STORM_NIMBUS_HOST);
    String port = props.getProperty(KeeperConstants.GLOBAL_CONF_KEY_CLUSTER_SERVER_SSH_PORT);

    // 0:routerJarsBasePath, 1:stormHomePath, 2:zk url, 3: topologyName, 4:jar path
    // 5:user name, 6:nimbus host, 7:ssh port, 8:project name, 9: alias
    String cmd = MessageFormat.format("ssh -p {7} {5}@{6} {0}/dbus_startTopology.sh {1} router {2} {3} {4} {8} {9}",
            routerJarsBasePath, stormHomePath, zkUrl, topologyName, jarFilePath, user, stormNimbusHost, port, projectName, alias);
    logger.info("start topology command: {}", cmd);

    Map<String, Object> retMap = execCmd(cmd, session, true, smt, (String) param.get("uid"));
    logger.info("start topology return code: {}, param: {}", retMap.get("code"), JSON.toJSONString(param));
    if ((Integer) retMap.get("code") == 0) {
        ProjectTopology record = new ProjectTopology();
        record.setId((Integer) param.get("id"));
        record.setStatus("running");
        update(record, true);
    }
    return new ResultEntity(ResultEntity.SUCCESS, (String) retMap.get("msg"));
}
 
Example 15
Source Project: DBus   File: AckWindows.java    License: Apache License 2.0 5 votes vote down vote up
public void fail(Ack ackVo) {
    logger.debug("topic:{}, partaiton:{}, offset:{}, trigger fail.", ackVo.getTopic(), ackVo.getPartition(), ackVo.getOffset());
    if (StringUtils.endsWith(ackVo.getTopic(), "_ctrl"))
        ackBooks.get(obtainKey(ackVo)).get(ackVo.getOffset()).setStatus(Ack.OK);
    else doAckOrFail(ackVo, Ack.FAIL);
    flush();
}
 
Example 16
Source Project: iyzipay-java   File: RequestFormatter.java    License: MIT License 5 votes vote down vote up
public static String formatPrice(BigDecimal price) {
    String formattedPrice = price.toString();
    if (!StringUtils.contains(formattedPrice, DOT)) {
        return formattedPrice + ".0";
    }
    formattedPrice = StringUtils.stripEnd(formattedPrice, ZERO);
    if (StringUtils.endsWith(formattedPrice, DOT)) {
        return formattedPrice + ZERO;
    }
    return formattedPrice;
}
 
Example 17
Source Project: supplierShop   File: ReflectUtils.java    License: 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 Project: jakduk-api   File: JakdukUtils.java    License: MIT License 4 votes vote down vote up
/**
 * 임시 이메일 주소인지 확인한다.
 */
public static Boolean isTempararyEmail(String email) {
    return StringUtils.endsWith(email, "@jakduk.com");
}
 
Example 19
Source Project: jinjava   File: MacroTag.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public String interpret(TagNode tagNode, JinjavaInterpreter interpreter) {
  Matcher matcher = MACRO_PATTERN.matcher(tagNode.getHelpers());
  if (!matcher.find()) {
    throw new TemplateSyntaxException(
      tagNode.getMaster().getImage(),
      "Unable to parse macro definition: " + tagNode.getHelpers(),
      tagNode.getLineNumber(),
      tagNode.getStartPosition()
    );
  }

  String name = matcher.group(1);
  String args = Strings.nullToEmpty(matcher.group(2));

  LinkedHashMap<String, Object> argNamesWithDefaults = new LinkedHashMap<>();

  List<String> argList = Lists.newArrayList(ARGS_SPLITTER.split(args));
  boolean deferred = false;
  for (int i = 0; i < argList.size(); i++) {
    String arg = argList.get(i);

    if (arg.contains("=")) {
      String argName = StringUtils.substringBefore(arg, "=").trim();
      StringBuilder argValStr = new StringBuilder(
        StringUtils.substringAfter(arg, "=").trim()
      );

      if (
        StringUtils.startsWith(argValStr, "[") && !StringUtils.endsWith(argValStr, "]")
      ) {
        while (i + 1 < argList.size() && !StringUtils.endsWith(argValStr, "]")) {
          argValStr.append(", ").append(argList.get(i + 1));
          i++;
        }
      }

      try {
        Object argVal = interpreter.resolveELExpression(
          argValStr.toString(),
          tagNode.getLineNumber()
        );
        argNamesWithDefaults.put(argName, argVal);
      } catch (DeferredValueException e) {
        deferred = true;
      }
    } else {
      argNamesWithDefaults.put(arg, null);
    }
  }

  MacroFunction macro = new MacroFunction(
    tagNode.getChildren(),
    name,
    argNamesWithDefaults,
    false,
    interpreter.getContext(),
    interpreter.getLineNumber(),
    interpreter.getPosition()
  );
  macro.setDeferred(deferred);

  interpreter.getContext().addGlobalMacro(macro);

  if (deferred) {
    throw new DeferredValueException(
      name,
      tagNode.getLineNumber(),
      tagNode.getStartPosition()
    );
  }

  return "";
}
 
Example 20
Source Project: data-prep   File: MoveDatasetContent.java    License: Apache License 2.0 4 votes vote down vote up
@Value("${content-service.store.local.path}")
public void setTmp(String basePath) {
    this.tmp = StringUtils.endsWith(basePath, "/") ? basePath + "store/datasets/tmp"
            : basePath + "/store/datasets/tmp";
}