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() 

Source Link

Document

Resets this matcher.

Usage

From source file:org.rhq.enterprise.server.plugins.alertOperations.AlertTokenReplacer.java

/**
 * Replace all tokens on the input line. If no tokens are found the input is returned.
 * Tokens have the form '<i><% class.sub %></i>'
 * @param input a line of text/* ww w.ja va 2 s.  co m*/
 * @return input with tokens replaced.
 * @see org.rhq.enterprise.server.plugins.alertOperations.Token
 * @see org.rhq.enterprise.server.plugins.alertOperations.TokenClass
 */
public String replaceTokens(String input) {

    String work = input;
    Matcher matcher = pattern.matcher(work);
    if (!matcher.find()) {
        if (log.isDebugEnabled()) {
            log.debug("No tokens found in " + input);
        }
        return input;
    }
    matcher.reset();

    do {
        matcher = pattern.matcher(work);
        if (!matcher.find()) {
            break;
        }
        String replacement = replaceToken(matcher.group(1));
        String s = matcher.replaceFirst(replacement);
        work = s;

    } while (true);

    return work;
}

From source file:de.tudarmstadt.ukp.dkpro.core.textnormalizer.frequency.ExpressiveLengtheningNormalizer.java

public String getBestReplacement(String token) throws IOException {
    Pattern pattern = Pattern.compile("([a-zA-Z])\\1{1,}");
    Matcher matcher = pattern.matcher(token);

    // In case there are no abnormalities
    if (!matcher.find())
        return token;

    // Collecting the start points of all abnormal parts
    List<Integer> abnormalities = new ArrayList<Integer>();
    matcher.reset();
    while (matcher.find()) {
        abnormalities.add(matcher.start());
    }//w  ww  . j  av  a 2 s .com

    // splitting in parts starting with first character abnormalities
    List<String> parts = new ArrayList<String>();

    for (int i = 0; i < abnormalities.size(); i++) {
        // in case the token has only one abnormality
        if (abnormalities.size() == 1) {
            parts.add(token);
            break;
        }

        // first abnormality
        if (i == 0) {
            parts.add(token.substring(0, abnormalities.get(i + 1)));
            continue;
        }

        // last abnormality
        if (i == abnormalities.size() - 1) {
            parts.add(token.substring(abnormalities.get(i)));
            continue;
        }

        if (i < abnormalities.size() - 1) {
            parts.add(token.substring(abnormalities.get(i), abnormalities.get(i + 1)));
            continue;
        }
    }

    // Fills big list of arrays with all parts and their versions
    List<String[]> bigList = new ArrayList<String[]>();
    for (String part : parts) {
        String v1 = part.replaceFirst(pattern.pattern(), "$1");
        String v2 = part.replaceFirst(pattern.pattern(), "$1$1");
        String v3 = part.replaceFirst(pattern.pattern(), "$1$1$1");

        bigList.add(new String[] { v1, v2, v3 });
    }

    List<String> candidates = permute(bigList, 0, new ArrayList<String>(), "");

    return getMostFrequentCandidate(candidates);
}

From source file:org.lightcouch.CouchDbDesign.java

private String processCodeMacro(String id, String from, String body) {
    Matcher m = codeMacroPattern.matcher(body);
    if (!m.find())
        return body;
    m.reset();
    StringBuilder b = new StringBuilder(body.length() * 2);
    int end = 0;/*from w w w .  ja v a2 s  .  c om*/
    while (m.find()) {
        if (log.isDebugEnabled())
            log.debug("replacing macro " + m.start() + ":" + m.end() + " " + m.group(2));
        b.append(body.substring(end, m.start()));
        String filePath = m.group(2);
        String macro = readTextResource(DESIGN_DOCS_DIR + "/" + id + "/" + filePath);
        if (macro == null)
            macro = readTextResource(DESIGN_DOCS_DIR + "/" + filePath); // global macro
        if (macro == null)
            throw new RuntimeException("Code file '" + filePath + "' not found on classpath; referenced by "
                    + from + " :: '" + m.group(1) + "'");
        b.append("// ==> " + filePath + "\n");
        b.append(macro);
        b.append("\n");
        b.append("// <== " + filePath + "\n");
        end = m.end();
    }
    b.append(body.substring(end));
    body = b.toString();
    if (log.isTraceEnabled())
        log.trace(from + " after // !code substitutions:\n" + body);
    return body;
}

