Example usage for org.apache.commons.lang3 StringUtils strip

List of usage examples for org.apache.commons.lang3 StringUtils strip

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils strip.

Prototype

public static String strip(String str, final String stripChars) 

Source Link

Document

Strips any of a set of characters from the start and end of a String.

Usage

From source file:jp.mathes.databaseWiki.dav.DavServlet.java

@Override
public Resource getResource(final String host, final String path) {
    DbwConfiguration.getInstance()/*from  w w  w  .ja va  2 s.  co  m*/
            .davLog(String.format("Entering getResource for host '%s' and path '%s'.", host, path));
    String realPath = path.replace(this.cutoffPath, "");
    realPath = StringUtils.strip(realPath, "/");
    String[] realPathSplit = StringUtils.split(realPath, "/");
    if (realPathSplit.length == 1) {
        return new DbResource(realPathSplit[0]);
    } else if (realPathSplit.length == 2) {
        return new TableResource(realPathSplit[0], realPathSplit[1]);
    } else if (realPathSplit.length == 3) {
        return new DocumentResource(realPathSplit[0], realPathSplit[1], realPathSplit[2]);
    } else {
        throw new RuntimeException(String.format("Invalid path '%s'", path));
    }
}

From source file:io.stallion.utils.Encrypter.java

private static String doDecryptString(String password, String encryptedBase32) throws Exception {
    encryptedBase32 = StringUtils.strip(encryptedBase32, "=");
    String salt = encryptedBase32.substring(0, 16);
    String ivString = encryptedBase32.substring(16, 48);
    byte[] iv = new byte[0];
    try {// w  w w.j a v  a2s  .c o m
        iv = Hex.decodeHex(ivString.toCharArray());
    } catch (DecoderException e) {
        throw new RuntimeException(e);
    }
    encryptedBase32 = encryptedBase32.substring(48);
    Base32 decoder = new Base32();
    byte[] encrypted = decoder.decode(encryptedBase32.toUpperCase());
    SecretKeySpec skeySpec = makeKeySpec(password, salt);

    /*
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec,
            new IvParameterSpec(iv));
      */
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv));

    byte[] original = cipher.doFinal(encrypted);
    return new String(original, Charset.forName("UTF-8"));

}

From source file:com.nhncorp.lucy.security.xss.listener.SecurityUtils.java

/**
 * @param element//from  w  w  w . jav a2 s . c  om
 * @param srcUrl
 * @param isWhiteUrl
 * @return
 */
public static boolean checkVulnerableWithHttp(Element element, String srcUrl, boolean isWhiteUrl,
        ContentTypeCacheRepo contentTypeCacheRepo) {
    boolean isVulnerable = false;

    // embed/object   ? (XSSFILTERSUS-109)
    if (isWhiteUrl) {

    } else {
        String type = element.getAttributeValue("type").trim();
        type = StringUtils.strip(type, "'\"");

        if (type != null && !"".equals(type)) {

            //? type ??
            if (!(isAllowedType(type) || props.values().contains(type))) {
                isVulnerable = true;
            }
        } else {
            //? ?
            String url = StringUtils.strip(srcUrl, "'\"");
            String extension = getExtension(url);

            if (StringUtils.containsAny(extension, specialCharArray)) {
                int pos = StringUtils.indexOfAny(extension, specialCharArray);
                if (pos != -1) {
                    extension = StringUtils.substring(extension, 0, pos);
                }
            }

            if (StringUtils.isEmpty(extension)) {
                // ?  MIME TYPE ? ?  ,  url ? head HTTP Method  ? content-type ?
                type = getContentTypeFromUrlConnection(url, contentTypeCacheRepo);

                //? type ??
                if (!isAllowedType(type)) {
                    isVulnerable = true;
                } else {
                    element.putAttribute("type", "\"" + type + "\"");
                }

            } else {
                type = getTypeFromExtension(extension);

                if (StringUtils.isEmpty(type)) {
                    type = props.getProperty(extension);

                    if (type != null) {
                        type = type.trim();
                    }
                }

                //? type ??
                if (StringUtils.isEmpty(type)) {
                    isVulnerable = true;
                } else {
                    element.putAttribute("type", "\"" + type + "\"");
                }
            }

        }
    }
    return isVulnerable;
}

From source file:com.quartercode.femtoweb.impl.DefaultContext.java

private String preparePath(String path) {

    return "/" + StringUtils.strip(path, "/");
}

From source file:net.dataforte.commons.resources.ClassUtils.java

private static String joinParts(String separator, String... paths) {
    Vector<String> trimmed = new Vector<String>();
    int pos = 0;/*from ww  w  . j  ava2 s .c  o  m*/
    int last = paths.length - 1;
    for (String path : paths) {
        String trimmedPath;
        if (pos == 0)
            trimmedPath = StringUtils.stripEnd(path, separator);
        else if (pos == last)
            trimmedPath = StringUtils.stripStart(path, separator);
        else
            trimmedPath = StringUtils.strip(path, separator);
        trimmed.add(trimmedPath);
        pos += 1;
    }
    String joined = String.join(separator, trimmed);
    return joined;
}

