Example usage for java.util.regex Matcher reset

List of usage examples for java.util.regex Matcher reset

Introduction

In this page you can find the example usage for java.util.regex Matcher reset.

Prototype

public Matcher reset(CharSequence input) 

Source Link

Document

Resets this matcher with a new input sequence.

Usage

From source file:org.apache.accumulo.start.classloader.AccumuloClassLoader.java

/**
 * Replace environment variables in the classpath string with their actual value
 *//*from   w ww . j a va2  s  .c  o  m*/
public static String replaceEnvVars(String classpath, Map<String, String> env) {
    Pattern envPat = Pattern.compile("\\$[A-Za-z][a-zA-Z0-9_]*");
    Matcher envMatcher = envPat.matcher(classpath);
    while (envMatcher.find(0)) {
        // name comes after the '$'
        String varName = envMatcher.group().substring(1);
        String varValue = env.get(varName);
        if (varValue == null) {
            varValue = "";
        }
        classpath = (classpath.substring(0, envMatcher.start()) + varValue
                + classpath.substring(envMatcher.end()));
        envMatcher.reset(classpath);
    }
    return classpath;
}

From source file:br.bireme.mlts.MoreLikeThatServlet.java

public static String getParamValue(final String file, final String paramName, final String defaultValue)
        throws IOException {
    if (file == null) {
        throw new NullPointerException("file");
    }//  w w  w.ja v  a2 s  . c  o  m
    if (paramName == null) {
        throw new NullPointerException("paramName");
    }
    final String regExp = "< *" + paramName.trim() + " *>([^<]*)</ *" + paramName.trim() + " *>";
    final Matcher mat = Pattern.compile(regExp).matcher("");
    final BufferedReader reader = new BufferedReader(new FileReader(file));
    String value = defaultValue;

    while (true) {
        final String line = reader.readLine();
        if (line == null) {
            break;
        }
        mat.reset(line);
        if (mat.find()) {
            value = mat.group(1);
            break;
        }
    }

    return value;
}

From source file:io.viewserver.core.Utils.java

public static String replaceSystemTokens(String inputString) {
    String result = inputString;//from   www  . j  a  v  a 2  s . c  om
    Pattern pattern = Pattern.compile("%([^%]+)%");
    Matcher matcher = pattern.matcher(inputString);
    while (true) {
        boolean found = false;
        while (matcher.find()) {
            found = true;
            String token = matcher.group(1);
            String value = Configuration.getString(token);
            if (value != null) {
                boolean encrypted = Configuration.getBoolean(String.format("%s[@%s]", token, PARSE_KEY), false);
                if (encrypted) {
                    value = parse(value);
                }
                result = result.replace(matcher.group(0), value);
            }
        }
        if (!found) {
            break;
        }
        matcher.reset(result);
    }
    //only replace single backslashes with double backslashes
    return result.replaceAll(Matcher.quoteReplacement("(?<!\\)\\(?![\\\"\'])"),
            Matcher.quoteReplacement("\\\\"));
}

From source file:org.apache.pig.impl.util.Utils.java

public static String substituteVars(String expr) {
    if (expr == null) {
        return null;
    }// w w w  .  ja v  a 2s.  c  o m
    Matcher match = varPat.matcher("");
    String eval = expr;
    for (int s = 0; s < MAX_SUBST; s++) {
        match.reset(eval);
        if (!match.find()) {
            return eval;
        }
        String var = match.group();
        var = var.substring(2, var.length() - 1); // remove ${ .. }
        String val = null;
        val = System.getProperty(var);
        if (val == null) {
            return eval; // return literal ${var}: var is unbound
        }
        // substitute
        eval = eval.substring(0, match.start()) + val + eval.substring(match.end());
    }
    throw new IllegalStateException("Variable substitution depth too large: " + MAX_SUBST + " " + expr);
}

From source file:org.apache.camel.component.restlet.RestletProducer.java