From source file:org.silverpeas.tools.dbBuilder.wysiwyg.purge.DataWiring.java

/**
 * Retrieve from a line the component id.
 * @param line//from  w  ww  . jav a  2s .c  om
 * @return
 */
public String getComponentIdFromLine(String line) {
    Matcher componentMatcher = REGEXP_COMPONENT_ID.matcher(line);
    for (String componentId : components) {
        while (componentMatcher.find()) {
            String extractedComponentId = componentMatcher.group(1);
            if (extractedComponentId.equals(componentId)) {
                return componentId;
            }
        }

        componentMatcher.reset();
    }
    return null;
}

From source file:org.nextframework.persistence.exception.OracleSQLErrorCodeSQLExceptionTranslator.java

@Override
protected DataAccessException customTranslate(String task, String sql, SQLException sqlEx) {
    //TODO ARRUMAR (FAZER HIGH COHESION.. LOW COUPLING)
    //System.out.println(task+" - "+sql);
    if (sqlEx.getNextException() != null) {
        sqlEx = sqlEx.getNextException();
    }//from w ww  . jav  a  2 s .  c om
    String errorMessage = sqlEx.getMessage();
    Matcher matcher = pattern.matcher(errorMessage);
    Matcher matcherIngles = patternIngles.matcher(errorMessage);
    //System.out.println(">>> "+errorMessage);
    if (!matcher.find()) {
        matcher = matcherIngles;
    } else {
        matcher.reset();
    }
    if (matcher.find()) {
        //exceo de FK
        String fk_name = matcher.group(1);
        if (fk_name.contains(".")) {
            fk_name = fk_name.substring(fk_name.indexOf('.') + 1, fk_name.length());
        }

        String fk_table_name = matcher.group(1).toUpperCase();
        String pk_table_name = matcher.group(1).toUpperCase();
        String fkTableDisplayName = null;
        String pkTableDisplayName = null;
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet importedKeys = metaData.getImportedKeys(null, null, null);

            while (importedKeys.next()) {
                System.out.println(importedKeys.getString("FK_NAME"));
                if (importedKeys.getString("FK_NAME").equals(fk_name)) {
                    pk_table_name = importedKeys.getString("PKTABLE_NAME");
                    if (pk_table_name != null) {
                        pk_table_name = pk_table_name.toUpperCase();
                    }

                    fk_table_name = importedKeys.getString("FKTABLE_NAME");
                    if (fk_table_name != null) {
                        fk_table_name = fk_table_name.toUpperCase();
                    }
                }
            }
        } catch (SQLException e) {
            //se nao conseguir o metadata .. vazar
            log.warn("No foi possvel conseguir o metadata do banco para ler informacoes de FK.");
            return null;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {

                }
            }
        }

        Class<?>[] entities = ClassManagerFactory.getClassManager().getClassesWithAnnotation(Entity.class);
        pkTableDisplayName = pk_table_name;
        fkTableDisplayName = fk_table_name;
        for (Class<?> entityClass : entities) {
            String tableName = getTableName(entityClass);
            if (tableName.equals(pk_table_name)) {
                pkTableDisplayName = BeanDescriptorFactory.forClass(entityClass).getDisplayName();
            }
            if (tableName.equals(fk_table_name)) {
                fkTableDisplayName = BeanDescriptorFactory.forClass(entityClass).getDisplayName();
            }
        }

        String mensagem = null;
        if (sql.toLowerCase().trim().startsWith("delete")) {
            mensagem = "No foi possvel remover " + pkTableDisplayName
                    + ". Existe(m) registro(s) vinculado(s) em " + fkTableDisplayName + ".";
        } else if (sql.toLowerCase().trim().startsWith("update")) {
            mensagem = "No foi possvel atualizar " + fkTableDisplayName + ". A referncia para "
                    + pkTableDisplayName + "  invlida.";
        } else if (sql.toLowerCase().trim().startsWith("insert")) {
            mensagem = "No foi possvel inserir " + fkTableDisplayName + ". A referncia para "
                    + pkTableDisplayName + "  invlida.";
        }
        return new ForeignKeyException(mensagem);
    } else {
        int indexOf = errorMessage.indexOf("APP");
        if (indexOf > 0) {
            errorMessage = errorMessage.substring(indexOf + 3);
            return new ApplicationDatabaseException(errorMessage);
        }
    }
    return null;
}

