/**
  * 检测密码正则表达式
  *
  * @param String passWord 出入字符串密码
  * @return 检测密码是否符合正则表达式规范的布尔值
  */
 public static boolean checkPassword(String passWord) {
   String regex =
       "([a-z]|[A-Z]|[0-9]|[\\,]|[\\.]|[\\@]|[\\$]|[\\%]|[\\!]|[\\*]|[\\#]|[\\^]|[\\(]|[\\)]|[\\/]|[\\&]|[\\<]|[\\>]|[\\+]|[\\-]|[\\?]|[\\_])+";
   Pattern p = Pattern.compile(regex);
   Matcher m = p.matcher(passWord);
   return m.matches();
 }
Ejemplo n.º 2
1
 void processPage(String pageUri) {
   String search = "href=\"";
   try {
     log.info("Calling to Google: " + pageUri);
     String inputString = UrlUtils.getURL(pageUri);
     log.info(inputString);
     int next = 0;
     Pattern cite = Pattern.compile("<cite>(.*?)</cite>");
     Matcher matcher = cite.matcher(inputString);
     while (matcher.find()) {
       String newURI =
           "http://"
               + matcher
                   .group(1)
                   .replaceAll("\"", "")
                   .replaceAll("<b>|</b>", "")
                   .replaceAll("[ \\t\\n\\r]+", "")
                   .trim();
       log.info(newURI);
       profiles.addDeviceIfNotAlreadyKnown(newURI);
     }
   } catch (Exception e) {
     log.error(e.toString(), e);
     System.exit(0);
   }
 }
 public void addHashtagsFromMessage(String message) {
   if (message == null) {
     return;
   }
   boolean changed = false;
   Pattern pattern = Pattern.compile("(^|\\s)#[\\w@\\.]+");
   Matcher matcher = pattern.matcher(message);
   while (matcher.find()) {
     int start = matcher.start();
     int end = matcher.end();
     if (message.charAt(start) != '@' && message.charAt(start) != '#') {
       start++;
     }
     String hashtag = message.substring(start, end);
     if (hashtagsByText == null) {
       hashtagsByText = new HashMap<>();
       hashtags = new ArrayList<>();
     }
     HashtagObject hashtagObject = hashtagsByText.get(hashtag);
     if (hashtagObject == null) {
       hashtagObject = new HashtagObject();
       hashtagObject.hashtag = hashtag;
       hashtagsByText.put(hashtagObject.hashtag, hashtagObject);
     } else {
       hashtags.remove(hashtagObject);
     }
     hashtagObject.date = (int) (System.currentTimeMillis() / 1000);
     hashtags.add(0, hashtagObject);
     changed = true;
   }
   if (changed) {
     putRecentHashtags(hashtags);
   }
 }
Ejemplo n.º 4
0
 /**
  * Checks whether a given name is a valid name.
  *
  * @param name
  * @post Returns true if the given name is a valid name (if it starts with a capital and exists of
  *     at least 2 letters and no numbers also single and double quotes are allowed.) If the give
  *     name is not a valid name the method returns false. | result == match "[A-Z]{1}[a-zA-Z0-9 "
  *     ']{1,}"
  */
 @Raw
 private static boolean isValidName(String name) {
   String regex = "^[A-Z]{1}[a-zA-Z0-9 \"\']{1,}$";
   Pattern pattern = Pattern.compile(regex);
   Matcher matcher = pattern.matcher(name);
   return matcher.find();
 }
Ejemplo n.º 5
0
  // Chamando Robot
  public static void robot() throws Exception {
    Database db = new Database();
    db.connect();
    ResultSet rs = Page.findAll(db);

    Page p = null;
    while ((p = Page.next(rs)) != null) {
      String body = Robot.get(p.getUrl());

      // procurar por urls dentro do body
      // buscar por essas paginas

      // String expr = "href=\"([^\"]*)";
      String ereg = "href=\"https{0,1}:\\/\\/([^\"]*)\"";
      Pattern pt = Pattern.compile(ereg);
      Matcher m = pt.matcher(body);

      while (m.find()) {
        System.out.println(m.group());
        String[] _url = m.group().split("\"");
        Page.newUrl(_url[1]);
      }

      p.setBody(body);
      p.update();
    }

    db.close();
  }
