Example usage for org.apache.commons.lang StringUtils startsWithIgnoreCase

List of usage examples for org.apache.commons.lang StringUtils startsWithIgnoreCase

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils startsWithIgnoreCase.

Prototype

public static boolean startsWithIgnoreCase(String str, String prefix) 

Source Link

Document

Case insensitive check if a String starts with a specified prefix.

Usage

From source file:org.apereo.lap.services.input.csv.BaseCSVInputHandler.java

/**
 * Reads a CSV file and verifies basic infor about it
 * @param minColumns min number of columns
 * @param headerStartsWith expected header value
 * @param reRead force reading the file again (otherwise it will use the existing copy)
 * @return the CSVReader//from   w  w  w .jav  a2 s.com
 * @throws IllegalStateException if we fail to produce the reader
 */
CSVReader readCSV(int minColumns, String headerStartsWith, boolean reRead, File file) {
    if (this.reader == null || reRead) {
        assert StringUtils.isNotBlank(file.getAbsolutePath()) : "filePath must not be blank: "
                + file.getAbsolutePath();
        assert minColumns > 0 : "minColumns must be > 0: " + minColumns;
        assert StringUtils.isNotBlank(headerStartsWith) : "headerStartsWith must not be blank: "
                + file.getAbsolutePath();
        CSVReader fileCSV;
        try {
            InputStream fileCSV_IS = FileUtils.openInputStream(file);
            fileCSV = new CSVReader(new InputStreamReader(fileCSV_IS));
            String[] check = fileCSV.readNext();
            if (check != null && check.length >= minColumns
                    && StringUtils.startsWithIgnoreCase(headerStartsWith, StringUtils.trimToEmpty(check[0]))) {
                //logger.debug(fileName+" file and header appear valid");
                this.reader = fileCSV;
            } else {
                throw new IllegalStateException(
                        file.getAbsolutePath() + " file and header do not appear valid (no " + headerStartsWith
                                + " header or less than " + minColumns + " required columns");
            }
        } catch (Exception e) {
            throw new IllegalStateException(file.getAbsolutePath() + " CSV is invalid: " + e);
        }
    }
    return this.reader;
}

From source file:org.apereo.lap.services.input.handlers.csv.BaseCSVInputHandler.java

/**
 * Reads a CSV file and verifies basic infor about it
 * @param minColumns min number of columns
 * @param headerStartsWith expected header value
 * @param reRead force reading the file again (otherwise it will use the existing copy)
 * @return the CSVReader/*from  w w w .j av  a  2  s .co  m*/
 * @throws IllegalStateException if we fail to produce the reader
 */
CSVReader readCSVResource(int minColumns, String headerStartsWith, boolean reRead) {
    if (this.reader == null || reRead) {
        assert minColumns > 0 : "minColumns must be > 0: " + minColumns;
        assert StringUtils.isNotBlank(headerStartsWith) : "headerStartsWith must not be blank: " + getPath();
        CSVReader fileCSV;
        try {
            Path csvPath = config.getApplicationHomeDirectory().resolve(Paths.get(getPath()));
            InputStream fileCSV_IS = Files.newInputStream(csvPath);
            fileCSV = new CSVReader(new InputStreamReader(fileCSV_IS));
            String[] check = fileCSV.readNext();
            if (check != null && check.length >= minColumns
                    && StringUtils.startsWithIgnoreCase(headerStartsWith, StringUtils.trimToEmpty(check[0]))) {
                //logger.debug(fileName+" file and header appear valid");
                this.reader = fileCSV;
            } else {
                throw new IllegalStateException(getPath() + " file and header do not appear valid (no "
                        + headerStartsWith + " header or less than " + minColumns + " required columns");
            }
        } catch (Exception e) {
            throw new IllegalStateException(getPath() + " CSV is invalid: " + e);
        }
    }
    return this.reader;
}

From source file:org.artifactory.maven.PomTargetPathValidator.java

