Package java.util.regex

Examples of java.util.regex.Matcher


    // javascript:loadOrAlert('WVOPRHRPFSCLAW7UWHCXCH7QNQIU6TWG')

    // accept raw hash of 32 base-32 chars, with garbage around it
    if (accept_magnets && guess) {
      Pattern pattern = Pattern.compile("[^a-zA-Z2-7][a-zA-Z2-7]{32}[^a-zA-Z2-7]");
      Matcher matcher = pattern.matcher(text);
      if (matcher.find()) {
        String hash = text.substring(matcher.start() + 1, matcher.start() + 33);
        return "magnet:?xt=urn:btih:" + hash;
      }

      pattern = Pattern.compile("[^a-fA-F0-9][a-fA-F0-9]{40}[^a-fA-F0-9]");
      matcher = pattern.matcher(text);
      if (matcher.find()) {
        String hash = text.substring(matcher.start() + 1, matcher.start() + 41);
        // convert from HEX to raw bytes
        byte[] infohash = ByteFormatter.decodeString(hash.toUpperCase());
        // convert to BASE32
        return "magnet:?xt=urn:btih:" + Base32.encode(infohash);
      }


    if (text.matches("^[a-zA-Z2-7]{32}$")) {
      return "magnet:?xt=urn:btih:" + text;
    }
   
    Pattern pattern;
    Matcher matcher;

    pattern = Pattern.compile("bc://bt/([a-z0-9=\\+/]+)", Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(text.replaceAll(" ", "+"));
    if (matcher.find()) {
      String base64 = matcher.group(1);
      byte[] decode = Base64.decode(base64);
      if (decode != null && decode.length > 0) {
        // Format is AA/<name>/<size>/<hash>/ZZ
        try {
          String decodeString = new String(decode, "utf8");
          pattern = Pattern.compile("AA.*/(.*)/ZZ", Pattern.CASE_INSENSITIVE);
          matcher = pattern.matcher(decodeString);
          if (matcher.find()) {
            String hash = matcher.group(1);
            String magnet = parseTextForMagnets(hash);
            if (magnet != null) {
              pattern = Pattern.compile("AA/(.*)/[0-9]+", Pattern.CASE_INSENSITIVE);
              matcher = pattern.matcher(decodeString);
              if (matcher.find()) {
                String name = matcher.group(1);
                return magnet + "&dn=" + encode(name);
              }
              return magnet;
            }
          }
        } catch (UnsupportedEncodingException e) {
        }
      }
    }

    pattern = Pattern.compile("bctp://task/(.*)", Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(text);
    if (matcher.find()) {
      // Format is <name>/<size>/<hash>
      String decodeString = matcher.group(1);
      String magnet = parseTextForMagnets(decodeString);
      if (magnet != null) {
        pattern = Pattern.compile("(.*)/[0-9]+", Pattern.CASE_INSENSITIVE);
        matcher = pattern.matcher(decodeString);
        if (matcher.find()) {
          String name = matcher.group(1);
          return magnet + "&dn=" + encode(name);
        }
        return magnet;
      }
    }

    // accept raw hash of 32 base-32 chars, with garbage around it
    if (true) {
      text = "!" + text + "!";
      pattern = Pattern.compile("[^a-zA-Z2-7][a-zA-Z2-7]{32}[^a-zA-Z2-7]");
      matcher = pattern.matcher(text);
      if (matcher.find()) {
        String hash = text.substring(matcher.start() + 1, matcher.start() + 33);
        return "magnet:?xt=urn:btih:" + hash;
      }

      pattern = Pattern.compile("[^a-fA-F0-9][a-fA-F0-9]{40}[^a-fA-F0-9]");
      matcher = pattern.matcher(text);
      if (matcher.find()) {
        String hash = text.substring(matcher.start() + 1, matcher.start() + 41);
        // convert from HEX to raw bytes
        byte[] infohash = ByteFormatter.decodeString(hash.toUpperCase());
        // convert to BASE32
        return "magnet:?xt=urn:btih:" + Base32.encode(infohash);
      }

    // <A style=cow HREF="http://abc.om/moo">test</a>
    // <a href="http://www.gnu.org/licenses/fdl.html" target="_top">moo</a>

    Pattern pat = Pattern.compile("<.*a\\s++.*href=\"?([^\\'\"\\s>]++).*",
        Pattern.CASE_INSENSITIVE);
    Matcher m = pat.matcher(text);
    if (m.find()) {
      String sURL = m.group(1);
      try {
        sURL = URLDecoder.decode(sURL);
      } catch (Exception e) {
        // sometimes fires a IllegalArgumentException
        // catch everything and ignore.

          int currentIndex = ((Integer) thisIndexIterator.next()).intValue();
          String fieldValue = String.valueOf(rowData.get(currentIndex - 1));

          if (fieldValue != null) {
            Pattern pattern = Pattern.compile("[^a-zA-z_0-9 ]");
            Matcher fieldMatch = pattern.matcher(fieldValue);
            fieldValue = fieldMatch.replaceAll("");
            // fieldValue = fieldValue.replaceAll("'","");
          }

          if (fieldValue == null || fieldValue.equals("null")) {
            fieldValue = "";

        resetExecutionState();
        if (logger.isLoggable(Level.FINER)) {
      logger.finer("Executing: requestID " + getCurrentRequestID() + " commands: " + Arrays.toString(commands) + " expecting: " + resultsMode); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    }
        if (commands.length == 1) {
          Matcher match = SET_STATEMENT.matcher(commands[0]);
          if (match.matches()) {
            if (resultsMode == ResultsMode.RESULTSET) {
              throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.set_result_set")); //$NON-NLS-1$
            }
            String key = match.group(1);
            String value = match.group(2);
            if (ExecutionProperties.NEWINSTANCE.equalsIgnoreCase(key) && Boolean.valueOf(value)) {
              this.getMMConnection().getServerConnection().cleanUp();
            } else {
              JDBCURL.addNormalizedProperty(key, value, this.driverConnection.getExecutionProperties());
            }
            this.updateCounts = new int[] {0};
            return booleanFuture(true);
          }
          match = TRANSACTION_STATEMENT.matcher(commands[0]);
          if (match.matches()) {
          logger.finer("Executing as transaction statement"); //$NON-NLS-1$
            if (resultsMode == ResultsMode.RESULTSET) {
              throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.set_result_set")); //$NON-NLS-1$
            }
            String command = match.group(1);
            Boolean commit = null;
            if (StringUtil.startsWithIgnoreCase(command, "start")) { //$NON-NLS-1$
              //TODO: this should force a start and through an exception if we're already in a txn
              this.getConnection().setAutoCommit(false);
            } else if (command.equalsIgnoreCase("commit")) { //$NON-NLS-1$
              commit = true;
              if (synch) {
                this.getConnection().setAutoCommit(true);
              }
            } else if (command.equalsIgnoreCase("rollback")) { //$NON-NLS-1$
              commit = false;
              if (synch) {
                this.getConnection().rollback(false);
              }
            }
            this.updateCounts = new int[] {0};
            if (commit != null && !synch) {
              ResultsFuture<?> pending = this.getConnection().submitSetAutoCommitTrue(commit);
              final ResultsFuture<Boolean> result = new ResultsFuture<Boolean>();
              pending.addCompletionListener(new ResultsFuture.CompletionListener() {
                @Override
                public void onCompletion(ResultsFuture future) {
                  try {
                future.get();
                result.getResultsReceiver().receiveResults(false);
              } catch (Throwable t) {
                result.getResultsReceiver().exceptionOccurred(t);
              }
                }
          });
              return result;
            }
            return booleanFuture(false);
          }
          match = SHOW_STATEMENT.matcher(commands[0]);
          if (match.matches()) {
          logger.finer("Executing as show statement"); //$NON-NLS-1$
            if (resultsMode == ResultsMode.UPDATECOUNT) {
              throw new TeiidSQLException(JDBCPlugin.Util.getString("StatementImpl.show_update_count")); //$NON-NLS-1$
            }
            String show = match.group(1);
            if (show.equalsIgnoreCase("PLAN")) { //$NON-NLS-1$
              List<ArrayList<Object>> records = new ArrayList<ArrayList<Object>>(1);
              PlanNode plan = driverConnection.getCurrentPlanDescription();
              if (plan != null) {
                ArrayList<Object> row = new ArrayList<Object>(3);

                continue;

            // special treatment for function keys
            if(!funcVisited)
            {
                final Matcher funcMatcher = FUNC_EXP.matcher(value);
                if(funcMatcher.find() && funcMatcher.start() == 0 && funcMatcher.end() == value.length())
                {
                    final int funcVal = Integer.parseInt(funcMatcher.group(2));

                    // SWT.F1 is (1 << 24) + 10
                    swtAccelerator = swtAccelerator | ((1 << 24) + (9 + funcVal));
                    displayValue.append(funcMatcher.group(0)).append(DELIM);

                    funcVisited = true;
                    matched = true;
                }
            }

            if(matched)
                continue;

            final Matcher valMatcher = SANCTIONED_EXP.matcher(value);
            if(valMatcher.find() && valMatcher.start() == 0)
            {
                final char c = valMatcher.group().charAt(0);

                // avoid possible duplicates (\t is index 0)
                final int subStrIndex = displayValue.indexOf(c + DELIM);
                if(subStrIndex == 1 || (subStrIndex > 1 && displayValue.substring(subStrIndex - 1, subStrIndex).equals(DELIM)))
                    continue;

        }
        return _literal;
    }

    public static XsDuration valueOf(String literal) throws XQueryException {
        final Matcher match = DURATION_PATTERN.matcher(literal);
        if(!match.matches()) {
            throw new DynamicError("err:FORG0001", "Illegal representation as xs:duration: "
                    + literal);
        }

        final String y, mo, d;
        int year = ((y = match.group(2)) == null) ? 0 : Integer.parseInt(y);
        int month = ((mo = match.group(4)) == null) ? 0 : Integer.parseInt(mo);
        int day = ((d = match.group(6)) == null) ? 0 : Integer.parseInt(d);
        String x;
        int hour = ((x = match.group(9)) == null) ? 0 : Integer.parseInt(x);
        int minute = ((x = match.group(11)) == null) ? 0 : Integer.parseInt(x);
        int sec = ((x = match.group(13)) == null) ? 0 : Integer.parseInt(x);

        final boolean neg = (match.group(1) != null);
        final int months = year * 12 + month;
        final long seconds = (day * SECONDS_PER_DATE_L) + (hour * 3600) + (minute * 60) + sec;
        final double milsec = ((x = match.group(15)) == null) ? 0d : Double.parseDouble(x);

        final XsDuration dur = new XsDuration(neg, months, seconds, milsec);
        dur._hasYearMonth = (y != null) || (mo != null);
        dur._hasDayTime = (d != null) || (match.group(8) != null);
        return dur;
    }

    }
    // selects are coming with "select\t" so using a space after "select" does not always work
    if (StringUtil.startsWithIgnoreCase(sql, "select")) { //$NON-NLS-1$
      modified = sql.replace('\n', ' ');
                   
      Matcher m = null;
      if ((m = pkPattern.matcher(modified)).matches()) {
        return new StringBuffer("SELECT k.Name AS attname, convert(Position, short) AS attnum, TableName AS relname, SchemaName AS nspname, TableName AS relname") //$NON-NLS-1$
                .append(" FROM SYS.KeyColumns k") //$NON-NLS-1$
                .append(" WHERE ") //$NON-NLS-1$
                .append(" UCASE(SchemaName)").append(" LIKE UCASE(").append(m.group(2)).append(")")//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                .append(" AND UCASE(TableName)") .append(" LIKE UCASE(").append(m.group(1)).append(")")//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                .append(" AND KeyType LIKE 'Primary'") //$NON-NLS-1$
                .append(" ORDER BY attnum").toString(); //$NON-NLS-1$         
      }
      else if ((m = pkKeyPattern.matcher(modified)).matches()) {
        String tableName = m.group(1);
        if (tableName.endsWith("_pkey'")) { //$NON-NLS-1$
          tableName = tableName.substring(0, tableName.length()-6) + '\'';
          return "select ia.attname, ia.attnum, ic.relname, n.nspname, NULL "+ //$NON-NLS-1$ 
            "from pg_catalog.pg_attribute ia, pg_catalog.pg_class ic, pg_catalog.pg_namespace n, Sys.KeyColumns kc "+ //$NON-NLS-1$ 
            "where ic.relname = "+tableName+" AND n.nspname = "+m.group(2)+" AND "+ //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            "n.oid = ic.relnamespace AND ia.attrelid = ic.oid AND kc.SchemaName = n.nspname " +//$NON-NLS-1$ 
            "AND kc.TableName = ic.relname AND kc.KeyType = 'Primary' AND kc.Name = ia.attname order by ia.attnum";//$NON-NLS-1$ 
        }
        return "SELECT NULL, NULL, NULL, NULL, NULL FROM (SELECT 1) as X WHERE 0=1"; //$NON-NLS-1$
      }
      else if ((m = fkPattern.matcher(modified)).matches()){
        return "SELECT PKTABLE_CAT, PKTABLE_SCHEM, PKTABLE_NAME, PKCOLUMN_NAME, FKTABLE_CAT, FKTABLE_SCHEM, "+//$NON-NLS-1$
              "FKTABLE_NAME, FKCOLUMN_NAME, KEY_SEQ, UPDATE_RULE, DELETE_RULE, FK_NAME, PK_NAME, DEFERRABILITY "+//$NON-NLS-1$
              "FROM SYS.ReferenceKeyColumns WHERE PKTABLE_NAME LIKE "+m.group(14)+" and PKTABLE_SCHEM LIKE "+m.group(15);//$NON-NLS-1$ //$NON-NLS-2$
      }
      else if (modified.equalsIgnoreCase("select version()")) { //$NON-NLS-1$
        return "SELECT 'Teiid "+ApplicationInfo.getInstance().getReleaseNumber()+"'"; //$NON-NLS-1$ //$NON-NLS-2$
      }
      else if (modified.startsWith("SELECT name FROM master..sysdatabases")) { //$NON-NLS-1$
        return "SELECT 'Teiid'"; //$NON-NLS-1$
      }
      else if (modified.equalsIgnoreCase("select db_name() dbname")) { //$NON-NLS-1$
        return "SELECT current_database()"; //$NON-NLS-1$
      }
      else if (preparedAutoIncrement.matcher(modified).matches()) {
        return "SELECT 1 from matpg_relatt where attrelid = ? and attnum = ? and autoinc = true"; //$NON-NLS-1$
      }
      else {
        // since teiid can work with multiple schemas at a given time
        // this call resolution is ambiguous
        if (sql.equalsIgnoreCase("select current_schema()")) { //$NON-NLS-1$
          return "SELECT ''"//$NON-NLS-1$
        }             
      }
     
    }
    else if (sql.equalsIgnoreCase("show max_identifier_length")){ //$NON-NLS-1$
      return "select 63"; //$NON-NLS-1$
    }
    else {
      Matcher m = setPattern.matcher(sql);
      if (m.matches()) {
        return "SET " + m.group(2) + " " + m.group(4); //$NON-NLS-1$ //$NON-NLS-2$
      }
      else if (modified.equalsIgnoreCase("BEGIN")) { //$NON-NLS-1$
        return "START TRANSACTION"; //$NON-NLS-1$
      }
      else if ((m = rollbackPattern.matcher(modified)).matches()) {
        return "ROLLBACK"; //$NON-NLS-1$
     
      else if ((m = savepointPattern.matcher(modified)).matches()) {
        return "SELECT 'SAVEPOINT'"; //$NON-NLS-1$
      }
      else if ((m = releasePattern.matcher(modified)).matches()) {
        return "SELECT 'RELEASE'"; //$NON-NLS-1$
      }   
      else if ((m = deallocatePattern.matcher(modified)).matches()) {
        closePreparedStatement(m.group(1));
        return "SELECT 'DEALLOCATE'"; //$NON-NLS-1$
      }         
    }
    modified = sql;
    //these are somewhat dangerous

   * @return
   */
  public static boolean mkdirs(File f) {
    if (Constants.isOSX) {
      Pattern pat = Pattern.compile("^(/Volumes/[^/]+)");
      Matcher matcher = pat.matcher(f.getParent());
      if (matcher.find()) {
        String sVolume = matcher.group();
        File fVolume = new File(sVolume);
        if (!fVolume.isDirectory()) {
          Logger.log(new LogEvent(LOGID, LogEvent.LT_WARNING, sVolume
              + " is not mounted or not available."));
          return false;

        "title",
        "dn"
      };
      // magnet:?xt=urn:btih:WENBTYBB7676MQWJ7NLTD4NGYDKYSQPO&dn=[DmzJ][School_Days][Vol.01-06][DVDRip]
      for (String toMatch : titles) {
        Matcher matcher = Pattern.compile("[?&]" + toMatch + "=(.*)&?",
            Pattern.CASE_INSENSITIVE).matcher(url);
        if (matcher.find()) {
          return matcher.group(1);
        }
      }
     
      /*
       * If no 'title' field was found then just get the file name instead

TOP

Related Classes of java.util.regex.Matcher

Copyright © 2015 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.