Example usage for java.util.regex Pattern CASE_INSENSITIVE

List of usage examples for java.util.regex Pattern CASE_INSENSITIVE

Introduction

In this page you can find the example usage for java.util.regex Pattern CASE_INSENSITIVE.

Prototype

int CASE_INSENSITIVE

To view the source code for java.util.regex Pattern CASE_INSENSITIVE.

Click Source Link

Document

Enables case-insensitive matching.

Usage

From source file:org.sonatype.nexus.apachehttpclient.Hc4ProviderBase.java

/**
 * @since 2.6//  w w  w .j a  v  a2  s . co m
 */
protected void applyProxyConfig(final Builder builder, final RemoteProxySettings remoteProxySettings) {
    if (remoteProxySettings != null && remoteProxySettings.getHttpProxySettings() != null
            && remoteProxySettings.getHttpProxySettings().isEnabled()) {
        final Map<String, HttpHost> proxies = Maps.newHashMap();

        final HttpHost httpProxy = new HttpHost(remoteProxySettings.getHttpProxySettings().getHostname(),
                remoteProxySettings.getHttpProxySettings().getPort());
        applyAuthenticationConfig(builder, remoteProxySettings.getHttpProxySettings().getProxyAuthentication(),
                httpProxy);

        log.debug("http proxy setup with host '{}'", remoteProxySettings.getHttpProxySettings().getHostname());
        proxies.put("http", httpProxy);
        proxies.put("https", httpProxy);

        if (remoteProxySettings.getHttpsProxySettings() != null
                && remoteProxySettings.getHttpsProxySettings().isEnabled()) {
            final HttpHost httpsProxy = new HttpHost(remoteProxySettings.getHttpsProxySettings().getHostname(),
                    remoteProxySettings.getHttpsProxySettings().getPort());
            applyAuthenticationConfig(builder,
                    remoteProxySettings.getHttpsProxySettings().getProxyAuthentication(), httpsProxy);
            log.debug("https proxy setup with host '{}'",
                    remoteProxySettings.getHttpsProxySettings().getHostname());
            proxies.put("https", httpsProxy);
        }

        final Set<Pattern> nonProxyHostPatterns = Sets.newHashSet();
        if (remoteProxySettings.getNonProxyHosts() != null
                && !remoteProxySettings.getNonProxyHosts().isEmpty()) {
            for (String nonProxyHostRegex : remoteProxySettings.getNonProxyHosts()) {
                try {
                    nonProxyHostPatterns.add(Pattern.compile(nonProxyHostRegex, Pattern.CASE_INSENSITIVE));
                } catch (PatternSyntaxException e) {
                    log.warn("Invalid non proxy host regex: {}", nonProxyHostRegex, e);
                }
            }
        }

        builder.getHttpClientBuilder().setRoutePlanner(
                new NexusHttpRoutePlanner(proxies, nonProxyHostPatterns, DefaultSchemePortResolver.INSTANCE));
    }
}

From source file:com.github.feribg.audiogetter.helpers.Utils.java

/**
 * Extract a list of urls from a string//from w  w w .  j  a v  a 2s.c o  m
 * Retrieved from: http://www.java-tutorial.ch/core-java-tutorial/extract-urls-using-java-regular-expressions
 *
 * @param value
 * @return
 */
