Beispiel #1
0
  public static VoiceCommand fromString(String str) {
    Log.v(TAG, "Checking against string: " + str);

    for (CommandAction command : CommandAction.values()) {
      Pattern pat = Pattern.compile(command.regex());
      Matcher mat = pat.matcher(str);

      boolean matchesMain = mat.matches();
      if (matchesMain) {
        Log.v(TAG, "Found match for user command: " + command.regex());
      }

      Pattern patAlt = Pattern.compile(command.regexAlt());
      Matcher matAlt = patAlt.matcher(str);

      boolean matchesAlt = matAlt.matches();
      if (matchesAlt) {
        Log.v(TAG, "Found match for user command: " + command.regexAlt());
      }

      // TODO
      // Integrate the matchesAlt with that.
      // It's useful information.
      if ((matchesMain && !command.forceAlt) || (matchesAlt && !command.forceKeyword)) {
        return new VoiceCommand(command, mat, matAlt, matchesMain, matchesAlt, command.textGroup);
      }
    }

    return new VoiceCommand(UNRECOGNIZED);
  }
  /**
   * Compares the two specified upgrade script strings to determine their relative ordering
   * considering their two version numbers. Assumes all database names used are the same, as this
   * function only compares the two version numbers.
   *
   * @param file0 an upgrade script file name
   * @param file1 a second upgrade script file name to compare with file0
   * @return an integer < 0 if file0 should be applied before file1, 0 if they are equal (though
   *     that shouldn't happen), and > 0 if file0 should be applied after file1.
   * @exception SQLiteAssetHelper.SQLiteAssetException thrown if the strings are not in the correct
   *     upgrade script format of: <code>databasename_fromVersionInteger_toVersionInteger</code>
   */
  @Override
  public int compare(String file0, String file1) {
    Matcher m0 = pattern.matcher(file0);
    Matcher m1 = pattern.matcher(file1);

    if (!m0.matches()) {
      Log.w(TAG, "could not parse upgrade script file: " + file0);
      throw new SQLiteAssetHelper.SQLiteAssetException("Invalid upgrade script file");
    }

    if (!m1.matches()) {
      Log.w(TAG, "could not parse upgrade script file: " + file1);
      throw new SQLiteAssetHelper.SQLiteAssetException("Invalid upgrade script file");
    }

    int v0_from = Integer.valueOf(m0.group(1));
    int v1_from = Integer.valueOf(m1.group(1));
    int v0_to = Integer.valueOf(m0.group(2));
    int v1_to = Integer.valueOf(m1.group(2));

    if (v0_from == v1_from) {
      // 'from' versions match for both; check 'to' version next

      if (v0_to == v1_to) {
        return 0;
      }

      return v0_to < v1_to ? -1 : 1;
    }

    return v0_from < v1_from ? -1 : 1;
  }
  private List<String> processArgs(String[] args) {
    // Args4j has a different format that the old command-line parser.
    // So we use some voodoo to get the args into the format that args4j
    // expects.
    Pattern argPattern = Pattern.compile("(--[a-zA-Z_]+)=(.*)");
    Pattern quotesPattern = Pattern.compile("^['\"](.*)['\"]$");
    List<String> processedArgs = Lists.newArrayList();

    for (String arg : args) {
      Matcher matcher = argPattern.matcher(arg);
      if (matcher.matches()) {
        processedArgs.add(matcher.group(1));

        String value = matcher.group(2);
        Matcher quotesMatcher = quotesPattern.matcher(value);
        if (quotesMatcher.matches()) {
          processedArgs.add(quotesMatcher.group(1));
        } else {
          processedArgs.add(value);
        }
      } else {
        processedArgs.add(arg);
      }
    }

    return processedArgs;
  }
  private Head readHead() {
    String headContent = tryLoadFile(myHeadFile, calcEncoding(myHeadFile));
    headContent =
        headContent.trim(); // remove possible leading and trailing spaces to clearly match regexps

    Matcher matcher = BRANCH_PATTERN.matcher(headContent);
    if (matcher.matches()) {
      return new Head(true, matcher.group(1));
    }

    if (COMMIT_PATTERN.matcher(headContent).matches()) {
      return new Head(false, headContent);
    }
    matcher = BRANCH_WEAK_PATTERN.matcher(headContent);
    if (matcher.matches()) {
      LOG.info(
          ".git/HEAD has not standard format: ["
              + headContent
              + "]. We've parsed branch ["
              + matcher.group(1)
              + "]");
      return new Head(true, matcher.group(1));
    }
    throw new GitRepoStateException("Invalid format of the .git/HEAD file: \n" + headContent);
  }
  @Test
  public void testMetadataRegex() {
    Matcher m =
        MavenProxyServletSupport.ARTIFACT_METADATA_URL_REGEX.matcher(
            "groupId/artifactId/version/maven-metadata.xml");
    assertTrue(m.matches());
    assertEquals("maven-metadata.xml", m.group(4));

    m =
        MavenProxyServletSupport.ARTIFACT_METADATA_URL_REGEX.matcher(
            "groupId/artifactId/version/maven-metadata-local.xml");
    assertTrue(m.matches());
    assertEquals("maven-metadata-local.xml", m.group(4));
    assertEquals("local", m.group(7));

    m =
        MavenProxyServletSupport.ARTIFACT_METADATA_URL_REGEX.matcher(
            "groupId/artifactId/version/maven-metadata-rep-1234.xml");
    assertTrue(m.matches());
    assertEquals("maven-metadata-rep-1234.xml", m.group(4));
    assertEquals("rep-1234", m.group(7));

    m =
        MavenProxyServletSupport.ARTIFACT_METADATA_URL_REGEX.matcher(
            "groupId/artifactId/version/maven-metadata.xml.md5");
    assertTrue(m.matches());
    assertEquals("maven-metadata.xml", m.group(4));
  }
  public void test_transparentBounds() {
    String testPattern = "and(?=roid)";
    String testString = "android";
    Pattern pat = Pattern.compile(testPattern);
    Matcher mat = pat.matcher(testString);

    mat.region(0, 3);
    mat.useTransparentBounds(false);
    assertFalse("Shouldn't find pattern with opaque bounds", mat.matches());

    mat.useTransparentBounds(true);
    assertTrue("Should find pattern transparent bounds", mat.matches()); // ***

    testPattern = "and(?!roid)";
    testString = "android";
    pat = Pattern.compile(testPattern);
    mat = pat.matcher(testString);

    mat.region(0, 3);
    mat.useTransparentBounds(false);
    assertTrue("Should find pattern with opaque bounds", mat.matches());

    mat.useTransparentBounds(true);
    assertFalse("Shouldn't find pattern transparent bounds", mat.matches()); // ***
  }