From source file:ca.phon.ipadictionary.impl.DatabaseDictionary.java

@Override
public String[] lookup(String ortho) throws IPADictionaryExecption {
    Connection conn = IPADatabaseManager.getInstance().getConnection();
    List<String> retVal = new ArrayList<String>();

    if (conn != null) {
        ortho = StringUtils.strip(ortho, "?!\"'.\\/@&$()^%#*");
        String qSt = "SELECT * FROM transcript WHERE orthography = ? AND langId = ?";
        try {//from w  ww  .j  a v  a 2  s .co m
            PreparedStatement pSt = conn.prepareStatement(qSt);
            pSt.setString(1, ortho.toLowerCase());
            pSt.setString(2, getLanguage().toString());

            java.sql.ResultSet rs = pSt.executeQuery();
            while (rs.next()) {
                retVal.add(rs.getString("IPA"));
            }
            rs.close();
            pSt.close();
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }

    return retVal.toArray(new String[0]);
}

From source file:com.quartercode.femtoweb.impl.DefaultContext.java

@Override
public Class<? extends Action> getAction(String uri) throws ActionNotFoundException {

    // By doing this, you are no longer able to flood the cache by requesting the same action with different amounts of repeated "/" at the end
    String effectiveUri = "/" + StringUtils.strip(uri, "/");

    if (!urisToActions.containsKey(effectiveUri)) {
        insertActionUriPair(ActionUriResolver.getAction(actionBasePackage, effectiveUri), effectiveUri);
    }/*from   w ww  .j a v a2s .  c  o m*/

    return urisToActions.get(effectiveUri);
}

From source file:com.versatus.jwebshield.filter.SecurityFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Assume its HTTP
    HttpServletRequest httpReq = (HttpServletRequest) request;

    String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL="
            + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr();

    logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr());
    logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo());
    logger.debug("doFilter: queryString=" + httpReq.getQueryString());
    logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString());
    logger.debug("doFilter: method=" + httpReq.getMethod());
    logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin"));
    logger.info("doFilter: Referer=" + httpReq.getHeader("Referer"));
    logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName));

    UrlExclusionList exclList = (UrlExclusionList) request.getServletContext()
            .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME);
    HttpSession session = httpReq.getSession(false);
    if (session == null) {
        chain.doFilter(request, response);
        return;/*from   w ww .j a va2  s  .c o  m*/
    }

    logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list "
            + exclList.getExclusionMap());

    try {
        if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
    } catch (Exception e) {
        logger.error("doFilter", e);
    }
    // check CSRF cookie/header
    boolean csrfHeaderPassed = false;
    String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName);
    if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) {
        String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\"");
        logger.debug("doFilter: csrfHeader after decoding" + csrfHeader);
        Cookie[] cookies = httpReq.getCookies();
        for (Cookie c : cookies) {
            String name = c.getName();

            if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) {

                logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value="
                        + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly="
                        + c.isHttpOnly());

                logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue()));

                if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) {

                    csrfHeaderPassed = true;
                    logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName);
                    break;
                } else {
                    logger.info(
                            "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName);
                }
            }

        }
        // String csrfCookieVal = (String) session
        // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM);
        // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) {
        // // chain.doFilter(request, response);
        // // return;
        // csrfHeaderPassed = true;
        // } else {
        // // logger.info(reqInfo);
        // // sendSecurityReject(response);
        // }
    }

    if (useCsrfToken && csrfHeaderPassed) {
        chain.doFilter(request, response);
        return;
    }

    // Validate that the salt is in the cache
    Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq
            .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME);

    if (csrfPreventionSaltCache != null) {
        // Get the salt sent with the request
        String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME);

        logger.debug("doFilter: csrf saltName=" + saltName);

        if (saltName != null) {

            String salt = httpReq.getParameter(saltName);

            logger.debug("doFilter: csrf salt=" + salt);

            if (salt != null) {

                SecurityInfo si = new SecurityInfo(saltName, salt);

                logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si));

                SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si);
                if (cachedSi != null) {
                    // csrfPreventionSaltCache.invalidate(si);
                    if (SecurityTokenFilter.checkReferer) {
                        String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer"));
                        logger.debug("doFilter: refHeader=" + refHeader);
                        if (StringUtils.isNotBlank(refHeader)) {
                            try {
                                URL refUrl = new URL(refHeader);
                                refHeader = refUrl.getHost();
                            } catch (MalformedURLException mex) {
                                logger.debug("doFilter: parsing referer header failed", mex);
                            }
                        }
                        if (!cachedSi.getRefererHost().isEmpty()
                                && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) {
                            logger.info("Potential CSRF detected - Referer host does not match orignal! "
                                    + refHeader + " != " + cachedSi.getRefererHost());
                            sendSecurityReject(response);
                        }
                    }

                    chain.doFilter(request, response);
                } else {
                    logger.info(reqInfo);
                    sendSecurityReject(response);
                }
            } else if (httpMethodMatch(httpReq.getMethod())) {
                // let flow through
                chain.doFilter(request, response);
            } else {
                logger.info(reqInfo);
                sendSecurityReject(response);
            }
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:com.sonymobile.jenkins.plugins.mq.mqnotifier.MQNotifierConfig.java