public static List<String> extractUrls(String value) {
    List<String> result = new ArrayList<String>();
    String urlPattern = "((https?):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
    Pattern p = Pattern.compile(urlPattern, Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(value);
    while (m.find()) {
        result.add(value.substring(m.start(0), m.end(0)));
    }
    return result;
}

From source file:de.zib.gndms.common.rest.UriFactory.java

public static Specifier<Void> parseSubspaceSpecifier(final String uri) {
    Pattern pattern = Pattern.compile("(.*)/dspace/_([^/]+)/?", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(uri);

    if (matcher.matches())
        return createSubspaceSpecifier(matcher.group(1), matcher.group(2));
    else/*from   www .ja v a  2s.  co  m*/
        throw new IllegalArgumentException("URL describes no valid Subspace specifier: " + uri);
}

From source file:com.dgtlrepublic.anitomyj.ParserNumber.java

/**
 * Match season and episode patters. e.g. "2x01", "S01E03", "S01-02xE001-150".
 *
 * @param word  the word//from   ww w  . j a v a2 s.com
 * @param token the token
 * @return true if the token matched
 */
public boolean matchSeasonAndEpisodePattern(String word, Token token) {
    String regexPattern = "S?(\\d{1,2})(?:-S?(\\d{1,2}))?(?:x|[ ._-x]?E)(\\d{1,3})(?:-E?(\\d{1,3}))?";
    Pattern pattern = Pattern.compile(regexPattern, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(word);
    if (matcher.matches()) {
        parser.getElements().add(new Element(kElementAnimeSeason, matcher.group(1)));
        if (StringUtils.isNotEmpty(matcher.group(2)))
            parser.getElements().add(new Element(kElementAnimeSeason, matcher.group(2)));
        setEpisodeNumber(matcher.group(3), token, false);
        if (StringUtils.isNotEmpty(matcher.group(4)))
            setEpisodeNumber(matcher.group(4), token, false);
        return true;
    }

    return false;
}

From source file:com.haulmont.cuba.core.global.QueryTransformerRegex.java

@Override
public void handleCaseInsensitiveParam(String paramName) {
    Pattern pattern = Pattern.compile(COND_PATTERN_REGEX + ":" + paramName, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(buffer);
    if (matcher.find()) {
        String field = matcher.group(1);
        buffer.replace(matcher.start(1), matcher.end(1), "lower(" + field + ")");
    }/*  w  w  w.j  a  va 2s .  c  o  m*/
}

From source file:com.ckfinder.connector.handlers.command.FileUploadCommand.java

/**
 * if file exists this method adds (number) to file.
 *
 * @param path folder//from   ww w .  j  a  v  a  2 s  . c o  m
 * @param name file name
 * @return new file name.
 */
private String getFinalFileName(final String path, final String name) {
    File file = new File(path, name);
    int number = 0;

    String nameWithoutExtension = FileUtils.getFileNameWithoutExtension(name, false);
    Pattern p = Pattern.compile("^(AUX|COM\\d|CLOCK\\$|CON|NUL|PRN|LPT\\d)$", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(nameWithoutExtension);
    boolean protectedName = m.find() ? true : false;

    while (true) {
        if (file.exists() || protectedName) {
            number++;
            StringBuilder sb = new StringBuilder();
            sb.append(FileUtils.getFileNameWithoutExtension(name, false));
            sb.append("(" + number + ").");
            sb.append(FileUtils.getFileExtension(name, false));
            this.newFileName = sb.toString();
            file = new File(path, this.newFileName);
            this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_FILE_RENAMED;
            protectedName = false;
        } else {
            return this.newFileName;
        }
    }
}

From source file:br.com.blackhubos.eventozero.updater.github.searcher.GitHubSearcher.java

@SuppressWarnings("unchecked")
private void processJsonObject(JSONObject jobject, MultiTypeFormatter formatter,
        Collection<Version> versionList) {
    /**//from   w  ww.  j  ava 2s.c  o  m
     * Variaveis do {@link Version}
     */
    String name = null;
    String version = null;
    Collection<Asset> downloadUrl = new ArrayList<>();
    String commitish = null;
    String changelog = null;
    Date creationDate = null;
    Date publishDate = null;
    long id = Long.MIN_VALUE;
    boolean criticalBug = false;
    boolean preRelease = false;
    List<String> supportedVersions = new ArrayList<>();
    /**
     * /Variaveis do {@link Version}
     */

    for (Map.Entry object : (Set<Map.Entry>) jobject.entrySet()) {

        Object key = object.getKey();
        Object value = object.getValue();
        String stringValue = String.valueOf(value);
        switch (GitHubAPIInput.parseObject(key)) {
        // Tag geralmente  a verso
        case TAG_NAME: {
            version = stringValue;
            break;
        }

        // Data de criao
        case CREATED_AT: {
            creationDate = formatter.format(stringValue, Date.class).get();
            break;
        }

        // Data de publicao
        case PUBLISHED_AT: {
            publishDate = formatter.format(stringValue, Date.class).get();
            break;
        }

        // Assets/Artefatos ou Arquivos (processado externamente)
        case ASSETS: {
            // Array com multiplos artefatos
            JSONArray jsonArray = (JSONArray) value;

            for (Object assetsJsonObject : jsonArray) {
                // Obtem o objeto a partir da array de artefatos
                JSONObject jsonAsset = (JSONObject) assetsJsonObject;
                // Obtm o artefato a partir do objeto
                Optional<Asset> assetOptional = Asset.parseJsonObject(jsonAsset, formatter);
                //  bom evitar um null n :P
                if (assetOptional.isPresent()) {
                    // Adiciona o artefato caso ele seja encontrado
                    downloadUrl.add(assetOptional.get());
                }
            }
            break;
        }

        // Obtem o nome (titulo) da verso
        case NAME: {
            name = stringValue;
            break;
        }

        // Numero de identificao do GitHub (nem sei se vamos usar)
        case ID: {
            id = Long.parseLong(stringValue);
            break;
        }

        // Obtm a mensagem, geralmente nosso changelog, e define se  uma verso de bug critico
        case BODY: {
            changelog = stringValue;
            // Define se  verso de bug critico
            criticalBug = changelog.endsWith("!!!CRITICAL BUG FOUND!!!")
                    || changelog.endsWith("CRITICAL BUG FOUND") || changelog.endsWith("CRITICAL BUG");

            // Regex para obter a linha que diz as verses suportadas
            Pattern supportedPattern = Pattern.compile("^(Verses|Supported)", Pattern.CASE_INSENSITIVE);

            // Faz loop nas linhas
            for (String line : changelog.split("\n")) {
                // Procura o regex na linha
                if (supportedPattern.matcher(line).find()) {
                    // Remove as letras
                    line = line.replaceAll("[^\\d. ]+", "").trim();
                    // Adiciona a lista
                    supportedVersions.addAll(Arrays.asList(line.split(" ")));
                }
            }

            break;
        }

        // Formata a boolean e verifica se ela  uma pre-release (alpha, beta, etc)
        case PRERELEASE: {
            Optional<Boolean> booleanOptional = formatter.format(value, Boolean.class);

            // Evitar um nullinho :D
            if (!booleanOptional.isPresent()) {
                preRelease = false;
                break;
            }

            preRelease = booleanOptional.get();
            break;
        }

        // Commitish geralmente  a branch ou a Commit relacionada a verso
        case TARGET_COMMITISH: {
            commitish = stringValue;
            break;
        }

        default: {
            break;
        }
        }
    }

    // Verifica se o ID  Diferente do valor minimo, isto vai fazer com que ns saibamos se alguma verso foi encontrada ou no :D
    if (id != Long.MIN_VALUE) {
        // Cria uma nova verso e adiciona a lista
        Version versionInstance = new Version(name, version, supportedVersions, downloadUrl, commitish,
                changelog, creationDate, publishDate, id, criticalBug, preRelease);
        versionList.add(versionInstance);
    }
}

From source file:com.linkedin.d2.D2BaseTest.java

protected void assertServersWeighSetup(Map<LoadBalancerEchoServer, Map<Integer, Double>> hostWeightMatrix,
        LoadBalancerClientCli cli, String zkConnectionString) throws Exception {
    String stores = LoadBalancerClientCli.printStores(cli.getZKClient(), zkConnectionString, "/d2");

    for (LoadBalancerEchoServer server : hostWeightMatrix.keySet()) {
        String str = server.getHost() + ": " + server.getPort() + "/cluster-\\d+="
                + hostWeightMatrix.get(server);
        Pattern pattern = Pattern.compile(str, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(stores);

        assertTrue(matcher.find(),// w  w w  . j  a  v a  2  s.  c o m
                "URIProperty '" + str + "' was not found is current active clusters.\n" + stores);
    }
}

From source file:csiro.pidsvc.mappingstore.Manager.java

protected String processGenericXmlCommand(String inputData, String xmlSchemaResourcePath,
        String xsltResourcePath) throws SaxonApiException, SQLException, IOException, ValidationException {
    // Validate request.
    if (xmlSchemaResourcePath != null)
        validateRequest(inputData, xmlSchemaResourcePath);

    // Generate SQL query.
    Processor processor = new Processor(false);
    XsltCompiler xsltCompiler = processor.newXsltCompiler();
    InputStream inputSqlGen = getClass().getResourceAsStream(xsltResourcePath);
    XsltExecutable xsltExec = xsltCompiler.compile(new StreamSource(inputSqlGen));
    XsltTransformer transformer = xsltExec.load();

    StringWriter swSqlQuery = new StringWriter();
    transformer.setInitialContextNode(//from  w  ww . jav  a  2  s  . c  om
            processor.newDocumentBuilder().build(new StreamSource(new StringReader(inputData))));
    transformer.setDestination(new Serializer(swSqlQuery));
    transformer.setParameter(new QName("AuthorizationName"), new XdmAtomicValue(getAuthorizationName()));
    _logger.trace("Generating SQL query.");
    transformer.transform();

    // Update mappings in the database.
    Statement st = null;
    try {
        String sqlQuery = swSqlQuery.toString();
        st = _connection.createStatement();
        st.execute(sqlQuery);

        Pattern re = Pattern.compile("^--((?:OK|ERROR): .*)", Pattern.CASE_INSENSITIVE);
        Matcher m = re.matcher(sqlQuery);

        if (m.find())
            return m.group(1);
    } finally {
        if (st != null)
            st.close();
    }
    return null;
}

From source file:wuit.crawler.CrawlerHtml.java

public String match(String content, String filter) {
    String val = "";
    try {/*  w w w  .j a v a  2 s.  co  m*/
        Matcher m = Pattern.compile(filter, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE).matcher(content);
        while (m.find()) {
            val = m.group();
            break;
        }
    } catch (Exception e) {
        System.out.println("Composite Parse match " + e.getMessage());
    }
    return val;
}