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.openhab.binding.iec6205621meter.internal.Iec6205621MeterBinding.java

/**
 * Analyze configuration to get meter names
 * //  ww  w  .j  av a2  s.  c om
 * @return set of String of meter names
 */
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;
        }

        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;
}

From source file:org.openhab.binding.exec.handler.ExecHandler.java

/**
 * Splits a transformation configuration string into its two parts - the
 * transformation type and the function/pattern to apply.
 *
 * @param transformation the string to split
 * @return a string array with exactly two entries for the type and the function
 *//*from  ww  w.  jav  a 2 s .c om*/
protected String[] splitTransformationConfig(String transformation) {
    Matcher matcher = EXTRACT_FUNCTION_PATTERN.matcher(transformation);

    if (!matcher.matches()) {
        throw new IllegalArgumentException("given transformation function '" + transformation
                + "' does not follow the expected pattern '<function>(<pattern>)'");
    }
    matcher.reset();

    matcher.find();
    String type = matcher.group(1);
    String pattern = matcher.group(2);

    return new String[] { type, pattern };
}

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

@Override
protected DataAccessException customTranslate(String task, String sql, SQLException sqlEx) {
    //TODO ARRUMAR ESSA ALGORITMO (FAZER HIGH COHESION.. LOW COUPLING)
    //System.out.println(task+" - "+sql);
    if (sqlEx.getNextException() != null) {
        sqlEx = sqlEx.getNextException();//tentar buscar a excecao mais especifica
    }//from  w w  w  .  j av  a 2 s  .c o m
    String errorMessage = sqlEx.getMessage();
    Matcher matcher = pattern.matcher(errorMessage);
    Matcher matcherIngles = patternIngles.matcher(errorMessage);
    Matcher matcherNullIngles = patternInglesNull.matcher(errorMessage);
    Matcher matcherNull = patternNull.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(2);
        String fk_table_name = matcher.group(3).toUpperCase();
        String pk_table_name = matcher.group(1).toUpperCase();
        String fkTableDisplayName = null;
        String pkTableDisplayName = null;
        //         try {
        //            DatabaseMetaData metaData = dataSource.getConnection().getMetaData();
        //            ResultSet importedKeys = metaData.getImportedKeys(null,null, fk_table_name);
        //            
        //            while(importedKeys.next()){
        //               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();
        //                  }
        //               }
        //            }
        //         } 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;
        //         }

        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 if (matcherNullIngles.find()) {
        return new ApplicationDatabaseException(errorMessage);
    } else if (matcherNull.find()) {
        return new ApplicationDatabaseException(errorMessage);
    } else {
        int indexOf = errorMessage.indexOf("APP");
        if (indexOf > 0) {
            errorMessage = errorMessage.substring(indexOf + 3);
            return new ApplicationDatabaseException(errorMessage);
        }
    }
    return null;
}

From source file:com.npower.dm.hibernate.management.DDFTreeManagementBeanImpl.java

public DDFNode findDDFNode(Set<DDFNode> rootNodesSet, String nodePath) {
    for (Iterator<DDFNode> nodes = rootNodesSet.iterator(); nodes.hasNext();) {
        DDFNode node = (DDFNode) nodes.next();
        if (nodePath.equals(node.getName())) {
            return node;
        }/*  ww  w  . j  av  a  2  s .c om*/
        Matcher matcher = DDFTreeHelper.DynamicNamePattern.matcher(nodePath);
        boolean equals = matcher.matches();
        matcher.reset();
        boolean found = matcher.find();
        boolean startWith = false;
        if (found) {
            int index = matcher.start();
            startWith = (index == 0) ? true : false;
        }

        if (equals && (node.getName() == null || node.getName().trim().length() == 0)) {
            return node;
        } else if (node.getName() == null || node.getName().trim().length() == 0) {
            if (startWith) {
                return findDDFNode(node.getChildren(),
                        nodePath.substring(nodePath.indexOf("/") + 1, nodePath.length()));
            } else {
                continue;
            }
        } else if (nodePath.startsWith(node.getName() + "/")) {
            return findDDFNode(node.getChildren(),
                    nodePath.substring(nodePath.indexOf("/") + 1, nodePath.length()));
        }
    }
    return null;
}