private static String buildUri(RestletEndpoint endpoint, Exchange exchange) throws CamelExchangeException {
    String uri = endpoint.getProtocol() + "://" + endpoint.getHost() + ":" + endpoint.getPort()
            + endpoint.getUriPattern();//from   w w  w.j  av a  2 s  . co  m

    // substitute { } placeholders in uri and use mandatory headers
    if (LOG.isTraceEnabled()) {
        LOG.trace("Substituting { } placeholders in uri: " + uri);
    }
    Matcher matcher = PATTERN.matcher(uri);
    while (matcher.find()) {
        String key = matcher.group(1);
        String header = exchange.getIn().getHeader(key, String.class);
        // header should be mandatory
        if (header == null) {
            throw new CamelExchangeException("Header with key: " + key + " not found in Exchange", exchange);
        }

        if (LOG.isTraceEnabled()) {
            LOG.trace("Replacing: " + matcher.group(0) + " with header value: " + header);
        }

        uri = matcher.replaceFirst(header);
        // we replaced uri so reset and go again
        matcher.reset(uri);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Using uri: " + uri);
    }

    return uri;
}

From source file:org.structr.web.entity.html.HtmlElement.java

public static String replaceVariables(SecurityContext securityContext, AbstractNode page,
        AbstractNode startNode, String pageId, String componentId, AbstractNode viewComponent, String rawValue)
        throws FrameworkException {

    String value = null;/*from   w  w w. j a  va 2 s  .co  m*/

    if ((rawValue != null) && (rawValue instanceof String)) {

        value = (String) rawValue;

        // re-use matcher from previous calls
        Matcher matcher = threadLocalTemplateMatcher.get();

        matcher.reset(value);

        while (matcher.find()) {

            String group = matcher.group();
            String source = group.substring(2, group.length() - 1);

            // fetch referenced property
            String partValue = extractFunctions(securityContext, page, startNode, pageId, componentId,
                    viewComponent, source);

            if (partValue != null) {

                value = value.replace(group, partValue);
            }

        }

    }

    return value;

}

From source file:org.structr.web.entity.html.HtmlElement.java

public static String extractFunctions(SecurityContext securityContext, AbstractNode page,
        AbstractNode startNode, String pageId, String componentId, AbstractNode viewComponent, String source)
        throws FrameworkException {

    // re-use matcher from previous calls
    Matcher functionMatcher = threadLocalFunctionMatcher.get();

    functionMatcher.reset(source);

    if (functionMatcher.matches()) {

        String viewComponentId = viewComponent != null ? viewComponent.getProperty(AbstractNode.uuid) : null;
        String functionGroup = functionMatcher.group(1);
        String parameter = functionMatcher.group(2);
        String functionName = functionGroup.substring(0, functionGroup.length());
        Function<String, String> function = functions.get(functionName);

        if (function != null) {

            // store thread "state" in function
            function.setDataId(viewComponentId);
            function.setPageId(pageId);//from  w  ww . j  av  a2s  .  c  o m

            if (parameter.contains(",")) {

                String[] parameters = split(parameter);
                String[] results = new String[parameters.length];

                // collect results from comma-separated function parameter
                for (int i = 0; i < parameters.length; i++) {

                    results[i] = extractFunctions(securityContext, page, startNode, pageId, componentId,
                            viewComponent, StringUtils.strip(parameters[i]));
                }

                return function.apply(results);

            } else {

                String result = extractFunctions(securityContext, page, startNode, pageId, componentId,
                        viewComponent, StringUtils.strip(parameter));

                return function.apply(new String[] { result });

            }
        }

    }

    // if any of the following conditions match, the literal source value is returned
    if (StringUtils.isNotBlank(source) && StringUtils.isNumeric(source)) {

        // return numeric value
        return source;
    } else if (source.startsWith("\"") && source.endsWith("\"")) {

        return source.substring(1, source.length() - 1);
    } else if (source.startsWith("'") && source.endsWith("'")) {

        return source.substring(1, source.length() - 1);
    } else {

        // return property key
        return convertValueForHtml(getReferencedProperty(securityContext, page, startNode, pageId, componentId,
                viewComponent, source));
    }
}