Beispiel #7
0
  public static String getAccStatus(MainExcel.AccountObj accountObj) throws Exception {
    String accountId = accountObj.id;
    String accountTokken = accountObj.token;
    String status = null;

    String uri;
    String response;

    uri = "https://vk.com/id" + accountId;
    response = (MainRequest.postRequest(uri, ""));

    Pattern pZam = Pattern.compile(".*<b>temporarily</b>.*");
    Matcher mZam = pZam.matcher(response);
    boolean temporarily = mZam.matches();

    Pattern pBan = Pattern.compile(".*<b>block</b>.*");
    Matcher mBan = pBan.matcher(response);
    boolean block = mBan.matches();

    if (temporarily == true) {
      status = "Зам";
    }

    if (block == true) {
      status = "Блок";
    }

    if ((temporarily == false) && (block == false)) {
      status = "Ok";
    }

    return status;
  }
 public void filterFile() {
   try (Stream<String> lines =
       Files.lines(Paths.get(INPUT_FILE_NAME), Charset.forName("ISO-8859-1"))) {
     lines
         .skip(startLine)
         .filter(
             line -> {
               Matcher m = PATTERN.matcher(line);
               return m.matches();
             })
         .map(
             line -> {
               Matcher m = PATTERN.matcher(line);
               m.matches();
               return m.group(1);
             })
         .filter(
             system -> {
               if (system.equals(currentSystem)) {
                 return false;
               } else {
                 currentSystem = system;
                 return true;
               }
             })
         .map(system -> "jumped to " + system)
         .forEach(System.out::println);
   } catch (IOException ioe) {
     System.out.println(ioe.toString());
   }
 }
 /**
  * Returns the selected schema version for the given URI.
  *
  * @param doc document object model of the XML source file
  * @param namespaceUri namespace URI to examine
  * @return selected schema version for the given URI
  */
 public static Version getSchemaVersion(IDOMDocument doc, String namespaceUri) {
   String versLocation = getSelectedSchemaLocation(doc, namespaceUri);
   Matcher matcher = VERSION_PATTERN.matcher(versLocation);
   if (matcher.matches()) {
     return new Version(matcher.group(1));
   } else {
     List<INamespaceDefinition> defs = NamespaceUtils.getNamespaceDefinitions();
     for (INamespaceDefinition def : defs) {
       Version version = Version.emptyVersion;
       if (namespaceUri.equals(def.getNamespaceURI())) {
         Version tempVersion = Version.emptyVersion;
         for (String location : def.getSchemaLocations()) {
           matcher = VERSION_PATTERN.matcher(location);
           if (matcher.matches()) {
             tempVersion = new Version(matcher.group(1));
           }
           if (tempVersion.compareTo(version) >= 0) {
             version = tempVersion;
           }
         }
         return version;
       }
     }
     return Version.emptyVersion;
   }
 }
 @Override
 protected AbstractPSystem executeLine(String line) {
   try {
     if (line.matches("(?i)^(authors?|about)\\s*$")) {
       return PSystemVersion.createShowAuthors();
     }
     if (line.matches("(?i)^version\\s*$")) {
       return PSystemVersion.createShowVersion();
     }
     if (line.matches("(?i)^testdot\\s*$")) {
       return PSystemVersion.createTestDot();
     }
     if (line.matches("(?i)^checkversion\\s*$")) {
       return PSystemVersion.createCheckVersions(null, null);
     }
     final Pattern p1 = Pattern.compile("(?i)^checkversion\\(proxy=([\\w.]+),port=(\\d+)\\)$");
     final Matcher m1 = p1.matcher(line);
     if (m1.matches()) {
       final String host = m1.group(1);
       final String port = m1.group(2);
       return PSystemVersion.createCheckVersions(host, port);
     }
     final Pattern p2 = Pattern.compile("(?i)^checkversion\\(proxy=([\\w.]+)\\)$");
     final Matcher m2 = p2.matcher(line);
     if (m2.matches()) {
       final String host = m2.group(1);
       final String port = "80";
       return PSystemVersion.createCheckVersions(host, port);
     }
   } catch (IOException e) {
     Log.error("Error " + e);
   }
   return null;
 }
  public void testBaseUrlPath() throws Exception {
    sau1 = setupSimAu(simAuConfig(tempDirPath));
    createContent(sau1);
    crawlContent(sau1);
    CachedUrlSet cus1 = sau1.getAuCachedUrlSet();

    tempDirPath2 = getTempDir().getAbsolutePath() + File.separator;
    Configuration config2 = simAuConfig(tempDirPath2);
    config2.put("base_url", "http://anotherhost.org/some/path/");
    SimulatedArchivalUnit sau2 = setupSimAu(config2);
    createContent(sau2);
    crawlContent(sau2);
    CachedUrlSet cus2 = sau1.getAuCachedUrlSet();
    List urls1 = auUrls(sau1);
    List urls2 = auUrls(sau2);

    Pattern pat1 = Pattern.compile("http://www\\.example\\.com(/.*)$");
    Pattern pat2 = Pattern.compile("http://anotherhost\\.org/some/path(/.*)$");
    List<String> l1 = auUrls(sau1);
    List<String> l2 = auUrls(sau2);
    assertEquals(l1.size(), l2.size());
    for (int ix = 0; ix < l1.size(); ix++) {
      Matcher m1 = pat1.matcher(l1.get(ix));
      assertTrue(m1.matches());
      Matcher m2 = pat2.matcher(l2.get(ix));
      assertTrue(m2.matches());
      assertEquals(m1.group(1), m2.group(1));
    }
  }