Ejemplo n.º 6
0
 @Override
 public void validate() {
   if (StringUtils.isEmpty(accountBean.getEmail())) {
     addFieldError("accountBean.email", "Email cannnot be blank");
   } else {
     String expression = "^[\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
     CharSequence inputStr = accountBean.getEmail();
     Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
     Matcher matcher = pattern.matcher(inputStr);
     if (!matcher.matches()) addFieldError("accountBean.email", "Invalid email address");
   }
   if (StringUtils.isEmpty(accountBean.getPassword())) {
     addFieldError("accountBean.password", "Password cannnot be blank");
   } else if (accountBean.getPassword().length() < 6) {
     addFieldError("accountBean.password", "Password must be minimum of 6 characters");
   }
   if (StringUtils.isEmpty(accountBean.getFirstname())) {
     addFieldError("accountBean.firstname", "First Name cannnot be blank");
   }
   if (StringUtils.isEmpty(accountBean.getLastname())) {
     addFieldError("accountBean.lastname", "Last Name cannnot be blank");
   }
   if (accountBean.getGender().equals("-1")) {
     addFieldError("accountBean.gender", "You have to specify gender");
   }
 }
Ejemplo n.º 7
0
  /** @throws IOException */
  @Override
  protected final void setImageZipEntries() throws IOException {
    final File folder = file.getInputFile();
    ZipFile zipFolder = new ZipFile(folder);
    final Enumeration enumeration = zipFolder.entries();
    ZipEntry zipEntry;
    List<ZipEntry> tempSource = new ArrayList<ZipEntry>();
    final Pattern bandFilenamePattern = Pattern.compile("band[\\d]");

    while (enumeration.hasMoreElements()) {
      zipEntry = (ZipEntry) enumeration.nextElement();
      if (bandFilenamePattern
          .matcher(LandsatUtils.getZipEntryFileName(zipEntry).toLowerCase())
          .matches()) {
        tempSource.add(zipEntry);
      }
    }
    Collections.sort(
        tempSource,
        new Comparator<ZipEntry>() {
          public int compare(ZipEntry entry1, ZipEntry entry2) {
            String entry1FileName = LandsatUtils.getZipEntryFileName(entry1);
            String entry2FileName = LandsatUtils.getZipEntryFileName(entry2);
            return entry1FileName.compareTo(entry2FileName);
          }
        });
    imageSources = tempSource.toArray();
  }
