Exemple #1
0
  protected final String stripcomments() {
    String s;
    String p;
    Pattern S;
    Matcher m;

    s = this.text;
    if (this.cs != null) {
      p = String.format("(?m)^[ \\t\\f]*%s.*(\\r|\\r\\n|\\n|\\z)", Pattern.quote(this.cs));
      S = makeregex(p);
      m = S.matcher(this.text);
      s = m.replaceAll("");
    }

    if (this.ics != null) {
      // A naive approach to handle ';' as the begin of a comment. Test
      // '\;' and '\\;' ..
      // Step 1: remove all unescaped inline comments till \eol
      p = String.format("(?m)([^\\\\])%s.*$", Pattern.quote(this.ics));
      S = makeregex(p);
      m = S.matcher(s);
      s = m.replaceAll("$1");
      // Step 2: handle escaped inline comment sequence, i.e. turn
      // '\;' into ';'. Ignore on purpose any escape sequence before
      // this escaped sequence.
      p = String.format("(?m)\\\\(%s.*)$", Pattern.quote(this.ics));
      S = makeregex(p);
      m = S.matcher(s);
      s = m.replaceAll("$1");
    }
    return s;
  }
Exemple #2
0
 public static String getDomain(String address) {
   String domain;
   String[] protos = address.split(Pattern.quote(ADDR_PROT_INTERN_SEP));
   if (protos.length > 1) domain = protos[1];
   else domain = protos[0];
   return domain.split(Pattern.quote(ADDR_PART_SEP))[0].trim();
 }
  public static String getViewPathsRegexp(String[] loadRules, boolean isUnix) {
    // Note - the logic here to do ORing to match against *any* of the load rules is, quite frankly,
    // hackishly ugly. I'm embarassed by it. But it's what I've got for right now.
    String filterRegexp = "";
    if (loadRules != null) {
      String tempFilterRules = "";
      for (String loadRule : loadRules) {
        if (StringUtils.isNotEmpty(loadRule)) {
          if (loadRule.endsWith("/") || loadRule.endsWith("\\")) {
            loadRule = loadRule.substring(0, loadRule.length() - 1);
          }
          loadRule = PathUtil.convertPathForOS(loadRule, isUnix);
          tempFilterRules += "|" + Pattern.quote(loadRule + PathUtil.fileSepForOS(isUnix));
          tempFilterRules += "|" + Pattern.quote(loadRule) + "$";
        }
      }

      // Adding tweak for ignoring leading slashes or Windows drives in case of strange situations
      // using setview.
      if (StringUtils.isNotEmpty(tempFilterRules)) {
        filterRegexp = tempFilterRules.substring(1);
      }
    }
    return filterRegexp;
  }
  // TODO: Check processing order
  public int compareTo(DataRecord otherRecord) {
    String[] orIDcomponents =
        otherRecord.getIDRecord().split(Pattern.quote(DataRecord.getIDSeperator()));
    String[] myIDcomponents = this.IDRecord.split(Pattern.quote(DataRecord.getIDSeperator()));
    // String orID = otherRecord.getIDRecord().split( "\\$" )[0];
    // String myID = this.IDRecord.split( "\\$" )[0];
    String orID = orIDcomponents[0];
    String myID = myIDcomponents[0];

    int compareVal = myID.compareTo(orID);
    if (compareVal == 0 && orIDcomponents.length > 1 && myIDcomponents.length > 1) {
      // Compare the sub-ids
      return this.IDRecord.compareTo(otherRecord.getIDRecord());
    }
    // Check if we compare against the main entry here
    /*else if( compareVal == 0 ) {
        if( myIDcomponents.length > 1 ) {
            return 1;
        }
        else {
            return -1;
        }
    }*/

    return compareVal;

    // return myID.compareTo(orID);

    // return this.IDRecord.compareTo( otherRecord.getIDRecord() );
  }