Beispiel #12
0
 /**
  * 好友分享
  *
  * @param ctuser
  * @param ly
  * @param ep
  * @return
  */
 public JSONObject recommendSharing(IpavuserEntity ctuser, String ly, String ep) {
   JSONObject rtn = new JSONObject();
   Pattern p = Pattern.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$");
   Matcher m = p.matcher(ep);
   boolean b = m.matches();
   if (b) {
     try {
       messageUtil.sendrecommendMail(ctuser.getUsername(), ep, ly);
     } catch (Exception e) {
       rtn.put("msg", e.getMessage());
       return rtn;
     }
     rtn.put("msg", "分享成功");
   } else {
     p = Pattern.compile("^((170)|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
     m = p.matcher(ep);
     b = m.matches();
     if (b == true) {
       try {
         messageUtil.sendrecommendPhone(ctuser.getUsername(), ep, ly);
       } catch (Exception e) {
         rtn.put("msg", e.getMessage());
         return rtn;
       }
       rtn.put("msg", "分享成功");
     } else {
       rtn.put("msg", "邮箱或手机号码有误");
     }
   }
   return rtn;
 }
 /**
  * Get the noun and verb <roots> (i.e. 'the highest' synsets in WordNet) from the particular
  * 'icfile' (Information Content) that you are applying. Store a noun <root>: a synset offset
  * number of type Integer in nounroots: an ArrayList<Integer> defined in the constructor of this
  * class. Store a verb <root>: a synset offset number of type Integer in verbroots: an
  * ArrayList<Integer> defined in the constructor of this class.
  *
  * <p>An example line in an 'icfile', showing a noun <root>: 1740n 128767 ROOT
  */
 private void getRoots() {
   Pattern pn = Pattern.compile("[0-9]+n [0-9]+ ROOT"); // find noun <root>
   Pattern pv = Pattern.compile("[0-9]+v [0-9]+ ROOT"); // find verb <root>
   Matcher m = null;
   String root = "";
   try {
     BufferedReader in = new BufferedReader(new FileReader(icfile));
     String line;
     while ((line = in.readLine()) != null) {
       // nouns
       m = pn.matcher(line);
       if (m.matches()) {
         root = (line.split("\\s")[0]).split("n")[0]; // !!! double split !!!
         nounroots.add(Integer.parseInt(root));
       }
       // verbs
       m = pv.matcher(line);
       if (m.matches()) {
         root = (line.split("\\s")[0]).split("v")[0]; // !!! double split !!!
         verbroots.add(Integer.parseInt(root));
       }
     }
     in.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  /**
   * Creates a descriptor URL based on the provided reference URL to a workflow.
   *
   * @param reference a URL to a workflow
   * @return the likely descriptor URL or the reference if no match was found
   */
  private static String guessDescriptor(String reference) {
    if (reference == null) {
      return reference;
    }
    if (reference.matches("(.+\\:\\/\\/.+workflow.xml)(.*[?&]id=\\d+)")) {
      return reference;
    } else {
      String myExperimentUrl = null;
      String id = null;
      String version = null;

      Matcher dlMatcher = WORKFLOW_DL_PATTERN.matcher(reference);
      if (dlMatcher.matches()) {
        myExperimentUrl = dlMatcher.group(WORKFLOW_URL_GROUP);
        id = dlMatcher.group(WORKFLOW_DL_ID_GROUP);
        version = dlMatcher.group(WORKFLOW_DL_VERSION_GROUP);
      } else {
        Matcher pathMatcher = WORKFLOW_PATH_PATTERN.matcher(reference);
        if (pathMatcher.matches()) {
          myExperimentUrl = pathMatcher.group(WORKFLOW_URL_GROUP);
          id = pathMatcher.group(WORKFLOW_PATH_ID_GROUP);
          version = pathMatcher.group(WORKFLOW_PATH_VERSION_GROUP);
        }
      }

      if (myExperimentUrl != null && id != null) {
        if (version == null) {
          version = "1";
        }
        return myExperimentUrl + "workflow.xml?id=" + id + "&version=" + version;
      }
    }
    return reference;
  }
  @Test
  public void testCurrentVersionStructureAgainstGold() throws Throwable {
    int latestVersion = CatalogVersions.getCurrentVersion().getSchemaVersion();
    String[] lastKnown = UpgradeTestUtils.getGoldVersion(latestVersion);
    String[] current = generateCatalog();
    Pattern thanksHibernate =
        Pattern.compile("(alter table )(\\w+)( add index )(\\w+)(.*add constraint )(\\w+)(.*)");
    assertEquals("number of stmts in schema ddl", lastKnown.length, current.length - 1);
    for (int i = 0; i < current.length - 1; i++) {
      if (!lastKnown[i].equals(current[i])) {
        // accept differences in index, constraint names
        if (lastKnown[i].startsWith("alter table") && current[i].startsWith("alter table")) {
          Matcher last = thanksHibernate.matcher(lastKnown[i]);
          Matcher now = thanksHibernate.matcher(current[i]);
          if (last.matches() && now.matches()) {
            String knownConstraint = lastKnown[i].substring(last.start(6), last.end(6));
            String knownIndex = lastKnown[i].substring(last.start(4), last.end(4));

            StringBuilder buf = new StringBuilder();
            buf.append(current[i].substring(0, now.start(4)));
            buf.append(knownIndex);
            buf.append(current[i].substring(now.end(4), now.start(6)));
            buf.append(knownConstraint);
            buf.append(current[i].substring(now.end(6)));
            String munged = buf.toString();
            if (lastKnown[i].equals(munged)) continue;
          }
        }
        assertEquals("schema ddl stmt " + i, lastKnown[i], current[i]);
      }
    }
  }
 /**
  * Parse a duration
  *
  * @param duration 3h, 2mn, 7s
  * @return The number of seconds
  */
 public int parseDuration(String duration) {
   if (duration == null) {
     return 60 * 60 * 24 * 30;
   }
   int toAdd = -1;
   if (days.matcher(duration).matches()) {
     Matcher matcher = days.matcher(duration);
     matcher.matches();
     toAdd = Integer.parseInt(matcher.group(1)) * (60 * 60) * 24;
   } else if (hours.matcher(duration).matches()) {
     Matcher matcher = hours.matcher(duration);
     matcher.matches();
     toAdd = Integer.parseInt(matcher.group(1)) * (60 * 60);
   } else if (minutes.matcher(duration).matches()) {
     Matcher matcher = minutes.matcher(duration);
     matcher.matches();
     toAdd = Integer.parseInt(matcher.group(1)) * (60);
   } else if (seconds.matcher(duration).matches()) {
     Matcher matcher = seconds.matcher(duration);
     matcher.matches();
     toAdd = Integer.parseInt(matcher.group(1));
   }
   if (toAdd == -1) {
     throw new IllegalArgumentException("Invalid duration pattern : " + duration);
   }
   return toAdd;
 }
Beispiel #17
0
  @Override
  protected void handleGet(HttpExchange exchange) throws IOException {
    String path = exchange.getRequestURI().getPath();
    if (path.equals("/")) {
      handleListBuckets(exchange);
      return;
    }

    Matcher bucketPatternMatcher = BUCKET_PATTERN.matcher(path);
    if (bucketPatternMatcher.matches()) {
      String bucketName = bucketPatternMatcher.group(1);
      handleListObjects(exchange, bucketName);
    }

    Matcher requestPathPatternMatcher = REQUEST_PATH_PATTERN.matcher(path);
    if (!requestPathPatternMatcher.matches()) {
      respondErrorAndClose(exchange, ErrorResponse.INVALID_URI);
      return;
    }
    String bucketName = requestPathPatternMatcher.group(1);
    String keyName = requestPathPatternMatcher.group(2);

    if (DOUBLE_DOT_PATTERN.matcher(keyName).matches()) {
      respondErrorAndClose(exchange, ErrorResponse.INVALID_URI);
      return;
    }

    handleGetObject(exchange, bucketName, keyName);
  }
  public String getSpecificAuthChainName(HttpServletRequest request) {
    for (String specificAuthChainName : specificAuthChains.keySet()) {
      SpecificAuthChainDescriptor desc = specificAuthChains.get(specificAuthChainName);

      List<Pattern> urlPatterns = desc.getUrlPatterns();
      if (!urlPatterns.isEmpty()) {
        // test on URI
        String requestUrl = request.getRequestURI();
        for (Pattern pattern : urlPatterns) {
          Matcher m = pattern.matcher(requestUrl);
          if (m.matches()) {
            return specificAuthChainName;
          }
        }
      }

      Map<String, Pattern> headerPattern = desc.getHeaderPatterns();

      for (String headerName : headerPattern.keySet()) {
        String headerValue = request.getHeader(headerName);
        if (headerValue != null) {
          Matcher m = headerPattern.get(headerName).matcher(headerValue);
          if (m.matches()) {
            return specificAuthChainName;
          }
        }
      }
    }
    return null;
  }
Beispiel #19
0
  public static boolean isTextValid(String aText, boolean canBeNull) {
    if (!canBeNull && (aText == null || aText.trim().length() == 0)) {
      return (false);
    }

    if (canBeNull && (aText == null || aText.trim().length() == 0)) {
      return (true);
    }

    String checkText = aText.toUpperCase();
    try {
      Pattern pattern =
          Pattern.compile(
              patternStr, Pattern.DOTALL + Pattern.CASE_INSENSITIVE + Pattern.UNIX_LINES);
      Matcher matcher = pattern.matcher(checkText);
      if (matcher.matches()) {
        return (false);
      }
      Pattern patternHex =
          Pattern.compile(
              hexPatternStr, Pattern.DOTALL + Pattern.CASE_INSENSITIVE + Pattern.UNIX_LINES);
      Matcher matcherHex = patternHex.matcher(checkText);
      if (matcherHex.matches()) {
        return (false);
      }
    } catch (Exception e) {
      Debug.info("Threw exception " + e.getMessage());
      return (false);
    }

    return (true);
  }
Beispiel #20
0
  /**
   * For example the archives are all known. (Check 4chan-x) Should be based on the software the
   * specific chan uses. FoolFuuka uses the same (url) layout as 4chan
   */
  @Override
  public String getGID(URL url) throws MalformedURLException {
    Pattern p;
    Matcher m;

    String u = url.toExternalForm();
    if (u.contains("/thread/") || u.contains("/res/")) {
      p =
          Pattern.compile(
              "^.*\\.[a-z]{1,3}/[a-zA-Z0-9]+/(thread|res)/([0-9]+)(\\.html|\\.php)?.*$");
      m = p.matcher(u);
      if (m.matches()) {
        return m.group(2);
      }

      // Drawchan is weird, has drawchan.net/dc/dw/res/####.html
      p =
          Pattern.compile(
              "^.*\\.[a-z]{1,3}/[a-zA-Z0-9]+/[a-zA-Z0-9]+/res/([0-9]+)(\\.html|\\.php)?.*$");
      m = p.matcher(u);
      if (m.matches()) {
        return m.group(1);
      }
    }

    throw new MalformedURLException(
        "Expected *chan URL formats: " + ".*/@/(res|thread)/####.html" + " Got: " + u);
  }
 public List<Token> recognize(List<Token> tokens) {
   List<Token> extractedTokens = new LinkedList<Token>();
   for (Token token : tokens) {
     String value = token.getValue();
     TokenType type = token.getType();
     if (type != TokenType.UNKNOWN) {
       // we already know what this is, continue
       extractedTokens.add(token);
       continue;
     }
     // whitespace
     Matcher whitespaceMatcher = whitespacePattern.matcher(value);
     if (whitespaceMatcher.matches()) {
       extractedTokens.add(new Token(value, TokenType.WHITESPACE));
       continue;
     }
     // punctuation
     Matcher punctuationMatcher = punctuationPattern.matcher(value);
     if (punctuationMatcher.matches()) {
       extractedTokens.add(new Token(value, TokenType.PUNCTUATION));
       continue;
     }
     // we came this far, then its still UNKNOWN
     extractedTokens.add(token);
   }
   return extractedTokens;
 }
  @Override
  protected void eol(byte[] b, int len) throws IOException {
    String line = charset.decode(ByteBuffer.wrap(b, 0, len)).toString();
    // line = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(b, 0, len)).toString();

    // trim off CR/LF from the end
    line = trimEOL(line);

    Pattern patternWarnings = Pattern.compile(".*\\d+\\sWarning\\(s\\).*");
    Pattern patternErrors = Pattern.compile(".*\\d+\\sError\\(s\\).*");

    Matcher mWarnings = patternWarnings.matcher(line);
    Matcher mErrors = patternErrors.matcher(line);

    if (mWarnings.matches()) { // Match the number of warnings
      String[] part = line.split(" ");
      try {
        numberOfWarnings = Integer.parseInt(part[4]);
      } catch (NumberFormatException e) {

      }
    } else if (mErrors.matches()) { // Match the number of errors
      String[] part = line.split(" ");
      try {
        numberOfErrors = Integer.parseInt(part[4]);
      } catch (NumberFormatException e) {

      }
    }

    // Write to output
    // out.write(b, 0, len);
    out.write(sjis.decode(ByteBuffer.wrap(b, 0, len)).toString().getBytes(StandardCharsets.UTF_8));
  }
Beispiel #23
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String str = request.getParameter("rssurl");
    try {

      Pattern p = Pattern.compile("(http|https):\\/\\/[A-Za-z\\.]*\\.(com|de|pl|org|net)");
      Matcher m = p.matcher(str);
      System.out.println("Validator: " + m.matches());
      if (m.matches()) {
        out.println("<tr>");
        out.println("<td>");
        out.println(str);
        out.println("</td>");
        out.println("<td>true");
        out.println("</td>");
        out.println("</tr>");
        this.sendJMSMessageToRSSQueue(str);
      } else {
        out.println("<tr>");
        out.println("<td>");
        out.println(str);
        out.println("</td>");
        out.println("<td>false");
        out.println("</td>");
        out.println("</tr>");
      }

    } catch (JMSException ex) {
      Logger.getLogger(RSSServlet.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      out.close();
    }
  }
  /**
   * Match.
   *
   * @param message the message
   * @return the log match result
   */
  public LogMatchResult match(String message) {
    Matcher matcher = null;

    for (int i = 0; i < startFormats.size(); i++) {
      matcher = startFormats.get(i).matcher(message);
      if (matcher.matches()) {
        LogMatchResult match = new LogMatchResult(LogMatchTypes.START, message);
        return match;
      }
    }

    for (int i = 0; i < endFormats.size(); i++) {
      matcher = endFormats.get(i).matcher(message);
      if (matcher.matches()) {
        LogMatchResult match = new LogMatchResult(LogMatchTypes.END, message);
        return match;
      }
    }

    for (int i = 0; i < exceptionFormats.size(); i++) {
      matcher = exceptionFormats.get(i).matcher(message);
      if (matcher.matches()) {
        LogMatchResult match = new LogMatchResult(LogMatchTypes.EXCEPTION, message);
        return match;
      }
    }
    return null;
  }
  @Test
  public void testRepoRegex() {
    Matcher m =
        MavenProxyServletSupport.REPOSITORY_ID_REGEX.matcher("repo1.maven.org/maven2@id=central");
    assertTrue(m.matches());
    assertEquals("central", m.group(2));

    m =
        MavenProxyServletSupport.REPOSITORY_ID_REGEX.matcher(
            "https://repo.fusesource.com/nexus/content/repositories/releases@id=fusereleases");
    assertTrue(m.matches());
    assertEquals("fusereleases", m.group(2));

    m =
        MavenProxyServletSupport.REPOSITORY_ID_REGEX.matcher(
            "repo1.maven.org/maven2@snapshots@id=central");
    assertTrue(m.matches());
    assertEquals("central", m.group(2));

    m =
        MavenProxyServletSupport.REPOSITORY_ID_REGEX.matcher(
            "repo1.maven.org/maven2@id=central@snapshots");
    assertTrue(m.matches());
    assertEquals("central", m.group(2));

    m =
        MavenProxyServletSupport.REPOSITORY_ID_REGEX.matcher(
            "repo1.maven.org/maven2@noreleases@id=central@snapshots");
    assertTrue(m.matches());
    assertEquals("central", m.group(2));
  }
    private static void parseLine(String line, FtraceEntryCallback callback) {
      Matcher m = sLineWithTgid.matcher(line);
      if (m.matches()) {
        callback.onTraceEntry(
            /*threadname*/ m.group(1),
            /*pid*/ m.group(3).startsWith("-") ? -1 : Integer.parseInt(m.group(3)),
            /*tid*/ Integer.parseInt(m.group(2)),
            /*eventName*/ m.group(6),
            /*details*/ m.group(7));
        return;
      }

      m = sLineWithIrqInfo.matcher(line);
      if (m.matches()) {
        callback.onTraceEntry(
            /*threadname*/ m.group(1),
            /*pid*/ -1,
            /*tid*/ Integer.parseInt(m.group(2)),
            /*eventName*/ m.group(5),
            /*details*/ m.group(6));
        return;
      }

      m = sLineLegacy.matcher(line);
      if (m.matches()) {
        callback.onTraceEntry(
            /*threadname*/ m.group(1),
            /*pid*/ -1,
            /*tid*/ Integer.parseInt(m.group(2)),
            /*eventName*/ m.group(5),
            /*details*/ m.group(6));
        return;
      }
      System.err.println("line doesn't match: " + line);
    }
Beispiel #27
0
  /**
   * 检验是否有效的邮件地址
   *
   * @param addr
   * @return
   */
  public static boolean isValidEmailAddress(String addr) {
    if (addr == null) return false;
    addr = addr.trim();
    if (addr.length() == 0) return false;
    Matcher matcher = basicAddressPattern.matcher(addr);
    if (!matcher.matches()) return false;
    String userPart = matcher.group(1);
    String domainPart = matcher.group(2);
    matcher = validUserPattern.matcher(userPart);
    if (!matcher.matches()) return false;
    matcher = ipDomainPattern.matcher(domainPart);
    if (matcher.matches()) {
      for (int i = 1; i < 5; i++) {
        String num = matcher.group(i);
        if (num == null) return false;
        if (Integer.parseInt(num) > 254) return false;
      }

      return true;
    }
    matcher = domainPattern.matcher(domainPart);
    if (matcher.matches()) {
      String tld = matcher.group(matcher.groupCount());
      matcher = tldPattern.matcher(tld);
      return tld.length() == 3 || matcher.matches();
    } else {
      return false;
    }
  }
  /**
   * Some dial strings in GSM are defined to do non-call setup things, such as modify or query
   * supplementary service settings (eg, call forwarding). These are generally referred to as "MMI
   * codes". We look to see if the dial string contains a valid MMI code (potentially with a dial
   * string at the end as well) and return info here.
   *
   * <p>If the dial string contains no MMI code, we return an instance with only "dialingNumber" set
   *
   * <p>Please see flow chart in TS 22.030 6.5.3.2
   */
  static GsmMmiCode newFromDialString(String dialString, GSMPhone phone, UiccCardApplication app) {
    Matcher m;
    GsmMmiCode ret = null;

    if (SystemProperties.getBoolean("ro.config.multimode_cdma", false)) {
      m = sPatternSuppServiceGlobalDev.matcher(dialString);
      if (m.matches()) {
        ret = new GsmMmiCode(phone, app);
        ret.action = makeEmptyNull(m.group(MATCH_GROUP_ACTION));
        String DialCode = makeEmptyNull(m.group(MATCH_GROUP_SERVICE_CODE));
        if (DialCode.equals(SC_GLOBALDEV_VM)) {
          ret.sc = SC_GLOBALDEV_VM;
          ret.dialingNumber = "+1" + phone.getMdn();
          return ret;
        } else if (DialCode.equals(SC_GLOBALDEV_CS)) {
          ret.sc = SC_GLOBALDEV_CS;
          ret.dialingNumber = GLOBALDEV_CS;
          return ret;
        } else if (DialCode.length() >= 3 && DialCode.startsWith(SC_GLOBALDEV_CLIR_INVK)) {
          // Dial "#31#PhoneNum" to invoke CLIR temporarily
          dialString = ACTION_DEACTIVATE + SC_CLIR + ACTION_DEACTIVATE + DialCode.substring(2);
        } else if (DialCode.length() >= 3 && DialCode.startsWith(SC_GLOBALDEV_CLIR_SUPP)) {
          // Dial "*31#PhoneNum" to suppress CLIR temporarily
          dialString = ACTION_ACTIVATE + SC_CLIR + ACTION_DEACTIVATE + DialCode.substring(2);
        }
      }
    }

    m = sPatternSuppService.matcher(dialString);

    // Is this formatted like a standard supplementary service code?
    if (m.matches()) {
      ret = new GsmMmiCode(phone, app);
      ret.poundString = makeEmptyNull(m.group(MATCH_GROUP_POUND_STRING));
      ret.action = makeEmptyNull(m.group(MATCH_GROUP_ACTION));
      ret.sc = makeEmptyNull(m.group(MATCH_GROUP_SERVICE_CODE));
      ret.sia = makeEmptyNull(m.group(MATCH_GROUP_SIA));
      ret.sib = makeEmptyNull(m.group(MATCH_GROUP_SIB));
      ret.sic = makeEmptyNull(m.group(MATCH_GROUP_SIC));
      ret.pwd = makeEmptyNull(m.group(MATCH_GROUP_PWD_CONFIRM));
      ret.dialingNumber = makeEmptyNull(m.group(MATCH_GROUP_DIALING_NUMBER));

    } else if (dialString.endsWith("#")) {
      // TS 22.030 sec 6.5.3.2
      // "Entry of any characters defined in the 3GPP TS 23.038 [8] Default Alphabet
      // (up to the maximum defined in 3GPP TS 24.080 [10]), followed by #SEND".

      ret = new GsmMmiCode(phone, app);
      ret.poundString = dialString;
    } else if (isTwoDigitShortCode(phone.getContext(), dialString)) {
      // Is a country-specific exception to short codes as defined in TS 22.030, 6.5.3.2
      ret = null;
    } else if (isShortCode(dialString, phone)) {
      // this may be a short code, as defined in TS 22.030, 6.5.3.2
      ret = new GsmMmiCode(phone, app);
      ret.dialingNumber = dialString;
    }

    return ret;
  }
  private void doProgressLine(final String msg) throws IOException {
    Matcher matcher;

    matcher = P_BOUNDED.matcher(msg);
    if (matcher.matches()) {
      final String taskname = matcher.group(1);
      if (!currentTask.equals(taskname)) {
        currentTask = taskname;
        lastCnt = 0;
        beginTask(Integer.parseInt(matcher.group(3)));
      }
      final int cnt = Integer.parseInt(matcher.group(2));
      monitor.update(cnt - lastCnt);
      lastCnt = cnt;
      return;
    }

    matcher = P_UNBOUNDED.matcher(msg);
    if (matcher.matches()) {
      final String taskname = matcher.group(1);
      if (!currentTask.equals(taskname)) {
        currentTask = taskname;
        lastCnt = 0;
        beginTask(ProgressMonitor.UNKNOWN);
      }
      final int cnt = Integer.parseInt(matcher.group(2));
      monitor.update(cnt - lastCnt);
      lastCnt = cnt;
      return;
    }

    messages.write(msg);
  }
Beispiel #30
0
 public static void main(String[] args) {
   Pattern p = Pattern.compile(".?pdf"); // Notice that .? matches 0 or 1 character
   Matcher m = p.matcher("pdf");
   System.out.println(m.matches()); // prints true. �������
   m = p.matcher(".pdf");
   System.out.println(m.matches()); // prints true.
 }