Exemplo n.º 1
0
  /**
   * This function returns the matched string in input when the pattern is found.
   *
   * @param pattern pattern string to match
   * @param input input string
   * @return returns the portion of the matched string in the input
   * @exception throws a FrameworkException when either pattern/input is null.
   */
  public static String getMatch(String pattern, String input) throws FrameworkException {
    if (input == null || pattern == null) {
      throw new FrameworkException(
          "RegexUtils: getMatch(): input or pattern is null."
              + "input ="
              + input
              + ", "
              + "pattern = "
              + pattern);
    }

    Perl5Util util = new Perl5Util();
    boolean isMatched = false;
    MatchResult matchResult = null;

    // default return value is the original input
    String result = input;

    pattern = makePerl5MatchPattern(pattern);

    if (util.match(pattern, input)) {
      matchResult = util.getMatch();
      result = matchResult.toString();
    }

    return result;
  }
 private String parseDatakey(String dataKey) {
   String result = dataKey;
   RegExp regex = RegExp.compile("([^\\\\/:*?\"<>|\r\n]+$)");
   MatchResult matcher = regex.exec(dataKey);
   if (regex.test(dataKey)) {
     result = matcher.getGroup(1);
   }
   return result;
 }
Exemplo n.º 3
0
 public static void test2() {
   MatchInterface tool =
       new MatchInterface("testPic/3.jpg", "testPic/a.jpg", 63, 515, 127, 708, 480, 800);
   MatchResult result = tool.getMatchResult();
   System.out.println(result.startx);
   System.out.println(result.starty);
   System.out.println(result.width);
   System.out.println(result.height);
   System.out.println(result.successflag);
   result.dispResult();
 }
Exemplo n.º 4
0
 @Override
 public int compareTo(MatchResult o) {
   int cmp = Integer.compare(this.getExact(), o.getExact());
   if (cmp == 0) {
     cmp = Integer.compare(this.getAssignable(), o.getAssignable());
     if (cmp == 0) {
       cmp = Integer.compare(this.getCoercible(), o.getCoercible());
     }
   }
   return cmp;
 }
Exemplo n.º 5
0
  /**
   * This function replace only the first pattern matched with the replacement.
   *
   * @param pattern pattern string to match
   * @param input input string
   * @param replacement replacement string
   * @return returns the processed string
   * @exception throws a FrameworkException when the pattern/replacement is null.
   */
  public static String replaceLast(String pattern, String input, String replacement)
      throws FrameworkException {
    if ((pattern == null) || (input == null) || (replacement == null)) {
      throw new FrameworkException(
          "RegexUtil: replaceLast(): pattern or input cannot be null. "
              + "pattern = "
              + pattern
              + "input = "
              + input
              + "replacement = "
              + replacement);
    }

    Perl5Util util = new Perl5Util();
    MatchResult matchResult = null;
    String result = null;
    String pre = null;
    String post = null;
    StringBuffer resultBuffer = new StringBuffer();

    int length = input.length();

    String regex = makePerl5SubstitutionPattern(pattern, replacement);
    pattern = makePerl5MatchPattern(pattern);

    // counts the number of match and grab the last one
    while (util.match(pattern, input)) {
      // getting the string before match
      pre = util.preMatch();
      resultBuffer.append(pre);

      // get the matched string
      matchResult = util.getMatch();
      resultBuffer.append(matchResult.toString());

      // get the post string after the match
      post = util.postMatch();

      // the post becomes the new input
      input = post;
    }

    // get the last match found
    matchResult = util.getMatch();

    // do the string replacement on the pattern found
    result = util.substitute(regex, matchResult.toString());

    resultBuffer.append(result);
    resultBuffer.append(post);

    return resultBuffer.toString();
  }
Exemplo n.º 6
0
 public static void test3() {
   MatchContext context;
   context = new MatchContext(new EnsembleAlgorithm());
   ImageObj imgobj = new ImageObj();
   imgobj.setSource("D:1.png");
   imgobj.setTemplate("D:a.png");
   imgobj.setStartx(354);
   imgobj.setStarty(24);
   imgobj.setEndx(515);
   imgobj.setEndy(87);
   imgobj.setWidth(540);
   imgobj.setHeight(960);
   MatchResult result = context.contextInterface(imgobj);
   result.dispResult();
   imgobj.writeResult(result, "result.jpg");
 }