From source file:com.seajas.search.contender.service.modifier.ModifierFilterProcessor.java

/**
 * Process the given reader using this filter.
 * //from   w w w.  j  a va  2 s .c  o m
 * @param filter
 * @param reader
 * @return Reader
 * @throws IOException
 */
public Reader process(final ModifierFilter filter, final Reader reader) throws IOException {
    StringBuffer stringBuffer = new StringBuffer();

    for (int c; (c = reader.read()) != -1;)
        stringBuffer.append((char) c);

    reader.close();

    if (!filter.getIsExpression()) {
        Pattern pattern = Pattern.compile(
                Pattern.quote(filter.getFragmentStart()) + ".*" + Pattern.quote(filter.getFragmentEnd()),
                Pattern.DOTALL | Pattern.CASE_INSENSITIVE);

        return new StringReader(
                pattern.matcher(stringBuffer).replaceAll(filter.getFragmentStart() + filter.getFragmentEnd()));
    } else {
        Matcher startMatcher = Pattern.compile(filter.getFragmentStart(), Pattern.CASE_INSENSITIVE)
                .matcher(stringBuffer),
                endMatcher = Pattern.compile(filter.getFragmentEnd(), Pattern.CASE_INSENSITIVE)
                        .matcher(stringBuffer);

        while (startMatcher.find() && endMatcher.find(startMatcher.end()))
            if (startMatcher.end() != endMatcher.start()) {
                stringBuffer.delete(startMatcher.end(), endMatcher.start());

                startMatcher.reset();
                endMatcher.reset();
            }

        // Store the result

        return new StringReader(stringBuffer.toString());
    }
}

From source file:org.openhab.binding.exec.internal.ExecGenericBindingProvider.java

protected ExecBindingConfig parseInBindingConfig(Item item, String bindingConfig, ExecBindingConfig config)
        throws BindingConfigParseException {

    Matcher matcher = IN_BINDING_PATTERN.matcher(bindingConfig);

    if (!matcher.matches()) {
        throw new BindingConfigParseException(
                "bindingConfig '" + bindingConfig + "' doesn't represent a valid in-binding-configuration.");
    }/*from  www.  j  a va  2s  .  com*/
    matcher.reset();

    ExecBindingConfigElement configElement;

    while (matcher.find()) {
        configElement = new ExecBindingConfigElement();
        configElement.commandLine = matcher.group(1).replaceAll("\\\\\"", "");
        configElement.refreshInterval = Integer.valueOf(matcher.group(2)).intValue();
        configElement.transformation = matcher.group(3).replaceAll("\\\\\"", "\"");
        config.put(IN_BINDING_KEY, configElement);
    }

    return config;
}

From source file:org.openhab.binding.exec.internal.ExecGenericBindingProvider.java

protected ExecBindingConfig parseOutBindingConfig(Item item, String bindingConfig, ExecBindingConfig config)
        throws BindingConfigParseException {

    Matcher matcher = OUT_BINDING_PATTERN.matcher(bindingConfig);

    if (!matcher.matches()) {
        throw new BindingConfigParseException(
                "bindingConfig '" + bindingConfig + "' doesn't represent a valid in-binding-configuration.");
    }/*from  w ww  . j a  v  a  2 s.  c  om*/
    matcher.reset();

    ExecBindingConfigElement configElement;

    while (matcher.find()) {
        Command command = createCommandFromString(item, matcher.group(1));

        configElement = new ExecBindingConfigElement();
        configElement.commandLine = matcher.group(2).replaceAll("\\\\\"", "");

        config.put(command, configElement);
    }

    return config;
}

From source file:org.openhab.persistence.jdbc.internal.JdbcConfiguration.java