/**
 * Sets URI for MQ server.//  w w w . j  av a2 s . co  m
 *
 * @param serverUri the URI.
 */
public void setServerUri(final String serverUri) {
    this.serverUri = StringUtils.strip(StringUtils.stripToNull(serverUri), "/");
}

From source file:forge.card.BoosterGenerator.java

@SuppressWarnings("unchecked")
public static PrintSheet makeSheet(String sheetKey, Iterable<PaperCard> src) {

    PrintSheet ps = new PrintSheet(sheetKey);
    String[] sKey = TextUtil.splitWithParenthesis(sheetKey, ' ', 2);
    Predicate<PaperCard> setPred = (Predicate<PaperCard>) (sKey.length > 1
            ? IPaperCard.Predicates.printedInSets(sKey[1].split(" "))
            : Predicates.alwaysTrue());// w ww.j av a  2  s.c o m

    List<String> operators = new LinkedList<>(Arrays.asList(TextUtil.splitWithParenthesis(sKey[0], ':')));
    Predicate<PaperCard> extraPred = buildExtraPredicate(operators);

    // source replacement operators - if one is applied setPredicate will be ignored
    Iterator<String> itMod = operators.iterator();
    while (itMod.hasNext()) {

        String mainCode = itMod.next();

        if (mainCode.regionMatches(true, 0, "fromSheet", 0, 9)) { // custom print sheet

            String sheetName = StringUtils.strip(mainCode.substring(9), "()\" ");
            src = StaticData.instance().getPrintSheets().get(sheetName).toFlatList();
            setPred = Predicates.alwaysTrue();

        } else if (mainCode.startsWith("promo")) { // get exactly the named cards, that's a tiny inlined print sheet

            String list = StringUtils.strip(mainCode.substring(5), "() ");
            String[] cardNames = TextUtil.splitWithParenthesis(list, ',', '"', '"');
            List<PaperCard> srcList = new ArrayList<>();

            for (String cardName : cardNames) {
                srcList.add(StaticData.instance().getCommonCards().getCard(cardName));
            }

            src = srcList;
            setPred = Predicates.alwaysTrue();

        } else {
            continue;
        }

        itMod.remove();

    }

    // only special operators should remain by now - the ones that could not be turned into one predicate
    String mainCode = operators.isEmpty() ? null : operators.get(0).trim();

    if (null == mainCode || mainCode.equalsIgnoreCase(BoosterSlots.ANY)) { // no restriction on rarity

        Predicate<PaperCard> predicate = Predicates.and(setPred, extraPred);
        ps.addAll(Iterables.filter(src, predicate));

    } else if (mainCode.equalsIgnoreCase(BoosterSlots.UNCOMMON_RARE)) { // for sets like ARN, where U1 cards are considered rare and U3 are uncommon

        Predicate<PaperCard> predicateRares = Predicates.and(setPred, IPaperCard.Predicates.Presets.IS_RARE,
                extraPred);
        ps.addAll(Iterables.filter(src, predicateRares));

        Predicate<PaperCard> predicateUncommon = Predicates.and(setPred,
                IPaperCard.Predicates.Presets.IS_UNCOMMON, extraPred);
        ps.addAll(Iterables.filter(src, predicateUncommon), 3);

    } else if (mainCode.equalsIgnoreCase(BoosterSlots.RARE_MYTHIC)) {
        // Typical ratio of rares to mythics is 53:15, changing to 35:10 in smaller sets.
        // To achieve the desired 1:8 are all mythics are added once, and all rares added twice per print sheet.

        Predicate<PaperCard> predicateMythic = Predicates.and(setPred,
                IPaperCard.Predicates.Presets.IS_MYTHIC_RARE, extraPred);
        ps.addAll(Iterables.filter(src, predicateMythic));

        Predicate<PaperCard> predicateRare = Predicates.and(setPred, IPaperCard.Predicates.Presets.IS_RARE,
                extraPred);
        ps.addAll(Iterables.filter(src, predicateRare), 2);

    } else {
        throw new IllegalArgumentException("Booster generator: operator could not be parsed - " + mainCode);
    }

    return ps;

}