public void validate(InputStream in, boolean suppressPomConsistencyChecks) throws IOException {
    MavenXpp3Reader reader = new MavenXpp3Reader();
    try {/*from  ww w  . jav  a2s  .  c o  m*/
        model = reader.read(new InputStreamReader(in, MavenModelUtils.UTF8));

        String groupId = getGroupId(model);

        if (StringUtils.isNotBlank(groupId)) {
            //Do not verify if the pom's groupid does not exist
            String modelVersion = getModelVersion(model);
            if (StringUtils.isBlank(modelVersion)) {
                String msg = String.format(
                        "The Pom version of '%s' does not exists. Please verify your POM content for correctness",
                        relPath);
                if (suppressPomConsistencyChecks) {
                    log.error("{} POM consistency checks are suppressed. Broken artifacts might have been "
                            + "stored in the repository - please resolve this manually.", msg);
                    return;
                } else {
                    throw new BadPomException(msg);
                }
            }

            //For snapshots with unique snapshot version, do not include the model version in the path
            boolean snapshot = moduleInfo.isIntegration();
            boolean versionSnapshot = MavenNaming.isNonUniqueSnapshotVersion(modelVersion);

            String pathPrefix = null;
            if (snapshot && !versionSnapshot) {
                pathPrefix = groupId.replace('.', '/') + "/" + model.getArtifactId() + "/";
            } else if (StringUtils.isNotBlank(modelVersion)) {
                pathPrefix = groupId.replace('.', '/') + "/" + model.getArtifactId() + "/" + modelVersion;
            }

            //Do not validate paths that contain property references
            if (pathPrefix != null && !pathPrefix.contains("${")
                    && !StringUtils.startsWithIgnoreCase(relPath, pathPrefix)) {
                String msg = String
                        .format("The target deployment path '%s' does not match the POM's expected path "
                                + "prefix '%s'. Please verify your POM content for correctness and make sure the source path "
                                + "is a valid Maven repository root path.", relPath, pathPrefix);
                if (suppressPomConsistencyChecks) {
                    log.warn("{} POM consistency checks are suppressed. Broken artifacts might have been "
                            + "stored in the repository - please resolve this manually.", msg);
                } else {
                    throw new BadPomException(msg);
                }
            }
        }
    } catch (XmlPullParserException e) {
        if (log.isDebugEnabled()) {
            try {
                in.reset();
                InputStreamReader isr = new InputStreamReader(in, MavenModelUtils.UTF8);
                String s = readString(isr);
                log.debug("Could not parse bad POM for '{}'. Bad POM content:\n{}\n", relPath, s);
            } catch (Exception ex) {
                log.trace("Could not extract bad POM content for '{}': {}.", relPath, e.getMessage());
            }
        }
        String message = "Failed to read POM for '" + relPath + "': " + e.getMessage() + ".";
        if (suppressPomConsistencyChecks) {
            log.error(message + " POM consistency checks are suppressed. Broken artifacts might have been "
                    + "stored in the repository - please resolve this manually.");
        } else {
            throw new BadPomException(message);
        }
    }
}

From source file:org.artifactory.webapp.wicket.page.build.tabs.BuildEnvironmentTabPanel.java

private List<SerializablePair<String, String>> filterEnvProperties(
        List<SerializablePair<String, String>> propertyPairs) {
    return Lists/*from   ww  w.jav a  2s .c om*/
            .newArrayList(Iterables.filter(propertyPairs, new Predicate<SerializablePair<String, String>>() {
                @Override
                public boolean apply(@Nullable SerializablePair<String, String> input) {
                    return input != null
                            && StringUtils.startsWithIgnoreCase(input.getFirst(), "buildInfo.env.");
                }
            }));
}

From source file:org.artifactory.webapp.wicket.page.build.tabs.BuildEnvironmentTabPanel.java

private List<SerializablePair<String, String>> filterSystemProperties(
        List<SerializablePair<String, String>> propertyPairs) {
    return Lists/*from www  .jav a  2  s  .  c  o m*/
            .newArrayList(Iterables.filter(propertyPairs, new Predicate<SerializablePair<String, String>>() {
                @Override
                public boolean apply(@Nullable SerializablePair<String, String> input) {
                    return input != null
                            && !StringUtils.startsWithIgnoreCase(input.getFirst(), "buildInfo.env.");
                }
            }));
}

From source file:org.awesomeagile.testing.google.FakeGoogleController.java

private void validateAuthorization(String authorizationHeader) {
    if (StringUtils.startsWithIgnoreCase(authorizationHeader, BEARER)) {
        if (knownTokens.contains(StringUtils.removeStartIgnoreCase(authorizationHeader, BEARER).trim())) {
            return;
        }/*from   w  ww .  j a  va  2 s .co  m*/
    }
    throw new BadCredentialsException("Invalid authorization header: " + authorizationHeader);
}

From source file:org.b3log.solo.service.PreferenceMgmtService.java

/**
 * Updates the preference with the specified preference.
 *
 * @param preference the specified preference
 * @throws ServiceException service exception
 *///  ww w.  ja  v  a 2s  . co  m