Ejemplo n.º 8
0
  /**
   * Parses Apache combined access log, and prints out the following <br>
   * 1. Requester IP <br>
   * 2. Date of Request <br>
   * 3. Requested Page Path
   *
   * @param line : tuple to parsee
   * @throws ParseException
   * @throws IOException
   */
  public void processTuple(String line) throws ParseException {
    // Apapche log attaributes on each line.
    String url;
    String httpStatusCode;
    long numOfBytes;
    String referer;
    String agent;
    String ipAddr;

    // Parse each log line.
    Pattern accessLogPattern =
        Pattern.compile(getAccessLogRegex(), Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher accessLogEntryMatcher;
    accessLogEntryMatcher = accessLogPattern.matcher(line);

    if (accessLogEntryMatcher.matches()) {
      // System.out.println("MATCHED!");
      ipAddr = accessLogEntryMatcher.group(1);
      url = accessLogEntryMatcher.group(5);
      httpStatusCode = accessLogEntryMatcher.group(6);
      numOfBytes = Long.parseLong(accessLogEntryMatcher.group(7));
      referer = accessLogEntryMatcher.group(8);
      agent = accessLogEntryMatcher.group(9);

      outputIPAddress.emit(ipAddr);
      outputUrl.emit(url);
      outputStatusCode.emit(httpStatusCode);
      outputBytes.emit(numOfBytes);
      outputReferer.emit(referer);
      outputAgent.emit(agent);
    }
  }
  private List<String> findRelativeURLs(StringBuffer buf) {
    List<String> uris = new ArrayList<String>();

    if (buf.indexOf("<wsdl:") < 0) { // $NON-NLS-1$
      Pattern pattern = Pattern.compile("(<import)(.*)( schemaLocation=\")([^\"]+)"); // $NON-NLS-1$
      Matcher matcher = pattern.matcher(buf);
      while (matcher.find()) {
        String relativeURLString = matcher.group(4);
        uris.add(relativeURLString);
      }

      pattern = Pattern.compile("(<import schemaLocation=\")([^\"]+)"); // $NON-NLS-1$
      matcher = pattern.matcher(buf);
      while (matcher.find()) {
        String relativeURLString = matcher.group(2);
        uris.add(relativeURLString);
      }
    } else {
      Pattern pattern =
          Pattern.compile("(<xsd:import)(.*)( schemaLocation=\")([^\"]+)"); // $NON-NLS-1$
      Matcher matcher = pattern.matcher(buf);
      while (matcher.find()) {
        String relativeURLString = matcher.group(4);
        uris.add(relativeURLString);
      }
      pattern = Pattern.compile("(<xsd:import schemaLocation=\")([^\"]+)"); // $NON-NLS-1$
      matcher = pattern.matcher(buf);
      while (matcher.find()) {
        String relativeURLString = matcher.group(2);
        uris.add(relativeURLString);
      }
    }
    return uris;
  }
Ejemplo n.º 10
0
    public void map(LongWritable key, Text value, Context context)
        throws IOException, InterruptedException {

      String strId = "";
      String strBody = "";

      // Parse the xml and read data (page id and article body)
      // Using XOM library
      Builder builder = new Builder();

      try {
        Document doc = builder.build(value.toString(), null);

        Nodes nodeId = doc.query("//eecs485_article_id");
        strId = nodeId.get(0).getChild(0).getValue();

        Nodes nodeBody = doc.query("//eecs485_article_body");
        strBody = nodeBody.get(0).getChild(0).getValue();
      } catch (ParsingException ex) {
        System.out.println("Not well-formed.");
        System.out.println(ex.getMessage());
      } catch (IOException ex) {
        System.out.println("io exception");
      }

      // Tokenize document body
      Pattern pattern = Pattern.compile("\\w+");
      Matcher matcher = pattern.matcher(strBody);

      while (matcher.find()) {
        // Write the parsed token
        // key = term, docid   value = 1
        context.write(new Text(matcher.group() + "," + strId), one);
      }
    }
Ejemplo n.º 11
0
 /**
  * 根据微吼url创建直播信息
  *
  * @param url
  * @param groupList
  * @return
  * @throws Exception
  */
 private Live createVhLive(String url, List<JSONObject> groupList, User user) throws Exception {
   int i = url.lastIndexOf("/");
   String num = url.substring(i + 1);
   if (!StringUtil.isBlank(num)) {
     Pattern p = Pattern.compile("^\\d{9}$");
     if (p.matcher(num).matches()) {
       VhallWebinar vh = vhallWebinarService.getVhLiveInfo(num);
       if (vh != null) {
         //					2015-07-11 13:30:00
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Date start = sdf.parse(vh.getT_start());
         Date end = sdf.parse(vh.getT_end());
         String image = getVhPicUrl(url);
         List<Images> images = this.changePicUrlToImage(image);
         return liveRepo.save(
             new Live(
                 vh.getSubject(),
                 start.getTime(),
                 end.getTime(),
                 Config.LIVE_TYPE_VH,
                 vh.getWebinar_desc(),
                 images,
                 groupList,
                 num,
                 url,
                 user.getId(),
                 user.getNickName(),
                 user.getLogoURL()));
       }
     }
   }
   throw new Exception("创建直播失败");
 }
Ejemplo n.º 12
0
  @Override
  public View getView(final int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
      convertView = inflateLayout();
    }
    TextView title = (TextView) convertView.findViewById(R.id.tv_search_result_title);
    TextView net = (TextView) convertView.findViewById(R.id.tv_search_result_original_net);
    TextView time = (TextView) convertView.findViewById(R.id.tv_search_result_time);

    SpannableString s = new SpannableString(mList.get(position).getTitle());
    Pattern p = Pattern.compile(keyword);
    Matcher m = p.matcher(s);
    while (m.find()) {
      int start = m.start();
      int end = m.end();
      s.setSpan(
          new ForegroundColorSpan(mContext.getResources().getColor(R.color.orange)),
          start,
          end,
          Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    title.setText(s);
    net.setText(mList.get(position).getSite());
    time.setText(formatTime(mList.get(position).getCreateTime()));
    return convertView;
  }
Ejemplo n.º 13
0
  private boolean isValidPort(String text) {
    if (StringUtils.isBlank(text)) return false;
    String[] ports = text.trim().split(",");
    boolean ok = false;
    // linux (and OSX?)
    if (SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC_OSX) {
      // each will be /dev/tty* or /dev/cu*
      for (String port : ports) {
        if (StringUtils.isBlank(port)) continue;
        if (portNamesRegexLinux.matcher(port.trim()).matches()) {
          // must be at least one good
          ok = true;
        } else {
          // doesnt match, its bad so outa here.
          return false;
        }
      }
    }

    // windows
    if (SystemUtils.IS_OS_WINDOWS) {
      // each will be COM*
      for (String port : ports) {
        if (StringUtils.isBlank(port)) continue;
        if (portNamesRegexWindows.matcher(port.trim()).matches()) {
          // must be at least one good
          ok = true;
        } else {
          // doesnt match, its bad so outa here.
          return false;
        }
      }
    }
    return ok;
  }
Ejemplo n.º 14
0
  private String blankSectionHeaders(String markup, StringBuffer context) {

    Pattern p = Pattern.compile("(={2,})([^=]+)\\1");
    Matcher m = p.matcher(markup);

    int lastPos = 0;
    StringBuilder sb = new StringBuilder();

    while (m.find()) {
      sb.append(markup.substring(lastPos, m.start()));
      sb.append(getSpaceString(m.group().length()));

      String title = m.group(2).trim();

      if (!title.equalsIgnoreCase("see also")
          && !title.equalsIgnoreCase("external links")
          && !title.equalsIgnoreCase("references")
          && !title.equalsIgnoreCase("further reading")) context.append("\n").append(title);

      lastPos = m.end();
    }

    sb.append(markup.substring(lastPos));
    return sb.toString();
  }
Ejemplo n.º 15
0
  /**
   * Loads the plugin in the specified file
   *
   * <p>File must be valid according to the current enabled Plugin interfaces
   *
   * @param file File containing the plugin to load
   * @return The Plugin loaded, or null if it was invalid
   * @throws InvalidPluginException Thrown when the specified file is not a valid plugin
   * @throws UnknownDependencyException If a required dependency could not be found
   */
  public synchronized Plugin loadPlugin(File file)
      throws InvalidPluginException, UnknownDependencyException {
    Validate.notNull(file, "File cannot be null");

    checkUpdate(file);

    Set<Pattern> filters = fileAssociations.keySet();
    Plugin result = null;

    for (Pattern filter : filters) {
      String name = file.getName();
      Matcher match = filter.matcher(name);

      if (match.find()) {
        PluginLoader loader = fileAssociations.get(filter);

        result = loader.loadPlugin(file);
      }
    }

    if (result != null) {
      plugins.add(result);
      lookupNames.put(result.getDescription().getName(), result);
    }

    return result;
  }
Ejemplo n.º 16
0
 private String getTextNodeText(TextNode tn, boolean normalText) {
   String input = normalText ? tn.text() : tn.getWholeText();
   Node prev = tn.previousSibling();
   Node next = tn.nextSibling();
   boolean parentIsBlock = isBlock(tn.parent());
   if (isBlock(prev)) {
     input = ltrim(input);
   } else if (prev == null && parentIsBlock) {
     input = ltrim(input);
   } else if (normalText && prev instanceof TextNode) {
     TextNode tprev = (TextNode) prev;
     if (EMPTY_MATCHER.matcher(tprev.text()).matches()) {
       input = ltrim(input);
     }
   }
   if (input.length() > 0) {
     if (isBlock(next)) {
       input = rtrim(input);
     } else if (next == null && parentIsBlock) {
       input = rtrim(input);
     } else if (normalText && next instanceof TextNode) {
       TextNode tnext = (TextNode) next;
       if (EMPTY_MATCHER.matcher(tnext.text()).matches()) {
         input = rtrim(input);
       }
     }
   }
   return input;
 }
Ejemplo n.º 17
0
  private MyBooleanExpression(String expression) throws ParseException {
    expression = expression.replaceAll(" ", "").replaceAll("!", "~");
    this.repr = expression;
    Pattern pattern = Pattern.compile("[()~&|=>+]");
    String[] vars = pattern.split(expression);

    HashSet<String> varsSet = new HashSet<>(Arrays.asList(vars));
    varsSet.removeAll(Arrays.asList(new String[] {"", "1", "0"}));
    this.variables = varsSet.toArray(new String[0]);

    assert variables.length < 26;

    String shortExpr = new String(expression);
    for (int i = 0; i < variables.length; i++) {
      shortExpr = shortExpr.replaceAll(variables[i], "___" + i);
    }
    for (int i = 0; i < variables.length; i++) {
      shortExpr = shortExpr.replaceAll("___" + i, "" + (char) ('a' + i));
    }

    // System.out.println(shortExpr);

    BooleanExpression booleanExpression = new BooleanExpression(shortExpr);
    Map<Map<String, Boolean>, Map<BooleanExpression, Boolean>> truthTable =
        new TruthTable(booleanExpression).getResults();
    this.truthTable = new HashMap<>();

    for (Map<String, Boolean> map : truthTable.keySet()) {
      Map<BooleanExpression, Boolean> booleanMap = truthTable.get(map);
      boolean val = booleanMap.containsValue(true);
      satisfiabilitySetsCount += val ? 1 : 0;
      this.truthTable.put(map, val);
    }
  }
Ejemplo n.º 18
0
  @Override
  public String execute() throws Exception {
    code = (code == null && code.trim().length() == 0) ? null : code;
    expression = expression.trim();

    if (valueType.equals(ProgramIndicator.VALUE_TYPE_DATE)) {
      Pattern pattern = Pattern.compile("[(+|-|*|\\)]+");
      Matcher matcher = pattern.matcher(expression);
      if (matcher.find() && matcher.start() != 0) {
        expression = "+" + expression;
      }
    }

    ProgramIndicator programIndicator = programIndicatorService.getProgramIndicator(id);

    programIndicator.setName(name);
    programIndicator.setShortName(shortName);
    programIndicator.setCode(code);
    programIndicator.setDescription(description);
    programIndicator.setExpression(expression);
    programIndicator.setValueType(valueType);
    programIndicator.setRootDate(rootDate);

    programIndicatorService.updateProgramIndicator(programIndicator);

    programId = programIndicator.getProgram().getId();

    return SUCCESS;
  }
  /*Method to validate the keyword and the technology names*/
  public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    try {
      logger.info("In SearchPageForm validate method");
      ActionErrors errors = new ActionErrors(); // ActionError object is created to add the errors

      Pattern keywordPattern =
          Pattern.compile("^[A-za-z ]{1,20}$"); // Keyword is validated using regular expression

      Matcher keywordMatcher = keywordPattern.matcher(searchresultdto.getKeyword());

      if ((searchresultdto.getKeyword() == "")
          && (searchresultdto.getTechCode().equals("--Select--"))) {
        errors.add("errors", new ActionError("errors.Empty"));
      } else if ((searchresultdto.getTechCode().equals("--Select--"))) {
        if (!keywordMatcher.find()) {
          errors.add("errors", new ActionError("errors.InvalidKeyword"));
        }
      }

      return errors;
    } catch (NullPointerException e) {

    }
    return null;
  }
Ejemplo n.º 20
0
  private List parseCompileFailuresFromFormattedMessage(String target, String message) {
    final List errors = new ArrayList();

    final Pattern pattern = Pattern.compile("^(.+):\\[(\\d+),\\d+\\] ", Pattern.MULTILINE);

    final Matcher matcher = pattern.matcher(message);

    boolean found = matcher.find();

    while (found) {
      final String file = toRelative(matcher.group(1));
      final Integer line = Integer.valueOf(matcher.group(2));
      // final String msg = matcher.group(3);

      int start = matcher.end();

      found = matcher.find();
      int end = message.length() - 1;
      if (found) {
        end = matcher.start();
      }

      final String msg = message.substring(start, end).replaceAll("\r", "").trim();

      errors.add(
          new AntEventSummary(
              Constants.MESSAGE_LOGGED, "project", target, "task", msg, 0, file, line, null));
    }

    return errors;
  }
Ejemplo n.º 21
0
  @Override
  public List<String> getCphNameList(boolean toLowerCase) {
    Pattern pattern = Pattern.compile("ui:insert\\s*name=[\"'](.*?)[\"']");
    Set<String> matches = new HashSet<String>();

    Matcher m = pattern.matcher(head);
    while (m.find()) {
      String match = m.group(1);
      if (!match.startsWith("_")) {
        matches.add(m.group(1));
      }
    }

    m = pattern.matcher(body);
    while (m.find()) {
      String match = m.group(1);
      if (!match.startsWith("_")) {
        matches.add(m.group(1));
      }
    }
    List<String> cphNameList = new ArrayList<String>(matches);
    if (toLowerCase) {
      for (int i = 0, n = cphNameList.size(); i < n; i++) {
        cphNameList.set(i, cphNameList.get(i).toLowerCase());
      }
    }
    return cphNameList;
  }
Ejemplo n.º 22
0
  protected static List<String> getFilesInHivePartition(Partition part, JobConf jobConf) {
    List<String> result = newArrayList();

    String ignoreFileRegex = jobConf.get(HCatTap.IGNORE_FILE_IN_PARTITION_REGEX, "");
    Pattern ignoreFilePattern = Pattern.compile(ignoreFileRegex);

    try {
      Path partitionDirPath = new Path(part.getSd().getLocation());
      FileStatus[] partitionContent =
          partitionDirPath.getFileSystem(jobConf).listStatus(partitionDirPath);
      for (FileStatus currStatus : partitionContent) {
        if (!currStatus.isDir()) {
          if (!ignoreFilePattern.matcher(currStatus.getPath().getName()).matches()) {
            result.add(currStatus.getPath().toUri().getPath());
          } else {
            LOG.debug(
                "Ignoring path {} since matches ignore regex {}",
                currStatus.getPath().toUri().getPath(),
                ignoreFileRegex);
          }
        }
      }

    } catch (IOException e) {
      logError("Unable to read the content of partition '" + part.getSd().getLocation() + "'", e);
    }

    return result;
  }
Ejemplo n.º 23
0
  private String decodeEntities(String s) {
    StringBuffer buf = new StringBuffer();

    Matcher m = P_ENTITY.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.decode(match).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    buf = new StringBuffer();
    m = P_ENTITY_UNICODE.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.valueOf(match, 16).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    buf = new StringBuffer();
    m = P_ENCODE.matcher(s);
    while (m.find()) {
      final String match = m.group(1);
      final int decimal = Integer.valueOf(match, 16).intValue();
      m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal)));
    }
    m.appendTail(buf);
    s = buf.toString();

    s = validateEntities(s);
    return s;
  }