/**
 * @{inheritDoc/*from ww w  .  j a v  a2s. c  o  m*/
 */
public void updateConfig(Map<Object, Object> configuration) {
    logger.debug("JDBC::updateConfig: configuration.size = " + configuration.size());

    // Database-Url jdbc:h2:./testH2
    String url = (String) configuration.get("url");
    Properties parsedURL = StringUtilsExt.parseJdbcURL(url);
    logger.debug("JDBC::updateConfig: url={}", url);
    if (StringUtils.isBlank(url) || parsedURL.getProperty("parseValid") == "false") {
        logger.error(
                "JDBC::updateConfig: url The SQL database URL is missing - please configure the jdbc:url parameter in openhab.cfg");
    } else {
        dbName = parsedURL.getProperty("databaseName");
    }

    // Which DB-Type to use
    serviceName = parsedURL.getProperty("dbShortcut"); // derby, h2, hsqldb, mariadb, mysql, postgresql, sqlite
    logger.debug("JDBC::updateConfig: found serviceName = '{}'", serviceName);
    if (StringUtils.isBlank(serviceName) || serviceName.length() < 2) {
        serviceName = "no";
        logger.error(
                "JDBC::updateConfig: url Required database url like 'jdbc:<service>:<host>[:<port>;<attributes>]' - please configure the jdbc:url parameter in openhab.cfg");
    }

    // DB Class
    String ddp = DB_DAO_PACKAGE + serviceName.toUpperCase().charAt(0) + serviceName.toLowerCase().substring(1)
            + "DAO";

    logger.debug("JDBC::updateConfig: Init Data Access Object Class: '{}'", ddp);
    try {

        dBDAO = (JdbcBaseDAO) Class.forName(ddp).newInstance();
        // dBDAO.databaseProps.setProperty("jdbcUrl", url);
        // dBDAO.databaseProps.setProperty("dataSource.url", url);

        logger.debug("JDBC::updateConfig: dBDAO ClassName={}", dBDAO.getClass().getName());
    } catch (InstantiationException e) {
        logger.error("JDBC::updateConfig: InstantiationException: {}", e.getMessage());
    } catch (IllegalAccessException e) {
        logger.error("JDBC::updateConfig: IllegalAccessException: {}", e.getMessage());
    } catch (ClassNotFoundException e) {
        logger.warn(
                "JDBC::updateConfig: no Configuration for serviceName '{}' found. ClassNotFoundException: {}",
                serviceName, e.getMessage());
        logger.debug("JDBC::updateConfig: using default Database Configuration: JdbcBaseDAO !!");
        dBDAO = new JdbcBaseDAO();
        logger.debug("JDBC::updateConfig: dBConfig done");
    }

    @SuppressWarnings("unchecked")
    Enumeration<String> keys = new IteratorEnumeration(configuration.keySet().iterator());

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

        Matcher matcher = EXTRACT_CONFIG_PATTERN.matcher(key);

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

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

        if (!matcher.group(1).equals("sqltype"))
            continue;

        String itemType = matcher.group(2).toUpperCase() + "ITEM";
        String value = (String) configuration.get(key);

        logger.debug("JDBC::updateConfig: set sqlTypes: itemType={} value={}", itemType, value);
        dBDAO.sqlTypes.put(itemType, value);
    }

    String user = (String) configuration.get("user");
    logger.debug("JDBC::updateConfig:  user={}", user);
    if (StringUtils.isBlank(user)) {
        logger.error(
                "JDBC::updateConfig: SQL user is missing - please configure the jdbc:user parameter in openhab.cfg");
    } else {
        dBDAO.databaseProps.setProperty("dataSource.user", user);
    }

    String password = (String) configuration.get("password");
    if (StringUtils.isBlank(password)) {
        logger.error("JDBC::updateConfig: SQL password is missing. Attempting to connect without password. "
                + "To specify a password configure the jdbc:password parameter in openhab.cfg.");
    } else {
        logger.debug("JDBC::updateConfig:  password=<masked> password.length={}", password.length());
        dBDAO.databaseProps.setProperty("dataSource.password", password);
    }

    String et = (String) configuration.get("reconnectCnt");
    if (StringUtils.isNotBlank(et)) {
        errReconnectThreshold = Integer.parseInt(et);
        logger.debug("JDBC::updateConfig: errReconnectThreshold={}", errReconnectThreshold);
    }

    String np = (String) configuration.get("tableNamePrefix");
    if (StringUtils.isNotBlank(np)) {
        dBDAO.databaseProps.setProperty("tableNamePrefix", np);
    }

    String dd = (String) configuration.get("numberDecimalcount");
    if (StringUtils.isNotBlank(dd)) {
        numberDecimalcount = Integer.parseInt(dd);
        logger.debug("JDBC::updateConfig: numberDecimalcount={}", numberDecimalcount);
    }

    String rn = (String) configuration.get("tableUseRealItemNames");
    if (StringUtils.isNotBlank(rn)) {
        tableUseRealItemNames = "true".equals(rn) ? Boolean.parseBoolean(rn) : false;
        logger.debug("JDBC::updateConfig: tableUseRealItemNames={}", tableUseRealItemNames);
    }

    String td = (String) configuration.get("tableIdDigitCount");
    if (StringUtils.isNotBlank(td)) {
        tableIdDigitCount = Integer.parseInt(td);
        logger.debug("JDBC::updateConfig: tableIdDigitCount={}", tableIdDigitCount);
    }

    String rt = (String) configuration.get("rebuildTableNames");
    if (StringUtils.isNotBlank(rt)) {
        rebuildTableNames = "true".equals(rt) ? Boolean.parseBoolean(rt) : false;
        logger.debug("JDBC::updateConfig: rebuildTableNames={}", rebuildTableNames);
    }
    // undocumented
    String ac = (String) configuration.get("maximumPoolSize");
    if (StringUtils.isNotBlank(ac)) {
        dBDAO.databaseProps.setProperty("maximumPoolSize", ac);
    }
    // undocumented
    String ic = (String) configuration.get("minimumIdle");
    if (StringUtils.isNotBlank(ic)) {
        dBDAO.databaseProps.setProperty("minimumIdle", ic);
    }
    // undocumented
    String it = (String) configuration.get("idleTimeout");
    if (StringUtils.isNotBlank(it)) {
        dBDAO.databaseProps.setProperty("idleTimeout", it);
    }
    // undocumented
    String ent = (String) configuration.get("enableLogTime");
    if (StringUtils.isNotBlank(ent)) {
        enableLogTime = "true".equals(ent) ? Boolean.parseBoolean(ent) : false;
    }
    logger.debug("JDBC::updateConfig: enableLogTime {}", enableLogTime);

    // undocumented
    String fd = (String) configuration.get("driverClassName");
    if (StringUtils.isNotBlank(fd)) {
        dBDAO.databaseProps.setProperty("driverClassName", fd);
    }
    // undocumented
    String ds = (String) configuration.get("dataSourceClassName");
    if (StringUtils.isNotBlank(ds)) {
        dBDAO.databaseProps.setProperty("dataSourceClassName", ds);
    }

    driverAvailable = true;
    String dn = dBDAO.databaseProps.getProperty("driverClassName");
    if (dn == null) {
        dn = dBDAO.databaseProps.getProperty("dataSourceClassName");
    } else {
        dBDAO.databaseProps.setProperty("jdbcUrl", url);
    }

    logger.warn("JDBC::updateConfig: try to load JDBC-driverClass: '{}'", dn);
    try {
        Class.forName(dn);
        logger.debug("JDBC::updateConfig: load JDBC-driverClass was successful: '{}'", dn);
    } catch (ClassNotFoundException e) {
        driverAvailable = false;
        logger.error(
                "JDBC::updateConfig: could NOT load JDBC-driverClassName or JDBC-dataSourceClassName ClassNotFoundException: '{}'",
                e.getMessage());
        String warn = ""
                + "\n\n\t!!!\n\tTo avoid this error, place a appropriate JDBC driver file for serviceName '{}' in addons directory.\n"
                + "\tCopy missing JDBC-Driver-jar to your OpenHab/addons Folder.\n\t!!!\n" + "\tDOWNLOAD: \n";
        if (serviceName.equals("derby"))
            warn += "\tDerby:     version >= 10.11.1.1 from          http://mvnrepository.com/artifact/org.apache.derby/derby\n";
        else if (serviceName.equals("h2"))
            warn += "\tH2:        version >= 1.4.189 from            http://mvnrepository.com/artifact/com.h2database/h2\n";
        else if (serviceName.equals("hsqldb"))
            warn += "\tHSQLDB:    version >= 2.3.3 from              http://mvnrepository.com/artifact/org.hsqldb/hsqldb\n";
        else if (serviceName.equals("mariadb"))
            warn += "\tMariaDB:   version >= 1.2.0 from              http://mvnrepository.com/artifact/org.mariadb.jdbc/mariadb-java-client\n";
        else if (serviceName.equals("mysql"))
            warn += "\tMySQL:     version >= 5.1.36 from             http://mvnrepository.com/artifact/mysql/mysql-connector-java\n";
        else if (serviceName.equals("postgresql"))
            warn += "\tPostgreSQL:version >= 9.4-1201-jdbc41 from    http://mvnrepository.com/artifact/org.postgresql/postgresql\n";
        else if (serviceName.equals("sqlite"))
            warn += "\tSQLite:    version >= 3.8.11.2 from           http://mvnrepository.com/artifact/org.xerial/sqlite-jdbc\n";
        logger.warn(warn, serviceName);
    }

    logger.debug("JDBC::updateConfig: configuration complete. service={}", getName());
}