Exemple #5
0
 public static ArrayList<Address> getAddress(String addresses) {
   // boolean DEBUG = true;
   if (D_Peer.DEBUG) System.out.println("PeerAddress:getAddress: parsing addresses " + addresses);
   String[] addresses_l = Address.split(addresses);
   // may have to control addresses, to defend from DOS based on false addresses
   ArrayList<Address> address = new ArrayList<Address>(addresses_l.length);
   for (int k = 0; k < addresses_l.length; k++) {
     if (D_Peer.DEBUG)
       System.out.println("PeerAddress:getAddress: parsing address " + addresses_l[k]);
     Address a = new Address();
     String taddr[] = addresses_l[k].split(Pattern.quote(Address.ADDR_PROT_NET_SEP), COMPONENTS);
     if (taddr.length < 2) continue;
     a.pure_protocol = taddr[0];
     String adr = taddr[1];
     if (adr == null) {
       address.add(a);
       continue;
     }
     String pri[] = adr.split(Pattern.quote(Address.PRI_SEP));
     a.address = pri[0];
     if (pri.length > 1) {
       a.certified = true;
       try {
         a.priority = Integer.parseInt(pri[1]);
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
     address.add(a);
     if (D_Peer.DEBUG) System.out.println("PeerAddress:getAddress: got typed address " + a);
   }
   return address;
 }
  @Override
  public IPathParameter resolvePathParameter(IContainer item) {
    IPathParameter result = null;
    String[] groupParts = item.getName().split(Pattern.quote(mPathSeparator));
    String[] pathParts = mPath.getValue().split(Pattern.quote(mPathSeparator));
    String part, param, buff;

    // Parse the path
    for (int depth = 0; depth < groupParts.length; depth++) {
      if (depth < pathParts.length) {
        part = groupParts[depth];
        param = pathParts[depth];

        // If a parameter is defined
        if (param.matches(".*(" + mPath.PARAM_PATTERN + ")+.*")) {
          // Try to determine the parameter result
          buff = param.replaceFirst("^(.*)(" + mPath.PARAM_PATTERN + ".*)$", "$1");
          part = part.substring(buff.length());
          buff = param.replaceAll(".*" + mPath.PARAM_PATTERN, "");
          part = part.replaceFirst(Pattern.quote(buff), "");
          buff = param.replaceAll(".*" + mPath.PARAM_PATTERN + ".*", "$1");
          result =
              new PathParameter(
                  Factory.getFactory(getFactoryName()), ParameterType.SUBSTITUTION, buff, part);
          break;
        }
      }
    }
    return result;
  }
Exemple #7
0
 public static String escapeSpecialRegexCharacters(final String toEscape) {
   return toEscape
       .replaceAll(Pattern.quote("{"), "\\\\{")
       .replaceAll(Pattern.quote("}"), "\\\\}")
       .replaceAll(Pattern.quote("["), "\\\\[")
       .replaceAll(Pattern.quote("]"), "\\\\]");
 }
  /**
   * see: <code>
   * org.apache.karaf.management.KarafMBeanServerGuard#getGeneralPid(java.util.List, java.lang.String)
   * </code>
   *
   * <p>Given a list of all available configadmin PIDs that define RBAC information, return a real
   * PID that'll be used to fetch information about particular, non wildcard <code>pid</code>.
   *
   * <p>Here, the PID returned may use wildcards ("_"), which means that general PID will be used to
   * check particular <code>pid</code> (one of possible PIDs derived from {@link ObjectName})
   *
   * @param allJmxAclPids
   * @param pid one of the PIDs returned from {@link #iterateDownPids(List)}
   * @return
   */
  private static String getGeneralPid(List<String> allJmxAclPids, String pid) {
    String[] pidStrArray = pid.split(Pattern.quote("."));
    Set<String[]> rets = new TreeSet<>(WILDCARD_PID_COMPARATOR);
    for (String id : allJmxAclPids) {
      String[] idStrArray = id.split(Pattern.quote("."));
      if (idStrArray.length == pidStrArray.length) {
        boolean match = true;
        for (int i = 0; i < idStrArray.length; i++) {
          if (!(idStrArray[i].equals(JMX_OBJECTNAME_PROPERTY_WILDCARD)
              || idStrArray[i].equals(pidStrArray[i]))) {
            match = false;
            break;
          }
        }
        if (match) {
          rets.add(idStrArray);
        }
      }
    }

    Iterator<String[]> it = rets.iterator();
    if (!it.hasNext()) {
      return "";
    } else {
      StringBuilder buffer = new StringBuilder();
      for (String segment : it.next()) {
        if (buffer.length() > 0) {
          buffer.append(".");
        }
        buffer.append(segment);
      }
      return buffer.toString();
    }
  }
  public static String obfuscate(String email) {
    LinkedList<String> emailList = new LinkedList<>();

    // Attack the dots
    String[] chunks = email.split(Pattern.quote("."));
    String[] atChunks = null;
    int dotCounter = chunks.length - 1;

    for (int i = 0; i < chunks.length; i++) {
      emailList.addLast(chunks[i]);
      if (dotCounter != 0) {
        emailList.addLast("[.]");
        dotCounter--;
      }
    }
    // Attack the @
    for (int j = 0; j < emailList.size(); j++) {
      if (emailList.get(j).contains("@")) {
        atChunks = emailList.get(j).split(Pattern.quote("@"));
        emailList.remove(j);
        emailList.add(j, atChunks[0]);
        emailList.add(j + 1, "[at]");
        emailList.add(j + 2, atChunks[1]);
      }
    }

    System.out.println(toString(emailList));
    return toString(emailList);
  }
Exemple #10
0
 private void updateFilter() {
   DefaultRowSorter<TableModel, Object> sorter =
       (DefaultRowSorter<TableModel, Object>) otherTable.getRowSorter();
   String key = keyFilter.getSelectedItem().toString();
   RowFilter<TableModel, Object> filter = null;
   if (!key.isEmpty()) {
     Object method = keyFilterMethod.getSelectedItem();
     if (method == STARTS_WITH) {
       filter = RowFilter.regexFilter('^' + Pattern.quote(key), UITableModel.KEY_COLUMN_INDEX);
     } else if (method == ENDS_WITH) {
       filter = RowFilter.regexFilter(Pattern.quote(key) + '$', UITableModel.KEY_COLUMN_INDEX);
     } else if (method == CONTAINS) {
       filter = RowFilter.regexFilter(Pattern.quote(key), UITableModel.KEY_COLUMN_INDEX);
     } else {
       filter = RowFilter.regexFilter(key, UITableModel.KEY_COLUMN_INDEX);
     }
   }
   String type = typeFilter.getSelectedItem().toString();
   if (!type.isEmpty()) {
     RowFilter<TableModel, Object> typeFilter =
         RowFilter.regexFilter('^' + type + '$', UITableModel.TYPE_COLUMN_INDEX);
     filter =
         filter == null
             ? typeFilter
             : RowFilter.<TableModel, Object>andFilter(Arrays.asList(filter, typeFilter));
   }
   sorter.setRowFilter(filter);
 }
  public void testRun() {
    // Wait for activity: 'com.fitbit.onboarding.landing.LandingActivity_'
    solo.waitForActivity("LandingActivity_", 500);
    // Wait for activity: 'com.fitbit.home.ui.HomeActivity_'
    assertTrue("HomeActivity_ is not found!", solo.waitForActivity("HomeActivity_"));
    solo.sleep(500);
    solo.clickOnView(solo.getView("tile_content", 1));

    // Wait for activity: 'com.fitbit.runtrack.ui.ExerciseListActivity'
    assertTrue("ExerciseListActivity is not found!", solo.waitForActivity("ExerciseListActivity"));
    // sleep for x seconds
    solo.sleep(500);

    // Click on Empty Text View
    solo.clickOnView(solo.getView("new_exercise"));
    // Wait for activity: 'com.fitbit.runtrack.ui.RecordExerciseActivity'
    assertTrue(
        "RecordExerciseActivity is not found!", solo.waitForActivity("RecordExerciseActivity"));
    // sleep for x seconds
    solo.sleep(500);
    solo.clickOnText(java.util.regex.Pattern.quote("Log Previous"));

    solo.enterText(0, "yoga");
    solo.clickOnText(java.util.regex.Pattern.quote("Yoga"));

    solo.clickOnText(java.util.regex.Pattern.quote("30:00"));
    solo.setTimePicker(0, 23, 59);
    solo.clickOnView(solo.getView(android.R.id.button1));

    solo.clickOnView(solo.getView("confirm"));
    solo.clickOnView(solo.getView(android.R.id.button1));
  }
Exemple #12
0
  private CoreObject xGeneralReplace(CoreCall cc, boolean escapeRx) throws InterpreterException {
    String resultString = getCurrentObject(cc).value.toString();

    Iterator<String> i = cc.members.keySet().iterator();
    while (i.hasNext()) {
      String replaceFind = i.next();
      String replaceWith = cc.members.get(replaceFind).toString();
      replaceFind = replaceFind.substring(1);
      if (escapeRx) replaceFind = Pattern.quote(replaceFind);
      resultString = resultString.replaceAll(replaceFind, replaceWith);
    }

    if (cc.argCount > 0) {
      for (int idx = 0; idx < cc.argCount; idx++) {
        CoreObject rObj = cc.argPop();
        if (rObj.getClass() == CoreMap.class) {
          CoreMap map = (CoreMap) rObj;
          Iterator<String> mi = map.items.keySet().iterator();
          while (mi.hasNext()) {
            String replaceFind = mi.next();
            String replaceWith = map.items.get(replaceFind).toString();
            if (escapeRx) replaceFind = Pattern.quote(replaceFind);
            resultString = resultString.replaceAll(replaceFind, replaceWith);
          }
        } else {
          String replaceFind = rObj.toString();
          resultString = resultString.replaceAll(replaceFind, "");
        }
      }
    }

    return new CoreString(resultString);
  }
  /**
   * Matches a version object to versions in a set by comparing the non build number portion of the
   * string. Then find which of the matching versions has the highest build number and is therefore
   * the latest version.
   *
   * @param version the Version object to use.
   * @param versionSet a collection of versions to compare to.
   * @return the highest build number, or 0 if no matching build numbers are found.
   */
  public int findHighestMatchingBuildNumber(Version version, Set<String> versionSet) {
    int highestBuildNum = 0;

    // Build version pattern regex, matches something like "<mmm>.<qualifier>.<buildnum>".
    StringBuffer versionPatternBuf = new StringBuffer();
    versionPatternBuf.append("(");
    versionPatternBuf.append(Pattern.quote(getOriginalMMM()));
    versionPatternBuf.append(
        "(" + DELIMITER_REGEX + "0)*"); // Match zeros appended to a major only version
    versionPatternBuf.append(")?");
    versionPatternBuf.append(DELIMITER_REGEX);
    if (version.getQualifierBase() != null) {
      versionPatternBuf.append(Pattern.quote(version.getQualifierBase()));
      versionPatternBuf.append(DELIMITER_REGEX);
    }
    versionPatternBuf.append("(\\d+)");
    String candidatePatternStr = versionPatternBuf.toString();

    logger.debug(
        "Using pattern: '{}' to find compatible versions from metadata.", candidatePatternStr);
    final Pattern candidateSuffixPattern = Pattern.compile(candidatePatternStr);

    for (final String compareVersion : versionSet) {
      final Matcher candidateSuffixMatcher = candidateSuffixPattern.matcher(compareVersion);
      if (candidateSuffixMatcher.matches()) {
        String buildNumberStr = candidateSuffixMatcher.group(3);
        int compareBuildNum = Integer.parseInt(buildNumberStr);
        if (compareBuildNum > highestBuildNum) {
          highestBuildNum = compareBuildNum;
        }
      }
    }
    return highestBuildNum;
  }
  // <timestamp>2015-08-05T00:44:14Z</timestamp>
  public void extractTimestamp() {
    String ref = "<timestamp>";
    Pattern p = Pattern.compile(Pattern.quote(ref) + "(.*?)" + Pattern.quote("</timestamp>"));
    Matcher m = p.matcher(raw);
    while (m.find()) {
      String timestamp = m.group(1);
      if (StringUtils.isNotBlank(timestamp)) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        try {
          cal.setTime(sdf.parse(timestamp));
          // Date articleDate = cal.getTime();

          Calendar c = new GregorianCalendar();
          c.set(Calendar.HOUR_OF_DAY, 0); // anything 0 - 23
          c.set(Calendar.MINUTE, 0);
          c.set(Calendar.SECOND, 0);

          daysSinceRevision = daysBetween(c, cal);
        } catch (ParseException e) {
          System.out.println(
              "While extracting timestamp " + e.getMessage() + " for article " + articleTitle);
        }
      } else {
        System.out.println("No timestamp found for article " + articleTitle);
      }
    }
  }
  public void extractRefsWithoutCites() {
    String ref = "&lt;ref&gt;";
    String endref = "&lt;/ref&gt;";
    Pattern p = Pattern.compile(Pattern.quote(ref) + "(.*?)" + Pattern.quote(endref));
    Matcher m = p.matcher(raw);
    while (m.find()) {
      String token = m.group(0);

      if (token != null
          && token.contains("{{citation") == false
          && token.contains("{{cite") == false
          && token.contains("{{harv") == false
          && token.contains("{{harvt") == false
          && token.contains("{{sfn|") == false
          && token.contains("{{sfnm|") == false
          && token.contains("{{wikicite|") == false
          && token.contains("{{Citation") == false
          && token.contains("{{Cite") == false
          && token.contains("{{Harv") == false
          && token.contains("{{Harvt") == false
          && token.contains("{{Sfn|") == false
          && token.contains("{{Sfnm|") == false
          && token.contains("{{Wikicite|") == false) {

        refs.add(token);
      }
    }
  }
Exemple #16
0
  public static int add(String s) {

    if (s.isEmpty()) return 0;
    if (s.contains("//")) {
      String regex = "//(.)\n(.*)";
      Matcher m = Pattern.compile(regex).matcher(s);
      if (m.find()) {
        String fistSubStringComponent = m.group(1);
        String secondSubStringComponent = m.group(2);
        String[] listNumbers =
            secondSubStringComponent.split(Pattern.quote(fistSubStringComponent));
        return computeSumFromListOfStringNumbers(listNumbers);

      } else {
        String regex2 = "//\\[(.*)\\]\n(.*)";
        Matcher m2 = Pattern.compile(regex2).matcher(s);
        if (m2.find()) {
          String firstSubStringComponent = m2.group(1);
          String secondSubStringComponent = m2.group(2);
          String[] listNumbers =
              secondSubStringComponent.split(Pattern.quote(firstSubStringComponent));
          return computeSumFromListOfStringNumbers(listNumbers);
        }
      }
      return -1;
    } else {
      return computeSumFromListOfStringNumbers(s.split("[,\n]"));
    }
  }
Exemple #17
0
 public static java.util.List<TileSourceTemplate> getUserDefinedTemplates(File tilesDir) {
   java.util.List<TileSourceTemplate> ts = new ArrayList<TileSourceTemplate>();
   if (tilesDir != null) {
     File[] listFiles = tilesDir.listFiles();
     if (listFiles != null) {
       for (File f : listFiles) {
         File ch = new File(f, "url"); // $NON-NLS-1$
         if (f.isDirectory() && ch.exists()) {
           try {
             BufferedReader read =
                 new BufferedReader(
                     new InputStreamReader(new FileInputStream(ch), "UTF-8")); // $NON-NLS-1$
             String url = read.readLine();
             read.close();
             if (!Algoritms.isEmpty(url)) {
               url = url.replaceAll(Pattern.quote("{$x}"), "{1}"); // $NON-NLS-1$ //$NON-NLS-2$
               url = url.replaceAll(Pattern.quote("{$z}"), "{0}"); // $NON-NLS-1$//$NON-NLS-2$
               url = url.replaceAll(Pattern.quote("{$y}"), "{2}"); // $NON-NLS-1$ //$NON-NLS-2$
               TileSourceTemplate t =
                   new TileSourceTemplate(
                       f.getName(), url, ".jpg", 18, 1, 256, 16, 20000); // $NON-NLS-1$
               ts.add(t);
             }
           } catch (IOException e) {
             log.info("Mailformed dir " + f.getName(), e); // $NON-NLS-1$
           }
         }
       }
     }
   }
   return ts;
 }
Exemple #18
0
 /**
  * [<PROT>://]domain:...:...:<name>[:<active_int_boolean>:...]
  *
  * @param address
  * @return
  */
 public static String getName(String address) {
   String domain;
   String[] protos = address.split(Pattern.quote(ADDR_PROT_INTERN_SEP));
   if (protos.length > 1) domain = protos[1];
   else domain = protos[0];
   String[] ports = domain.split(Pattern.quote(ADDR_PART_SEP));
   if (ports.length < 4) return null;
   return ports[3];
 }
    @Override
    public String toString() {
      String packageName = AbstractEntity.class.getCanonicalName();
      packageName = packageName.replaceFirst(Pattern.quote(".AbstractEntity"), "");

      String className = (this.getClass().getInterfaces()[0]).getCanonicalName();
      className = className.replaceFirst(Pattern.quote(packageName + "."), "");

      return className + "{" + "value=" + value + '}';
    }
 private Pattern makePattern(String startComment, String endComment) {
   return Pattern.compile(
       "^("
           + Pattern.quote(startComment)
           + ".*?"
           + Pattern.quote(endComment)
           + "[\r\n ]*)"
           + "(.*)$",
       Pattern.DOTALL);
 }
  public void testRun() {
    // Wait for activity: 'com.fitbit.onboarding.landing.LandingActivity_'
    solo.waitForActivity("LandingActivity_", 2000);
    // Wait for activity: 'com.fitbit.home.ui.HomeActivity_'
    assertTrue("HomeActivity_ is not found!", solo.waitForActivity("HomeActivity_"));
    // sleep - shot
    solo.sleep(500);

    // Click on -- bpm 64 bpm resting
    solo.clickInList(3, 0);

    // Wait for activity: 'com.fitbit.heartrate.landing.HeartRateLandingActivity'
    assertTrue(
        "HeartRateLandingActivity is not found!", solo.waitForActivity("HeartRateLandingActivity"));
    // sleep - shot
    solo.sleep(500);

    // Scroll View to the right side
    solo.scrollViewToSide(solo.getView(android.view.ViewGroup.class, 19), Solo.RIGHT);
    // sleep - shot
    solo.sleep(500);

    solo.clickOnText(java.util.regex.Pattern.quote("Minutes in"));
    // Wait for activity: 'com.fitbit.heartrate.charts.ExerciseHeartRateChartActivity_'
    assertTrue(
        "ExerciseHeartRateChartActivity is not found!",
        solo.waitForActivity("ExerciseHeartRateChartActivity"));

    // Rotate the screen
    solo.setActivityOrientation(Solo.LANDSCAPE);

    // Click on 1 WEEK
    solo.clickOnText(java.util.regex.Pattern.quote("1 WEEK"));

    // solo.clickOnText(java.util.regex.Pattern.quote("TIME IN HEART RATE ZONES"));

    solo.clickOnText(java.util.regex.Pattern.quote("Fat Burn"));
    solo.clickOnText(java.util.regex.Pattern.quote("Cardio"));
    solo.clickOnText(java.util.regex.Pattern.quote("Peak"));

    solo.scrollToSide(Solo.LEFT);
    solo.scrollToSide(Solo.LEFT);

    solo.scrollToSide(Solo.LEFT);
    solo.scrollToSide(Solo.LEFT);
    solo.scrollToSide(Solo.RIGHT);
    solo.scrollToSide(Solo.RIGHT);
    solo.scrollToSide(Solo.RIGHT);
    solo.scrollToSide(Solo.LEFT);
    solo.scrollToSide(Solo.RIGHT);

    solo.sleep(500);

    solo.goBack();
  }
Exemple #22
0
  void setTags(String start, String stop) {

    if (start.equals(UNESCAPED_START) || stop.equals(UNESCAPED_STOP)) {
      throw new IllegalArgumentException("Normal tags cannot override escape tags");
    }

    this.unquotedStart = start;
    this.precede = start.length() > UNESCAPED_START.length();
    this.start = Pattern.quote(start);
    this.stop = Pattern.quote(stop);
  }
 @Override
 public void performAction(SiteNode sn) throws Exception {
   Session session = Model.getSingleton().getSession();
   String url = new URI(sn.getHierarchicNodeName(), false).toString();
   if (sn.isLeaf()) {
     url = Pattern.quote(url);
   } else {
     url = Pattern.quote(url + "/") + ".*";
   }
   session.getExcludeFromSpiderRegexs().add(url);
 }
Exemple #24
0
  @Inject
  public HFRUrlParser(MDEndpoints mdEndpoints, CategoriesStore categoriesStore) {
    this.mdEndpoints = mdEndpoints;
    this.categoriesStore = categoriesStore;

    String baseRewrittenRegex = "(?:" + Pattern.quote(mdEndpoints.baseurl() + "/hfr/") + ")";
    baseRewrittenUrlRegex = Pattern.quote(mdEndpoints.baseurl()) + "/hfr/.*";

    baseStandardUrlRegex = Pattern.quote(mdEndpoints.baseurl()) + "/forum.*";
    rewrittenTopicPattern = Pattern.compile(baseRewrittenRegex + REWRITTEN_TOPIC_REGEX);
  }
Exemple #25
0
 /**
  * [<PROT>://]domain:...:...:....:<active_int_boolean>[:...]
  *
  * @param address
  * @return
  */
 public static boolean getActive(String address) {
   String domain;
   String[] protos = address.split(Pattern.quote(ADDR_PROT_INTERN_SEP));
   if (protos.length > 1) domain = protos[1];
   else domain = protos[0];
   String[] ports = domain.split(Pattern.quote(ADDR_PART_SEP));
   if (DEBUG)
     System.out.println("Address:getActive " + domain + " ports=" + Util.concat(ports, "=="));
   if (ports.length < 5) return true;
   return Util.stringInt2bool(ports[4], false);
 }
Exemple #26
0
  /**
   * renders wiki markup like _italic_ to XHTML see also www.radeox.org @Deprecated The wiki markup
   * area is no longer supported. In the legacy form infrastructure it's still there, but it won't
   * be available in the new flexi forms. In flexi forms use the RichTextElement instead. tested
   * during migration and expanded to prevent radeox failures
   *
   * @param originalText
   * @return result (rendered originalText) or null if originalText was null
   */
  @Deprecated
  public static String formatWikiMarkup(String oldValue) {
    if (oldValue != null) {
      String newValue = "";
      // oldValue = oldValue.replaceAll("<>", "&lt;&gt;");
      // oldValue = oldValue.replaceAll(Pattern.quote("[]"),
      // "&#91;&#93;");

      // prevent error with {$} interpreted as regexp
      String marker1 = "piYie6Eigh0phafeiTuk4dahwahvoh7eedoegee2egh8xuj9phah8eop8iuk";
      oldValue = oldValue.replaceAll(Pattern.quote("{$}"), marker1);

      // \{code} will result in an error => convert
      String marker2 = "RohbaeW7xahbohk8iewoo7thocaemaech2pahS8oe1UVohkohJiugaagaeco";
      oldValue = oldValue.replaceAll(Pattern.quote("\\{code}"), marker2);

      // radeox gets an error, if {code} is not a closed tag. prevent at
      // least the case with one single statement.
      int nrOfCodeStatements = countOccurrences(oldValue, "{code}");
      String marker3 = "shagheiph6enieNo0theph9aique0EihoChae6ve2edie4Pohwaok8thaoda";
      if (nrOfCodeStatements == 1) {
        oldValue = oldValue.replaceAll(Pattern.quote("{code}"), marker3);
      }
      if (nrOfCodeStatements % 2 != 0 && nrOfCodeStatements != 1) {
        Formatter fInst = Formatter.getInstance(new Locale("olat"));
        fInst.log(
            "There will be a Warning/NPE from Radeox soon, as there are not enough {code} statements in a text.");
        fInst.log("Old value of text will be kept! " + oldValue);
      }

      // added for compatibility with wikimedia syntax used in the new wiki component.
      // WikiMarkupComponent
      // filters " ''' " for bold and " ''''' " for bold/italic
      oldValue =
          oldValue.replaceAll(
              "(^|>|[\\p{Punct}\\p{Space}]+)'{3}(.*?)'{3}([\\p{Punct}\\p{Space}]+|<|$)",
              "$1*$2*$3");
      oldValue =
          oldValue.replaceAll(
              "(^|>|[\\p{Punct}\\p{Space}]+)'{5}(.*?)'{5}([\\p{Punct}\\p{Space}]+|<|$)",
              "$1_*$2*_$3");

      // try-catch not usable, as Radeox doesn't throw an exception,
      // it just prints warnings and returns unconverted value!
      newValue = engineWithContext.render(oldValue, baseRenderContext);

      // convert back
      newValue = newValue.replaceAll(marker1, Matcher.quoteReplacement("{$}"));
      newValue = newValue.replaceAll(marker2, Matcher.quoteReplacement("\\{code}"));
      newValue = newValue.replaceAll(marker3, Matcher.quoteReplacement("{code}"));

      return newValue;
    } else return null;
  }
 static {
   REGEX_URL_1 =
       ImgurUserGalleryFragment.captureMinimumLength("[a-zA-Z0-9]", 4)
           + "\\."
           + Pattern.quote("imgur.com")
           + "(?:/.*)?";
   REGEX_URL_2 = Pattern.quote("imgur.com") + "/user/" + CAPTURE_ALPHANUMERIC_REPEATING + "/?";
   REGEX_URL =
       "(?:http://www.|https://www.|https://|http://|www.)?"
           + ImgurUserGalleryFragment.matchOne(REGEX_URL_1, REGEX_URL_2);
   BREADCRUMB_PARENT_CLASS = ImgurFragment.class;
 }
  // Derived from http://stackoverflow.com/a/3054692/250076
  public static File getRelativeFile(File targetFile, File baseFile) {
    try {
      targetFile = targetFile.getCanonicalFile();
      baseFile = baseFile.getCanonicalFile();
    } catch (IOException ignored) {
    }
    String pathSeparator = File.separator;
    String basePath = baseFile.getAbsolutePath();
    String normalizedTargetPath = normalize(targetFile.getAbsolutePath(), pathSeparator);
    String normalizedBasePath = normalize(basePath, pathSeparator);

    String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator));
    String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator));

    StringBuilder common = new StringBuilder();

    int commonIndex = 0;
    while (commonIndex < target.length
        && commonIndex < base.length
        && target[commonIndex].equals(base[commonIndex])) {
      common.append(target[commonIndex]).append(pathSeparator);
      commonIndex++;
    }

    if (commonIndex == 0) {
      throw new Error(
          "No common path element found for '"
              + normalizedTargetPath
              + "' and '"
              + normalizedBasePath
              + '\'');
    }

    boolean baseIsFile = true;

    if (baseFile.exists()) {
      baseIsFile = baseFile.isFile();
    } else if (basePath.endsWith(pathSeparator)) {
      baseIsFile = false;
    }

    StringBuilder relative = new StringBuilder();

    if (base.length != commonIndex) {
      int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex;

      for (int i = 0; i < numDirsUp; i++) {
        relative.append("..").append(pathSeparator);
      }
    }
    relative.append(normalizedTargetPath.substring(common.length()));
    return new File(relative.toString());
  }
Exemple #29
0
 public FormatValue(String par1, String... par2) {
   if (!isEmpty(par1) && !isEmpty(par2)) {
     this.name = par1;
     this.values = par2;
     for (String value : values) {
       String name = value.split(Pattern.quote(VAR_SEP))[0];
       String val = value.split(Pattern.quote(VAR_SEP))[1];
       Value fval = new Value(name, val);
       data_values.add(fval);
     }
   }
 }
Exemple #30
0
  private void selectProjectFiles(SWTBotTree tree, String project, String[] files) {
    for (SWTBotTreeItem item : tree.getAllItems()) while (item.isChecked()) item.uncheck();

    for (String file : files) {
      String[] nodes = file.split("/|\\\\");
      List<String> regex = new ArrayList<String>(nodes.length + 1);
      regex.add(Pattern.quote(project));

      for (String node : nodes) regex.add(Pattern.quote(node));

      WidgetUtil.getTreeItemWithRegex(tree, regex.toArray(new String[0])).check();
    }
  }