From source file:org.openhab.binding.ACDBCommon.internal.ACDBBinding.java

@Override
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    logger.debug(getBindingName() + ":calling updated(config)!");
    String lowerBindingName = StringUtils.lowerCase(getBindingName());
    if (config == null) {
        throw new ConfigurationException(lowerBindingName + ":url",
                "The SQL database URL is missing - please configure the " + lowerBindingName
                        + ":url parameter in openhab.cfg");
    }//from  w ww  .j  a v  a 2  s. c o m

    // read DB Server connection Information
    DBManager.serverCache = new HashMap<String, ServerInfo>();
    Enumeration<String> keys = config.keys();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();

        Matcher matcher = DEVICES_PATTERN.matcher(key);

        if (!matcher.matches()) {
            continue;
        }
        matcher.reset();
        matcher.find();

        String serverId = matcher.group(1);
        ServerInfo server = DBManager.serverCache.get(serverId);
        if (server == null) {
            server = new ServerInfo(serverId);
            DBManager.serverCache.put(serverId, server);
            logger.debug("Created new DBserver Info " + serverId);
        }

        String configKey = matcher.group(2);
        String value = (String) config.get(key);

        if ("url".equals(configKey)) {
            server.setUrl(value);
        } else if ("user".equals(configKey)) {
            server.setUser(value);
        } else if ("password".equals(configKey)) {
            server.setPassword(value);
        } else {
            throw new ConfigurationException(configKey, "the given configKey '" + configKey + "' is unknown");
        }
    }
    // read defult DBServer connection information
    String serverId = "DefultServer";
    ServerInfo server = new ServerInfo(serverId);
    server.setUrl((String) config.get("url"));
    server.setUser((String) config.get("user"));
    server.setPassword((String) config.get("password"));

    DBManager.serverCache.put("DefultServer", server);

    String refreshIntervalString = (String) config.get("refresh");
    if (StringUtils.isNotBlank(refreshIntervalString)) {
        refreshInterval = Long.parseLong(refreshIntervalString);
    }

    try {
        for (Map.Entry<String, ServerInfo> mapI : DBManager.serverCache.entrySet()) {
            ServerInfo serverI = mapI.getValue();
            serverI.setDriverClassName(getDriverClassName());
            if (StringUtils.isBlank(serverI.getUrl()) || StringUtils.isBlank(serverI.getUser())
                    || StringUtils.isBlank(serverI.getPassword())) {
                logger.warn("more information needed:" + serverI.toString());
                continue;
            }
            serverI.openConnection();
        }
    } catch (Exception e) {
        logger.error(getBindingName() + ":failed to connect DB.", e);
    }

    setProperlyConfigured(true);
    logger.debug(getBindingName() + ":updated(config) is called!");
}

From source file:org.openhab.binding.multionewire.internal.MultiOneWireBinding.java