Ejemplo n.º 24
0
  public String getTransformedURL(Core core) {
    String result = getUrl();
    log.debug("URL before transformation: " + url);
    // index.jsp?param=${type}&param2=${id}&param3=${fieldname}
    Pattern p = Pattern.compile("(?!\\$\\{)([A-Za-z0-9]+?)(?:\\})", Pattern.CASE_INSENSITIVE);

    List<String> list = new ArrayList<String>();
    Matcher m = p.matcher(url);
    while (m.find()) {
      String tokenpart = m.group(1);
      log.debug("tokenpart = " + tokenpart);
      list.add(tokenpart);
    }
    log.debug("We found parameters: " + list);

    for (String param : list) {
      if ("user".equalsIgnoreCase(param)) {
        result = result.replaceAll("\\$\\{user\\}", core.getLoggedInUser().getUserName());
      }
    }

    log.debug("Returning URL: " + result);

    return result;
  }
Ejemplo n.º 25
0
  /**
   * 删除号码中的所有非数字
   *
   * @param str
   * @return
   */
  public static String filterUnNumber(String str) {
    if (str == null) {
      return null;
    }
    if (str.startsWith("+86")) {
      str = str.substring(3, str.length());
    }

    //		if (str.contains("#")) {
    //
    //			return str.replaceAll("#", "@");
    //		}

    // 只允数字
    String regEx = "[^0-9]";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(str);
    // 替换与模式匹配的所有字符(即非数字的字符将被""替换)
    // 对voip造成的负数号码,做处理
    if (str.startsWith("-")) {
      return "-" + m.replaceAll("").trim();
    } else {
      return m.replaceAll("").trim();
    }
  }