Exemplo n.º 7
0
 public static void test1() {
   MatchContext context;
   context = new MatchContext(new EnsembleAlgorithm());
   ImageObj imgobj = new ImageObj();
   imgobj.setSource("D:\\itestin\\512.png");
   imgobj.setTemplate("D:\\itestin\\512a.png");
   imgobj.setStartx(376);
   imgobj.setStarty(172);
   imgobj.setEndx(595);
   imgobj.setEndy(269);
   imgobj.setWidth(540);
   imgobj.setHeight(960);
   MatchResult result = context.contextInterface(imgobj);
   result.dispResult();
   imgobj.writeResult(result, "result.jpg");
 }
  @Override
  public void handle(final HTTPRequestContext context, final HttpControl httpControl)
      throws Exception {

    final MatchResult result = (MatchResult) httpControl.data(RequestDispatchHandler.MATCH_RESULT);
    final Map<String, Object> args =
        (Map<String, Object>) httpControl.data(ArgsHandler.PREPARE_ARGS);

    // get class instance
    final Method invokeHolder = result.getProcessorInfo().getInvokeHolder();
    final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
    final Object classHolder = beanManager.getReference(invokeHolder.getDeclaringClass());

    final Object ret = invokeHolder.invoke(classHolder, args.values().toArray());

    httpControl.data(INVOKE_RESULT, ret);
  }
Exemplo n.º 9
0
  /**
   * The function checks and handles the situation where another begin token is found in between the
   * first begin token and the first end token. Such first beginToken is ignored. The current input
   * to be passed in to the replacement function will be the string between the LAST begin token and
   * the FIRST end token found.
   *
   * @param beginToken the pattern to look for
   * @param current input string
   * @param resultBuffer the buffer to hold the result
   * @return returns a Vector containing the substrings of the input that occur
   */
  private static final String skipOrphanedBeginToken(
      String beginToken, String current, StringBuffer resultBuffer) {
    Perl5Util util = new Perl5Util();
    boolean nextBeginTokenMatch = true;
    MatchResult matchResult = null;
    String remainderStr = null;
    String subCurrent = null;
    StringBuffer currentBuffer = new StringBuffer();
    String pre = null;

    // subCurrent is copy of the current to check if there is any next beginTokens
    subCurrent = current;

    while (nextBeginTokenMatch) {
      nextBeginTokenMatch = util.match(beginToken, subCurrent);

      if (nextBeginTokenMatch == true) {
        // pre is the string before the beginToken
        pre = util.preMatch();
        currentBuffer.append(pre);

        // get the  matched beginToken
        matchResult = util.getMatch();
        currentBuffer.append(matchResult.toString());

        // get the remaining string after the beginToken
        remainderStr = util.postMatch();
        subCurrent = remainderStr;
      } else // there is no match
      {
        // appending the string before the last begin token to the result
        resultBuffer.append(currentBuffer.toString());

        // finally get the string to perform the substitution on
        current = subCurrent;
        break;
      }
    } // while

    return current;
  }
Exemplo n.º 10
0
  public static void main(String[] args) {
    String dir = "/Users/argan/Opensource/myown/binary-refactor/jars";
    String jar2 = "/Users/argan/crack/jrebel-4.0/jrebel/jrebel.jar";

    MatchResult result = BinaryMatcher.match(jar2, dir);

    Log.debug("Match count: %d ", result.getResult().size());

    for (Map.Entry<String, Set<ClassMatchResult>> c : result.getResult().entrySet()) {
      Log.debug("=== matches for %s ===", c.getKey());
      for (ClassMatchResult cc : c.getValue()) {
        Log.debug("  class : %s = %s", cc.getLeftName(), cc.getRightName());
        for (Pair<FieldMatchResult, FieldMatchResult> fp : cc.getFields()) {
          Log.debug("    F : %s = %s ", fp.getLeft(), fp.getRight());
        }
        for (Pair<MethodMatchResult, MethodMatchResult> fp : cc.getMethods()) {
          Log.debug("    M : %s = %s ", fp.getLeft(), fp.getRight());
        }
      }
    }
  }
Exemplo n.º 11
0
  @Override
  protected MatchResult match(final List<LeafPattern> left, List<LeafPattern> collected) {
    if (collected == null) {
      collected = list();
    }

    List<LeafPattern> l = left;
    List<LeafPattern> c = collected;

    for (final Pattern pattern : getChildren()) {
      final MatchResult m = pattern.match(l, c);

      l = m.getLeft();
      c = m.getCollected();

      if (!m.matched()) {
        return new MatchResult(false, left, collected);
      }
    }

    return new MatchResult(true, l, c);
  }