@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {

    if (config == null)
        return;/*from w  w w.j  a va  2s. c o m*/

    @SuppressWarnings("unchecked")
    Enumeration<String> keys = config.keys();

    if (serverList == null) {
        serverList = new HashMap<String, ServerConfig>();
    }

    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();

        // the config-key enumeration contains additional keys that we
        // don't want to process here ...
        if ("service.pid".equals(key)) {
            continue;
        }

        Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key);

        if (!matcher.matches()) {
            continue;
        }

        matcher.reset();
        matcher.find();

        String serverId = matcher.group(1);

        ServerConfig serverConfig = serverList.get(serverId);

        if (serverConfig == null) {
            serverConfig = new ServerConfig();
            serverList.put(serverId, serverConfig);
        }

        String configKey = matcher.group(2);
        String value = (String) config.get(key);

        if ("host".equals(configKey)) {
            String[] hostConfig = value.split(":");
            serverConfig.host = hostConfig[0];
            if (hostConfig.length > 1) {
                serverConfig.port = Integer.parseInt(hostConfig[1]);
            } else {
                serverConfig.port = 4304;
            }
            logger.debug("Added new Server {}:{} to serverlist",
                    new Object[] { serverConfig.host, serverConfig.port });
        } else {
            throw new ConfigurationException(configKey,
                    "The given OWServer configKey '" + configKey + "' is unknown");
        }
    }

    String refreshIntervalString = (String) config.get("refresh");
    if (StringUtils.isNotBlank(refreshIntervalString)) {
        refreshInterval = Long.parseLong(refreshIntervalString);
    }

    String retryString = (String) config.get("retry");
    if (StringUtils.isNotBlank(retryString)) {
        retry = Integer.parseInt(retryString);
    }

    String tempScaleString = (String) config.get("tempscale");
    if (StringUtils.isNotBlank(tempScaleString)) {
        try {
            tempScale = OwTemperatureScale.valueOf("OWNET_TS_" + tempScaleString);
        } catch (IllegalArgumentException iae) {
            throw new ConfigurationException("onewire:tempscale", "Unknown temperature scale '"
                    + tempScaleString + "'. Valid values are CELSIUS, FAHRENHEIT, KELVIN or RANKIN.");
        }
    }

    setProperlyConfigured(true);
}

From source file:org.openhab.binding.owserver.internal.OWServerBinding.java

/**
 * {@inheritDoc}/*  ww w  . j a v a 2 s  .c  o m*/
 */
public void updated(Dictionary<String, ?> config) throws ConfigurationException {
    if (config != null) {
        Enumeration<String> keys = config.keys();

        if (serverList == null) {
            serverList = new HashMap<String, OWServerConfig>();
        }

        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();

            // the config-key enumeration contains additional keys that we
            // don't want to process here ...
            if ("service.pid".equals(key)) {
                continue;
            }

            Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key);

            if (!matcher.matches()) {
                continue;
            }

            matcher.reset();
            matcher.find();

            String serverId = matcher.group(1);

            OWServerConfig deviceConfig = serverList.get(serverId);

            if (deviceConfig == null) {
                deviceConfig = new OWServerConfig();
                serverList.put(serverId, deviceConfig);
            }

            String configKey = matcher.group(2);
            String value = (String) config.get(key);

            if ("host".equals(configKey)) {
                deviceConfig.host = value;
            } else if ("user".equals(configKey)) {
                deviceConfig.user = value;
            } else if ("password".equals(configKey)) {
                deviceConfig.password = value;
            } else {
                throw new ConfigurationException(configKey,
                        "The given OWServer configKey '" + configKey + "' is unknown");
            }
        }

        String timeoutString = (String) config.get("timeout");
        if (StringUtils.isNotBlank(timeoutString)) {
            timeout = Integer.parseInt(timeoutString);
        }

        String granularityString = (String) config.get("granularity");
        if (StringUtils.isNotBlank(granularityString)) {
            granularity = Integer.parseInt(granularityString);
        }

        String cacheString = (String) config.get("cache");
        if (StringUtils.isNotBlank(cacheString)) {
            cacheDuration = Integer.parseInt(cacheString);
        }

        setProperlyConfigured(true);
    }
}