Ejemplo n.º 26
0
  private static class ClassFilter implements FileFilter {
    private static final String DEFAULT_INCLUDE = "\\*";
    private static final String DEFAULT_EXCLUDE = "";
    private static final Pattern INCLUDE_PATTERN =
        Pattern.compile(
            SystemInstance.get()
                .getOptions()
                .get(OPENEJB_JAR_ENHANCEMENT_INCLUDE, DEFAULT_INCLUDE));
    private static final Pattern EXCLUDE_PATTERN =
        Pattern.compile(
            SystemInstance.get()
                .getOptions()
                .get(OPENEJB_JAR_ENHANCEMENT_EXCLUDE, DEFAULT_EXCLUDE));

    @Override
    public boolean accept(final File file) {
      boolean isClass = file.getName().endsWith(CLASS_EXT);
      if (DEFAULT_EXCLUDE.equals(EXCLUDE_PATTERN.pattern())
          && DEFAULT_INCLUDE.equals(INCLUDE_PATTERN.pattern())) {
        return isClass;
      }

      final String path = file.getAbsolutePath();
      return isClass
          && INCLUDE_PATTERN.matcher(path).matches()
          && !EXCLUDE_PATTERN.matcher(path).matches();
    }
  }
Ejemplo n.º 27
0
 private void checkLoadedModForPermissionClass(File modFile) {
   try {
     Pattern p = Pattern.compile("permission", Pattern.CASE_INSENSITIVE);
     if (modFile.isDirectory()) {
       for (File file : modFile.listFiles()) {
         checkLoadedModForPermissionClass(file);
       }
     } else if ((modFile.getName().endsWith(".zip")) || (modFile.getName().endsWith(".jar"))) {
       ZipFile zip = new ZipFile(modFile);
       Enumeration entries = zip.entries();
       while (entries.hasMoreElements()) {
         ZipEntry zipentry = (ZipEntry) entries.nextElement();
         if (zipentry != null
             && zipentry.getName().endsWith(".class")
             && p.matcher(zipentry.getName()).find()) {
           checkLoadedClass(zip.getInputStream(zipentry));
         }
       }
       zip.close();
     } else if (modFile.getName().endsWith(".class") && p.matcher(modFile.getName()).find()) {
       checkLoadedClass(new FileInputStream(modFile));
     }
   } catch (IOException e) {
   }
 }
 /** This process finds all of the processes, puts them into a list, and adds them to the gui */
 @Override
 public void getInformation() {
   Thread.setDefaultUncaughtExceptionHandler(
       new Thread.UncaughtExceptionHandler() {
         public void uncaughtException(Thread t, Throwable e) {
           if (e instanceof NullPointerException) {
             e.printStackTrace();
           }
         }
       });
   File procDir = new File("/proc");
   processes = new ArrayList<ProcessData>();
   for (File f : procDir.listFiles()) {
     if (f.isDirectory()) {
       Pattern pidPattern = Pattern.compile("/proc/[0-9].*");
       Matcher pidMatcher = pidPattern.matcher(f.getAbsolutePath());
       if (pidMatcher.find()) {
         processes.add(getProcessData(f));
       }
     }
   }
   for (ProcessData proc : processes) {
     if (proc.getProcessState() == null) {
       System.out.println("Null process: " + proc.getName());
       System.out.println("Null Process: " + proc.getPid());
     }
     gui.addRowToProcList(proc.toStringCollection());
   }
 }
  public static boolean isHTMLSourceTextPresent(LiferaySelenium liferaySelenium, String value)
      throws Exception {

    URL url = new URL(liferaySelenium.getLocation());

    InputStream inputStream = url.openStream();

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    String line = null;

    while ((line = bufferedReader.readLine()) != null) {
      Pattern pattern = Pattern.compile(value);

      Matcher matcher = pattern.matcher(line);

      if (matcher.find()) {
        return true;
      }
    }

    inputStream.close();

    bufferedReader.close();

    return false;
  }