public void updatePreference(final JSONObject preference) throws ServiceException {
    @SuppressWarnings("unchecked")
    final Iterator<String> keys = preference.keys();
    while (keys.hasNext()) {
        final String key = keys.next();
        if (preference.isNull(key)) {
            throw new ServiceException("A value is null of preference[key=" + key + "]");
        }
    }

    // TODO: checks preference 

    final Transaction transaction = preferenceRepository.beginTransaction();
    try {
        String blogHost = preference.getString(BLOG_HOST).toLowerCase().trim();
        if (StringUtils.startsWithIgnoreCase(blogHost, "http://")) {
            blogHost = blogHost.substring("http://".length());
        }
        if (blogHost.endsWith("/")) {
            blogHost = blogHost.substring(0, blogHost.length() - 1);
        }

        LOGGER.log(Level.FINER, "Blog Host[{0}]", blogHost);
        preference.put(BLOG_HOST, blogHost);

        final String skinDirName = preference.getString(Skin.SKIN_DIR_NAME);
        final String skinName = Skins.getSkinName(skinDirName);
        preference.put(Skin.SKIN_NAME, skinName);
        final Set<String> skinDirNames = Skins.getSkinDirNames();
        final JSONArray skinArray = new JSONArray();
        for (final String dirName : skinDirNames) {
            final JSONObject skin = new JSONObject();
            skinArray.put(skin);

            final String name = Skins.getSkinName(dirName);
            skin.put(Skin.SKIN_NAME, name);
            skin.put(Skin.SKIN_DIR_NAME, dirName);
        }
        final String webRootPath = SoloServletListener.getWebRoot();
        final String skinPath = webRootPath + Skin.SKINS + "/" + skinDirName;
        LOGGER.log(Level.FINER, "Skin path[{0}]", skinPath);
        Templates.CACHE.clear();

        preference.put(Skin.SKINS, skinArray.toString());

        final String timeZoneId = preference.getString(TIME_ZONE_ID);
        TimeZones.setTimeZone(timeZoneId);

        preference.put(Preference.SIGNS, preference.get(Preference.SIGNS).toString());

        final JSONObject oldPreference = preferenceQueryService.getPreference();
        final String adminEmail = oldPreference.getString(ADMIN_EMAIL);
        preference.put(ADMIN_EMAIL, adminEmail);

        if (!preference.has(PAGE_CACHE_ENABLED)) {
            preference.put(PAGE_CACHE_ENABLED, oldPreference.getBoolean(PAGE_CACHE_ENABLED));
        } else {
            if (RuntimeEnv.BAE == Latkes.getRuntimeEnv()) {
                // XXX: Ignores user's setting, uses default
                // https://github.com/b3log/b3log-solo/issues/73
                preference.put(PAGE_CACHE_ENABLED, Default.DEFAULT_PAGE_CACHE_ENABLED);
            }
        }

        final boolean pageCacheEnabled = preference.getBoolean(Preference.PAGE_CACHE_ENABLED);
        Templates.enableCache(pageCacheEnabled);

        final String version = oldPreference.optString(VERSION);
        if (!Strings.isEmptyOrNull(version)) {
            preference.put(VERSION, version);
        }

        final String localeString = preference.getString(Preference.LOCALE_STRING);
        LOGGER.log(Level.FINER, "Current locale[string={0}]", localeString);
        Latkes.setLocale(new Locale(Locales.getLanguage(localeString), Locales.getCountry(localeString)));

        preferenceRepository.update(Preference.PREFERENCE, preference);

        transaction.commit();

        Templates.MAIN_CFG.setDirectoryForTemplateLoading(new File(skinPath));

        if (preference.getBoolean(PAGE_CACHE_ENABLED)) {
            Latkes.enablePageCache();
        } else {
            Latkes.disablePageCache();
        }
    } catch (final JSONException e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        LOGGER.log(Level.SEVERE, "Updates preference failed", e);
        throw new ServiceException(langPropsService.get("updateFailLabel"));
    } catch (final RepositoryException e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        LOGGER.log(Level.SEVERE, "Updates preference failed", e);
        throw new ServiceException(langPropsService.get("updateFailLabel"));
    } catch (final IOException e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        LOGGER.log(Level.SEVERE, "Updates preference failed", e);
        throw new ServiceException(langPropsService.get("updateFailLabel"));
    }

    LOGGER.log(Level.FINER, "Updates preference successfully");
}