From source file:byku.traindroid.DataFacade.java

private static String parsePage(String page, String regexp, ArrayList<Pair<String, String>> times) {
    ArrayList<String> matches = new ArrayList<String>();

    Pattern pattern = Pattern.compile(regexp);
    Matcher matcher = pattern.matcher(page);

    Pattern timePattern = Pattern.compile(TIME_REGEXP);
    Matcher timeMatcher = timePattern.matcher("");

    while (matcher.find()) {
        matches.add(matcher.group());//ww  w  . ja  va2s.c  o  m
    }

    if (matches.size() == 0) {
        return "Trains data not found. Maybe server changes it's format.";
    }

    for (int i = 0; i < matches.size(); i += 2) {
        if (i + 1 == matches.size()) {
            return "Incorrect times count.";
        }

        if (matches.get(i).equals(matches.get(i + 1))) {
            continue;
        }

        timeMatcher.reset(matches.get(i));
        String timeFrom = timeMatcher.find() ? timeMatcher.group() : "error";

        timeMatcher.reset(matches.get(i + 1));
        String timeTo = timeMatcher.find() ? timeMatcher.group() : "error";

        times.add(new Pair<String, String>(timeFrom, timeTo));
    }

    return "";
}

From source file:br.com.capanema.kers.velocity.util.BuildManagerUtil.java

/**
 * Increment source code of filePath using template fragment.
 * /*from w  w  w  .j av a  2 s  .c  om*/
 * @param filePath
 * @param incrementPath
 * @param incrementPattern
 * @param dataGroup
 */