Ejemplo n.º 30
0
  /**
   * Chooses files that match the specified pattern.
   *
   * @param file file filter
   * @param content content filter
   * @param root root directory
   * @return sorted file paths
   * @throws InterruptedException interruption
   */
  String[] filter(final String file, final String content, final IOFile root)
      throws InterruptedException {

    final long id = ++filterId;
    final TreeSet<String> results = new TreeSet<>();
    final int[] search = new TokenParser(Token.lc(Token.token(content))).toArray();

    // glob pattern
    final ProjectCache pc = cache(root);
    if (file.contains("*") || file.contains("?")) {
      final Pattern pt = Pattern.compile(IOFile.regex(file));
      for (final String path : pc) {
        final int offset = offset(path, true);
        if (pt.matcher(path.substring(offset)).matches() && filterContent(path, search)) {
          results.add(path);
          if (results.size() >= MAXHITS) break;
        }
        if (id != filterId) throw new InterruptedException();
      }
    } else {
      // starts-with, contains, camel case
      final String pttrn = file.toLowerCase(Locale.ENGLISH).replace('\\', '/');
      final HashSet<String> exclude = new HashSet<>();
      final boolean pathSearch = pttrn.indexOf('/') != -1;
      for (int i = 0; i < (pathSearch ? 2 : 3); i++) {
        filter(pttrn, search, i, results, exclude, pathSearch, pc, id);
      }
    }
    return results.toArray(new String[results.size()]);
  }