Exemplo n.º 12
0
 /** Parse a string of the form [x1,y1},[x2,y2},...,[xN,yN} into a list of Points ([int,int]) */
 public static List<Point> parseString(String str) throws NumberFormatException {
   if (StringUtil.isNullString(str)) {
     throw new IllegalArgumentException("Must supply non-empty string");
   }
   ArrayList<Point> res = new ArrayList<Point>();
   Perl5Matcher matcher = RegexpUtil.getMatcher();
   while (matcher.contains(str, ONE_POINT_PAT)) {
     MatchResult matchResult = matcher.getMatch();
     String xstr = matchResult.group(1);
     String ystr = matchResult.group(2);
     str = matchResult.group(3);
     try {
       int x = Integer.parseInt(xstr);
       int y = Integer.parseInt(ystr);
       res.add(new Point(x, y));
     } catch (NumberFormatException e) {
       throw new IllegalArgumentException("bad point [" + xstr + "," + ystr + "] in " + str);
     }
   }
   res.trimToSize();
   return res;
 }
Exemplo n.º 13
0
  private void start(CmdArgs args) {
    String action = args.get("action", "").toLowerCase();
    args.put("graph.location", "./graph-cache");
    if (action.equals("import")) {
      String vehicle = args.get("vehicle", "car").toLowerCase();
      args.put("graph.flagEncoders", vehicle);
      args.put("osmreader.osm", args.get("datasource", ""));

      // standard should be to remove disconnected islands
      args.put("prepare.minNetworkSize", 200);
      args.put("prepare.minOneWayNetworkSize", 200);
      GraphHopper hopper = new GraphHopper().init(args);
      hopper.setCHEnable(false);
      hopper.importOrLoad();

    } else if (action.equals("match")) {
      GraphHopper hopper = new GraphHopper().init(args);
      hopper.setCHEnable(false);
      logger.info("loading graph from cache");
      hopper.load("./graph-cache");
      FlagEncoder firstEncoder = hopper.getEncodingManager().fetchEdgeEncoders().get(0);
      GraphHopperStorage graph = hopper.getGraphHopperStorage();

      int gpxAccuracy = args.getInt("gpxAccuracy", 15);
      String instructions = args.get("instructions", "");
      logger.info("Setup lookup index. Accuracy filter is at " + gpxAccuracy + "m");
      LocationIndexMatch locationIndex =
          new LocationIndexMatch(graph, (LocationIndexTree) hopper.getLocationIndex(), gpxAccuracy);
      MapMatching mapMatching = new MapMatching(graph, locationIndex, firstEncoder);
      mapMatching.setSeparatedSearchDistance(args.getInt("separatedSearchDistance", 500));
      mapMatching.setMaxNodesToVisit(args.getInt("maxNodesToVisit", 1000));
      mapMatching.setForceRepair(args.getBool("forceRepair", false));

      // do the actual matching, get the GPX entries from a file or via stream
      String gpxLocation = args.get("gpx", "");
      File[] files = getFiles(gpxLocation);

      logger.info("Now processing " + files.length + " files");
      StopWatch importSW = new StopWatch();
      StopWatch matchSW = new StopWatch();

      Translation tr = new TranslationMap().doImport().get(instructions);

      for (File gpxFile : files) {
        try {
          importSW.start();
          List<GPXEntry> inputGPXEntries =
              new GPXFile().doImport(gpxFile.getAbsolutePath()).getEntries();
          importSW.stop();
          matchSW.start();
          MatchResult mr = mapMatching.doWork(inputGPXEntries);
          matchSW.stop();
          System.out.println(gpxFile);
          System.out.println(
              "\tmatches:\t"
                  + mr.getEdgeMatches().size()
                  + ", gps entries:"
                  + inputGPXEntries.size());
          System.out.println(
              "\tgpx length:\t"
                  + (float) mr.getGpxEntriesLength()
                  + " vs "
                  + (float) mr.getMatchLength());
          System.out.println(
              "\tgpx time:\t"
                  + mr.getGpxEntriesMillis() / 1000f
                  + " vs "
                  + mr.getMatchMillis() / 1000f);

          String outFile = gpxFile.getAbsolutePath() + ".res.gpx";
          System.out.println("\texport results to:" + outFile);

          InstructionList il;
          if (instructions.isEmpty()) {
            il = new InstructionList(null);
          } else {
            AltResponse matchGHRsp = new AltResponse();
            Path path = mapMatching.calcPath(mr);
            new PathMerger().doWork(matchGHRsp, Collections.singletonList(path), tr);
            il = matchGHRsp.getInstructions();
          }

          new GPXFile(mr, il).doExport(outFile);
        } catch (Exception ex) {
          importSW.stop();
          matchSW.stop();
          logger.error("Problem with file " + gpxFile + " Error: " + ex.getMessage());
        }
      }
      System.out.println(
          "gps import took:" + importSW.getSeconds() + "s, match took: " + matchSW.getSeconds());

    } else if (action.equals("getbounds")) {
      String gpxLocation = args.get("gpx", "");
      File[] files = getFiles(gpxLocation);
      BBox bbox = BBox.createInverse(false);
      for (File gpxFile : files) {
        List<GPXEntry> inputGPXEntries =
            new GPXFile().doImport(gpxFile.getAbsolutePath()).getEntries();
        for (GPXEntry entry : inputGPXEntries) {
          if (entry.getLat() < bbox.minLat) {
            bbox.minLat = entry.getLat();
          }
          if (entry.getLat() > bbox.maxLat) {
            bbox.maxLat = entry.getLat();
          }
          if (entry.getLon() < bbox.minLon) {
            bbox.minLon = entry.getLon();
          }
          if (entry.getLon() > bbox.maxLon) {
            bbox.maxLon = entry.getLon();
          }
        }
      }

      System.out.println("max bounds: " + bbox);

      // show download only for small areas
      if (bbox.maxLat - bbox.minLat < 0.1 && bbox.maxLon - bbox.minLon < 0.1) {
        double delta = 0.01;
        System.out.println(
            "Get small areas via\n"
                + "wget -O extract.osm 'http://overpass-api.de/api/map?bbox="
                + (bbox.minLon - delta)
                + ","
                + (bbox.minLat - delta)
                + ","
                + (bbox.maxLon + delta)
                + ","
                + (bbox.maxLat + delta)
                + "'");
      }
    } else {
      System.out.println(
          "Usage: Do an import once, then do the matching\n"
              + "./map-matching action=import datasource=your.pbf\n"
              + "./map-matching action=match gpx=your.gpx\n"
              + "./map-matching action=match gpx=.*gpx\n\n"
              + "Or start in-built matching web service\n"
              + "./map-matching action=start-server\n\n");
    }
  }