From source file:org.b3log.symphony.util.Markdowns.java

/**
 * Gets the safe HTML content of the specified content.
 *
 * @param content the specified content/*from   w  w w . ja  va2s  .  co  m*/
 * @param baseURI the specified base URI, the relative path value of href will starts with this URL
 * @return safe HTML content
 */
public static String clean(final String content, final String baseURI) {
    final Document.OutputSettings outputSettings = new Document.OutputSettings();
    outputSettings.prettyPrint(false);

    final String tmp = Jsoup.clean(content, baseURI,
            Whitelist.relaxed().addAttributes(":all", "id", "target", "class")
                    .addTags("span", "hr", "kbd", "samp", "tt", "del", "s", "strike", "u")
                    .addAttributes("iframe", "src", "width", "height", "border", "marginwidth", "marginheight")
                    .addAttributes("audio", "controls", "src")
                    .addAttributes("video", "controls", "src", "width", "height")
                    .addAttributes("source", "src", "media", "type")
                    .addAttributes("object", "width", "height", "data", "type")
                    .addAttributes("param", "name", "value")
                    .addAttributes("input", "type", "disabled", "checked").addAttributes("embed", "src", "type",
                            "width", "height", "wmode", "allowNetworking"),
            outputSettings);
    final Document doc = Jsoup.parse(tmp, baseURI, Parser.htmlParser());

    final Elements ps = doc.getElementsByTag("p");
    for (final Element p : ps) {
        p.removeAttr("style");
    }

    final Elements iframes = doc.getElementsByTag("iframe");
    for (final Element iframe : iframes) {
        final String src = StringUtils.deleteWhitespace(iframe.attr("src"));
        if (StringUtils.startsWithIgnoreCase(src, "javascript")
                || StringUtils.startsWithIgnoreCase(src, "data:")) {
            iframe.remove();
        }
    }

    final Elements objs = doc.getElementsByTag("object");
    for (final Element obj : objs) {
        final String data = StringUtils.deleteWhitespace(obj.attr("data"));
        if (StringUtils.startsWithIgnoreCase(data, "data:")
                || StringUtils.startsWithIgnoreCase(data, "javascript")) {
            obj.remove();

            continue;
        }

        final String type = StringUtils.deleteWhitespace(obj.attr("type"));
        if (StringUtils.containsIgnoreCase(type, "script")) {
            obj.remove();
        }
    }

    final Elements embeds = doc.getElementsByTag("embed");
    for (final Element embed : embeds) {
        final String data = StringUtils.deleteWhitespace(embed.attr("src"));
        if (StringUtils.startsWithIgnoreCase(data, "data:")
                || StringUtils.startsWithIgnoreCase(data, "javascript")) {
            embed.remove();

            continue;
        }
    }

    final Elements as = doc.getElementsByTag("a");
    for (final Element a : as) {
        a.attr("rel", "nofollow");

        final String href = a.attr("href");
        if (href.startsWith(Latkes.getServePath())) {
            continue;
        }

        a.attr("target", "_blank");
    }

    final Elements audios = doc.getElementsByTag("audio");
    for (final Element audio : audios) {
        audio.attr("preload", "none");
    }

    final Elements videos = doc.getElementsByTag("video");
    for (final Element video : videos) {
        video.attr("preload", "none");
    }

    String ret = doc.body().html();
    ret = ret.replaceAll("(</?br\\s*/?>\\s*)+", "<br>"); // patch for Jsoup issue

    return ret;
}

From source file:org.b3log.symphony.util.Markdowns.java

/**
 * Converts the specified markdown text to HTML.
 *
 * @param markdownText the specified markdown text
 * @return converted HTML, returns an empty string "" if the specified markdown text is "" or {@code null}, returns
 * 'markdownErrorLabel' if exception/*from   www.j  av a  2 s  . c om*/
 */