From source file:org.openhab.binding.lutron.internal.LutronGenericBindingProvider.java

/**
 * {@inheritDoc}//w  w w  . java2  s . c  o  m
 */
@Override
public void processBindingConfiguration(String context, Item item, String bindingConfig)
        throws BindingConfigParseException {
    super.processBindingConfiguration(context, item, bindingConfig);

    if (bindingConfig != null) {
        LutronBindingConfig newConfig = new LutronBindingConfig();
        Matcher matcher = BASE_CONFIG_PATTERN.matcher(bindingConfig);

        if (!matcher.matches()) {
            throw new BindingConfigParseException(
                    "bindingConfig '" + bindingConfig + "' doesn't contain a valid binding configuration");
        }
        matcher.reset();

        while (matcher.find()) {
            String bindingConfigPart = matcher.group(1);
            if (StringUtils.isNotBlank(bindingConfigPart)) {
                parseBindingConfig(newConfig, item, bindingConfigPart);
            }
        }

        addBindingConfig(item, newConfig);
    } else {
        logger.warn("bindingConfig is NULL (item=" + item + ") -> processing bindingConfig aborted!");
    }
}

From source file:org.openhab.binding.tcp.protocol.internal.ProtocolGenericBindingProvider.java

private void parseAndAddBindingConfig(Item item, String bindingConfig) throws BindingConfigParseException {
    ProtocolBindingConfig newConfig = new ProtocolBindingConfig();
    Matcher matcher = BASE_CONFIG_PATTERN.matcher(bindingConfig);

    if (!matcher.matches()) {
        throw new BindingConfigParseException(
                "bindingConfig '" + bindingConfig + "' doesn't contain a valid binding configuration");
    }/*ww w  . j  a v a2  s.co  m*/
    matcher.reset();

    while (matcher.find()) {
        String bindingConfigPart = matcher.group(1);
        if (StringUtils.isNotBlank(bindingConfigPart)) {
            parseBindingConfig(newConfig, item, bindingConfigPart);
            addBindingConfig(item, newConfig);
        }
    }
}