Exemplo n.º 14
0
  /*
   * This class duplicates code in javax.el.Util. When making changes keep
   * the code in sync.
   */
  @SuppressWarnings("null")
  public static Method getMethod(
      Object base, Object property, Class<?>[] paramTypes, Object[] paramValues)
      throws MethodNotFoundException {
    if (base == null || property == null) {
      throw new MethodNotFoundException(
          MessageFactory.get("error.method.notfound", base, property, paramString(paramTypes)));
    }

    String methodName = (property instanceof String) ? (String) property : property.toString();

    int paramCount;
    if (paramTypes == null) {
      paramCount = 0;
    } else {
      paramCount = paramTypes.length;
    }

    Method[] methods = base.getClass().getMethods();
    Map<Method, MatchResult> candidates = new HashMap<>();

    for (Method m : methods) {
      if (!m.getName().equals(methodName)) {
        // Method name doesn't match
        continue;
      }

      Class<?>[] mParamTypes = m.getParameterTypes();
      int mParamCount;
      if (mParamTypes == null) {
        mParamCount = 0;
      } else {
        mParamCount = mParamTypes.length;
      }

      // Check the number of parameters
      if (!(paramCount == mParamCount || (m.isVarArgs() && paramCount >= mParamCount))) {
        // Method has wrong number of parameters
        continue;
      }

      // Check the parameters match
      int exactMatch = 0;
      int assignableMatch = 0;
      int coercibleMatch = 0;
      boolean noMatch = false;
      for (int i = 0; i < mParamCount; i++) {
        // Can't be null
        if (mParamTypes[i].equals(paramTypes[i])) {
          exactMatch++;
        } else if (i == (mParamCount - 1) && m.isVarArgs()) {
          Class<?> varType = mParamTypes[i].getComponentType();
          for (int j = i; j < paramCount; j++) {
            if (isAssignableFrom(paramTypes[j], varType)) {
              assignableMatch++;
            } else {
              if (paramValues == null) {
                noMatch = true;
                break;
              } else {
                if (isCoercibleFrom(paramValues[j], varType)) {
                  coercibleMatch++;
                } else {
                  noMatch = true;
                  break;
                }
              }
            }
            // Don't treat a varArgs match as an exact match, it can
            // lead to a varArgs method matching when the result
            // should be ambiguous
          }
        } else if (isAssignableFrom(paramTypes[i], mParamTypes[i])) {
          assignableMatch++;
        } else {
          if (paramValues == null) {
            noMatch = true;
            break;
          } else {
            if (isCoercibleFrom(paramValues[i], mParamTypes[i])) {
              coercibleMatch++;
            } else {
              noMatch = true;
              break;
            }
          }
        }
      }
      if (noMatch) {
        continue;
      }

      // If a method is found where every parameter matches exactly,
      // return it
      if (exactMatch == paramCount) {
        return getMethod(base.getClass(), m);
      }

      candidates.put(m, new MatchResult(exactMatch, assignableMatch, coercibleMatch));
    }

    // Look for the method that has the highest number of parameters where
    // the type matches exactly
    MatchResult bestMatch = new MatchResult(0, 0, 0);
    Method match = null;
    boolean multiple = false;
    for (Map.Entry<Method, MatchResult> entry : candidates.entrySet()) {
      int cmp = entry.getValue().compareTo(bestMatch);
      if (cmp > 0 || match == null) {
        bestMatch = entry.getValue();
        match = entry.getKey();
        multiple = false;
      } else if (cmp == 0) {
        multiple = true;
      }
    }
    if (multiple) {
      if (bestMatch.getExact() == paramCount - 1) {
        // Only one parameter is not an exact match - try using the
        // super class
        match = resolveAmbiguousMethod(candidates.keySet(), paramTypes);
      } else {
        match = null;
      }

      if (match == null) {
        // If multiple methods have the same matching number of parameters
        // the match is ambiguous so throw an exception
        throw new MethodNotFoundException(
            MessageFactory.get("error.method.ambiguous", base, property, paramString(paramTypes)));
      }
    }

    // Handle case where no match at all was found
    if (match == null) {
      throw new MethodNotFoundException(
          MessageFactory.get("error.method.notfound", base, property, paramString(paramTypes)));
    }

    return getMethod(base.getClass(), match);
  }