public static void incrementSourceCode(String filePath, String incrementPath, String incrementPattern,
        String firstAfter, Map<String, String> params, TemplateDataGroup dataGroup) {
    try {
        HashMap<String, Object> velocityVariables = new HashMap<String, Object>(); //map for velocity variables
        velocityVariables.put("data", dataGroup); //conjunto de vriaveis que podem ser usados no template

        if (params != null && params.size() > 0) {
            /*            for (String name : params.keySet()) {
                           velocityVariables.put("params."+name, params.get(name));
                        }*/
            velocityVariables.put("params", params);
        }

        //rodando velocity do incremento
        TemplateEngine templateEngine = TemplateEngineFactory.getEngine(incrementPath, true);
        String incrementSource = templateEngine.runFile(incrementPath, velocityVariables);

        // Create the pattern
        Pattern pattern = Pattern.compile("[\r\n]*[\t]*" + incrementPattern, Pattern.DOTALL); //o "[\r\n]*"  para pegar as quebras de linhas que podem existir no incremento
        Matcher matcher = pattern.matcher("");

        //novo incremento
        //aqui vai executar o pattern no prprio incremento... se o pattern estiver errado no ir encontrar nada e vai abortar o incremento
        matcher.reset(incrementSource);
        Map<String, String[]> mapGroupIncrement = new LinkedHashMap<String, String[]>();
        while (matcher.find()) {
            String[] groups = new String[matcher.groupCount()];
            for (int i = 0; i < matcher.groupCount(); i++) {
                groups[i] = matcher.group(i + 1);
            }

            String increment = matcher.group(); //new increment
            mapGroupIncrement.put(increment, groups); //map increment vs groups
        }

        if (mapGroupIncrement.size() == 0) { //no encontrou groups no incremento (usado para as comparaes), aborta
            return;
        }

        //le o arquivo atual
        FileInputStream inputFilePath = new FileInputStream(filePath);
        BufferedInputStream bufferedInput = new BufferedInputStream(inputFilePath);
        StringBuffer filePathContent = new StringBuffer();
        int ch = 0;
        while ((ch = bufferedInput.read()) > -1) {
            filePathContent.append((char) ch);
        }
        inputFilePath.close();
        bufferedInput.close();

        //procura no arquivo todo pela expresso regular
        matcher = pattern.matcher("");
        matcher.reset(filePathContent);
        StringBuffer newContentFile = new StringBuffer();
        int countMatcher = 0;
        Map<String, String[]> mapGroupFile = new HashMap<String, String[]>();
        while (matcher.find()) { //verifica cada ocorrncia da expresso no arquivo
            String[] groups = new String[matcher.groupCount()]; //pega os groups "()" do matcher para fazer a comparao com os groups do incremento que est sendo gerado
            for (int i = 0; i < matcher.groupCount(); i++) {
                groups[i] = matcher.group(i + 1);
            }
            mapGroupFile.put(matcher.group(), groups); //adiciona esse group em uma lista para ser avaliado depois

            countMatcher++; //isso vai contar onde esta o ltimo matcher
        }

        //valida quais incrementos so realmente novos, comparando os groups
        List<String> newIncrements = new LinkedList<String>();
        for (String groupIncrement : mapGroupIncrement.keySet()) {
            String[] groups1 = mapGroupIncrement.get(groupIncrement); //groups do incremento
            boolean itemFound = false;

            for (String groupFile : mapGroupFile.keySet()) {
                String[] groups2 = mapGroupFile.get(groupFile); //groups do incremento

                if (ArrayUtil.equals(groups1, groups2)) { //se no arquivo tem o cdigo que est sendo gerado, no precisa adicionar esse incremnto
                    itemFound = true;
                }
            }
            if (!itemFound) { //se no arquivo no tem o cdigo que est sendo gerado, adiciona em um array
                newIncrements.add(groupIncrement);
            }
        }

        //realiza uma quebra de linha adicional para o primeiro item do incremento, para no ficar na mesma linha do ltimo matcher no arquivo
        StringBuffer newIncrementSource = new StringBuffer();
        int i = 0;
        for (String incremento : newIncrements) {
            if (i == 0 && incremento.indexOf("\r\n\r\n") != 0) { //s coloca quebra de linha se precisar
                newIncrementSource.append("\r\n");
            }

            newIncrementSource.append(incremento);
            i++;
        }

        if (newIncrements.size() > 0) {
            //no encontrou nenhum increment no arquivo, ento procura pelo firstAfter para inserir o primeiro incremento
            if (countMatcher == 0 && firstAfter != null && !firstAfter.equals("")) {
                pattern = Pattern.compile(firstAfter, Pattern.DOTALL);
                matcher = pattern.matcher("");
                matcher.reset(filePathContent);

                //esse loop s serviu para contar e achar o ltimo matcher. No consegui fazer sem isso :(
                countMatcher = 0;
                while (matcher.find()) { //verifica cada ocorrncia da expresso
                    countMatcher++;
                }
            }

            //aqui vou realmente substituir os valores, j sabendo qual  a ltima ocorrencia da palavra no arquivo
            i = 0;
            matcher.reset();
            while (matcher.find()) { //verifica cada ocorrncia da expresso
                i++;
                if (countMatcher == i) { //se encontrou a ltima ocorrencia
                    String matcherGroup = matcher.group();
                    matcher.appendReplacement(newContentFile, matcherGroup + newIncrementSource); //substitui a ultima ocorrencia do firstIncrement   
                }
            }
            matcher.appendTail(newContentFile);
        }

        //save new file
        if (newContentFile.length() > 0) {
            FileUtil.writeFile(filePath, newContentFile.toString());
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}

From source file:org.apache.flink.test.util.TestBaseUtils.java

public static void checkLinesAgainstRegexp(String resultPath, String regexp) {
    Pattern pattern = Pattern.compile(regexp);
    Matcher matcher = pattern.matcher("");

    ArrayList<String> list = new ArrayList<>();
    try {/*from   w  w w .j  a  v a  2  s. c o  m*/
        readAllResultLines(list, resultPath, new String[] {}, false);
    } catch (IOException e1) {
        Assert.fail("Error reading the result");
    }

    for (String line : list) {
        matcher.reset(line);
        if (!matcher.find()) {
            String msg = "Line is not well-formed: " + line;
            Assert.fail(msg);
        }
    }
}