From source file:it.bradipao.berengar.DbTool.java

public static String jsonMinify(String jsonString) {
    String tokenizer = "\"|(/\\*)|(\\*/)|(//)|\\n|\\r";
    String magic = "(\\\\)*$";
    Boolean in_string = false;/*from w  w  w  . j  a va2  s .  c  o m*/
    Boolean in_multiline_comment = false;
    Boolean in_singleline_comment = false;
    String tmp = "";
    String tmp2 = "";
    List<String> new_str = new ArrayList<String>();
    Integer from = 0;
    String lc = "";
    String rc = "";

    Pattern pattern = Pattern.compile(tokenizer);
    Matcher matcher = pattern.matcher(jsonString);

    Pattern magicPattern = Pattern.compile(magic);
    Matcher magicMatcher = null;
    Boolean foundMagic = false;

    if (!matcher.find())
        return jsonString;
    else
        matcher.reset();

    while (matcher.find()) {
        lc = jsonString.substring(0, matcher.start());
        rc = jsonString.substring(matcher.end(), jsonString.length());
        tmp = jsonString.substring(matcher.start(), matcher.end());

        if (!in_multiline_comment && !in_singleline_comment) {
            tmp2 = lc.substring(from);
            if (!in_string)
                tmp2 = tmp2.replaceAll("(\\n|\\r|\\s)*", "");
            new_str.add(tmp2);
        }
        from = matcher.end();

        if (tmp.charAt(0) == '\"' && !in_multiline_comment && !in_singleline_comment) {
            magicMatcher = magicPattern.matcher(lc);
            foundMagic = magicMatcher.find();
            if (!in_string || !foundMagic || (magicMatcher.end() - magicMatcher.start()) % 2 == 0) {
                in_string = !in_string;
            }
            from--;
            rc = jsonString.substring(from);
        } else if (tmp.startsWith("/*") && !in_string && !in_multiline_comment && !in_singleline_comment) {
            in_multiline_comment = true;
        } else if (tmp.startsWith("*/") && !in_string && in_multiline_comment && !in_singleline_comment) {
            in_multiline_comment = false;
        } else if (tmp.startsWith("//") && !in_string && !in_multiline_comment && !in_singleline_comment) {
            in_singleline_comment = true;
        } else if ((tmp.startsWith("\n") || tmp.startsWith("\r")) && !in_string && !in_multiline_comment
                && in_singleline_comment) {
            in_singleline_comment = false;
        } else if (!in_multiline_comment && !in_singleline_comment
                && !tmp.substring(0, 1).matches("\\n|\\r|\\s")) {
            new_str.add(tmp);
        }
    }

    new_str.add(rc);
    StringBuffer sb = new StringBuffer();
    for (String str : new_str)
        sb.append(str);

    return sb.toString();
}

From source file:org.openhab.binding.dmlsmeter.internal.DmlsMeterBinding.java

private Set<String> getNames(Dictionary<String, ?> config) {
    Set<String> set = new HashSet<String>();

    Enumeration<String> keys = config.keys();
    while (keys.hasMoreElements()) {

        String key = (String) keys.nextElement();

        // the config-key enumeration contains additional keys that we
        // don't want to process here ...
        if ("service.pid".equals(key) || "refresh".equals(key)) {
            continue;
        }/*from   ww  w .j  a  va2 s . c  om*/

        Matcher meterMatcher = METER_CONFIG_PATTERN.matcher(key);

        if (!meterMatcher.matches()) {
            logger.debug("given config key '" + key
                    + "' does not follow the expected pattern '<meterName>.<serialPort|baudRateChangeDelay|echoHandling>'");
            continue;
        }

        meterMatcher.reset();
        meterMatcher.find();

        set.add(meterMatcher.group(1));
    }
    return set;
}