public static String toHTML(final String markdownText) {
    if (Strings.isEmptyOrNull(markdownText)) {
        return "";
    }

    final String cachedHTML = getHTML(markdownText);
    if (null != cachedHTML) {
        return cachedHTML;
    }

    final ExecutorService pool = Executors.newSingleThreadExecutor();
    final long[] threadId = new long[1];

    final Callable<String> call = () -> {
        threadId[0] = Thread.currentThread().getId();

        String html = LANG_PROPS_SERVICE.get("contentRenderFailedLabel");

        if (MARKED_AVAILABLE) {
            html = toHtmlByMarked(markdownText);
            if (!StringUtils.startsWith(html, "<p>")) {
                html = "<p>" + html + "</p>";
            }
        } else {
            com.vladsch.flexmark.ast.Node document = PARSER.parse(markdownText);
            html = RENDERER.render(document);
            if (!StringUtils.startsWith(html, "<p>")) {
                html = "<p>" + html + "</p>";
            }
        }

        final Document doc = Jsoup.parse(html);
        final List<org.jsoup.nodes.Node> toRemove = new ArrayList<>();
        doc.traverse(new NodeVisitor() {
            @Override
            public void head(final org.jsoup.nodes.Node node, int depth) {
                if (node instanceof org.jsoup.nodes.TextNode) {
                    final org.jsoup.nodes.TextNode textNode = (org.jsoup.nodes.TextNode) node;
                    final org.jsoup.nodes.Node parent = textNode.parent();

                    if (parent instanceof Element) {
                        final Element parentElem = (Element) parent;

                        if (!parentElem.tagName().equals("code")) {
                            String text = textNode.getWholeText();
                            boolean nextIsBr = false;
                            final org.jsoup.nodes.Node nextSibling = textNode.nextSibling();
                            if (nextSibling instanceof Element) {
                                nextIsBr = "br".equalsIgnoreCase(((Element) nextSibling).tagName());
                            }

                            if (null != userQueryService) {
                                try {
                                    final Set<String> userNames = userQueryService.getUserNames(text);
                                    for (final String userName : userNames) {
                                        text = text.replace('@' + userName + (nextIsBr ? "" : " "),
                                                "@<a href='" + Latkes.getServePath() + "/member/" + userName
                                                        + "'>" + userName + "</a> ");
                                    }
                                    text = text.replace("@participants ",
                                            "@<a href='https://hacpai.com/article/1458053458339' class='ft-red'>participants</a> ");
                                } finally {
                                    JdbcRepository.dispose();
                                }
                            }

                            if (text.contains("@<a href=")) {
                                final List<org.jsoup.nodes.Node> nodes = Parser.parseFragment(text, parentElem,
                                        "");
                                final int index = textNode.siblingIndex();

                                parentElem.insertChildren(index, nodes);
                                toRemove.add(node);
                            } else {
                                textNode.text(Pangu.spacingText(text));
                            }
                        }
                    }
                }
            }

            @Override
            public void tail(org.jsoup.nodes.Node node, int depth) {
            }
        });

        toRemove.forEach(node -> node.remove());

        doc.select("pre>code").addClass("hljs");
        doc.select("a").forEach(a -> {
            String src = a.attr("href");
            if (!StringUtils.startsWithIgnoreCase(src, Latkes.getServePath())) {
                try {
                    src = URLEncoder.encode(src, "UTF-8");
                } catch (final Exception e) {
                }
                a.attr("href", Latkes.getServePath() + "/forward?goto=" + src);
                a.attr("target", "_blank");
            }
        });
        doc.outputSettings().prettyPrint(false);

        String ret = doc.select("body").html();
        ret = StringUtils.trim(ret);

        // cache it
        putHTML(markdownText, ret);

        return ret;
    };

    Stopwatchs.start("Md to HTML");
    try {
        final Future<String> future = pool.submit(call);

        return future.get(MD_TIMEOUT, TimeUnit.MILLISECONDS);
    } catch (final TimeoutException e) {
        LOGGER.log(Level.ERROR, "Markdown timeout [md=" + markdownText + "]");
        Callstacks.printCallstack(Level.ERROR, new String[] { "org.b3log" }, null);

        final Set<Thread> threads = Thread.getAllStackTraces().keySet();
        for (final Thread thread : threads) {
            if (thread.getId() == threadId[0]) {
                thread.stop();

                break;
            }
        }
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Markdown failed [md=" + markdownText + "]", e);
    } finally {
        pool.shutdownNow();

        Stopwatchs.end();
    }

    return LANG_PROPS_SERVICE.get("contentRenderFailedLabel");
}

From source file:org.bigmouth.nvwa.network.http.Response.java

public void removeCookie(String key) {
    List<Header> removes = Lists.newArrayList();
    for (Header header : headers) {
        if (StringUtils.equals("Set-Cookie", header.getName())) {
            String value = header.getValue();
            if (StringUtils.isNotBlank(value) && StringUtils.startsWithIgnoreCase(value, key)) {
                removes.add(header);/*from w  w w  . jav  a  2s  .  c  o m*/
            }
        }
    }
    headers.removeAll(removes);
}