Exemplo n.º 15
0
 /**
  * Returns the set of matching events for a given control step.
  *
  * @param step the control step for which matches are to be found; non-{@code null}
  */
 public MatchResultSet computeMatches(final Step step) {
   final MatchResultSet result = new MatchResultSet();
   if (DEBUG) {
     System.out.printf("Matches for %s, %s%n  ", this.state, this.state.getGraph());
   }
   assert step != null;
   // there are three reasons to want to use the parent matches: to
   // save matching time, to reuse added nodes, and to find confluent
   // diamonds. The first is only relevant if the rule is not (re)enabled,
   // the third only if the parent match target is already closed
   final boolean isDisabled = isDisabled(step.getRuleCall());
   boolean isModifying = step.isModifying();
   if (!isDisabled) {
     for (GraphTransition trans : this.parentTransMap) {
       if (trans instanceof RuleTransition) {
         RuleTransition ruleTrans = (RuleTransition) trans;
         if (ruleTrans.getEvent().getRule().equals(step.getRule())) {
           MatchResult match = ruleTrans.getKey();
           if (isModifying) {
             // we can reuse the event but not the control step
             match = new MatchResult(match.getEvent(), step);
           }
           result.add(match);
           if (DEBUG) {
             System.out.print(" T" + System.identityHashCode(trans.getEvent()));
           }
         }
       }
     }
   }
   if (isDisabled || isEnabled(step.getRuleCall())) {
     // the rule was possibly enabled afresh, so we have to add the fresh
     // matches
     RuleToHostMap boundMap = extractBinding(step);
     if (boundMap != null) {
       final Record record = this.record;
       Visitor<Proof, Boolean> eventCollector =
           new Visitor<Proof, Boolean>(false) {
             @Override
             protected boolean process(Proof object) {
               RuleEvent event = record.getEvent(object);
               // only look up the event in the parent map if
               // the rule was disabled, as otherwise the result
               // already contains all relevant parent results
               MatchResult match = new MatchResult(event, step);
               if (isDisabled) {
                 match = getParentTrans(match);
               }
               result.add(match);
               if (DEBUG) {
                 System.out.print(" E" + System.identityHashCode(match.getEvent()));
                 checkEvent(match.getEvent());
               }
               setResult(true);
               return true;
             }
           };
       step.getRule().traverseMatches(this.state.getGraph(), boundMap, eventCollector);
     }
   }
   if (DEBUG) {
     System.out.println();
   }
   return result;
 }
Exemplo n.º 16
0
 public void setResult(MatchResult result) {
   setRedWin(result.wasRedWin());
   setTwoGame(result.wasTwoGame());
   pushResult();
 }