Exemplo n.º 1
1
Arquivo: Macro.java Projeto: bramk/bnd
  public String _range(String args[]) {
    verifyCommand(args, _rangeHelp, _rangePattern, 2, 3);
    Version version = null;
    if (args.length >= 3) version = new Version(args[2]);
    else {
      String v = domain.getProperty("@");
      if (v == null) return null;
      version = new Version(v);
    }
    String spec = args[1];

    Matcher m = RANGE_MASK.matcher(spec);
    m.matches();
    String floor = m.group(1);
    String floorMask = m.group(2);
    String ceilingMask = m.group(3);
    String ceiling = m.group(4);

    String left = version(version, floorMask);
    String right = version(version, ceilingMask);
    StringBuilder sb = new StringBuilder();
    sb.append(floor);
    sb.append(left);
    sb.append(",");
    sb.append(right);
    sb.append(ceiling);

    String s = sb.toString();
    VersionRange vr = new VersionRange(s);
    if (!(vr.includes(vr.getHigh()) || vr.includes(vr.getLow()))) {
      domain.error(
          "${range} macro created an invalid range %s from %s and mask %s", s, version, spec);
    }
    return sb.toString();
  }
Exemplo n.º 2
1
Arquivo: Macro.java Projeto: bramk/bnd
 public static void verifyCommand(
     String args[],
     @SuppressWarnings("unused") String help,
     Pattern[] patterns,
     int low,
     int high) {
   String message = "";
   if (args.length > high) {
     message = "too many arguments";
   } else if (args.length < low) {
     message = "too few arguments";
   } else {
     for (int i = 0; patterns != null && i < patterns.length && i < args.length; i++) {
       if (patterns[i] != null) {
         Matcher m = patterns[i].matcher(args[i]);
         if (!m.matches())
           message +=
               String.format(
                   "Argument %s (%s) does not match %s%n", i, args[i], patterns[i].pattern());
       }
     }
   }
   if (message.length() != 0) {
     StringBuilder sb = new StringBuilder();
     String del = "${";
     for (String arg : args) {
       sb.append(del);
       sb.append(arg);
       del = ";";
     }
     sb.append("}, is not understood. ");
     sb.append(message);
     throw new IllegalArgumentException(sb.toString());
   }
 }
  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));
    }
  }
Exemplo n.º 4
0
 /**
  * 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();
   }
 }
  public boolean isPresent2(String patternStr) {
    Pattern p = Pattern.compile(patternStr);
    Matcher m = p.matcher(string2);
    boolean b = m.matches();

    return b;
  }
Exemplo n.º 6
0
 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
     throws IOException {
   if (m != null) m.reset(root.relativize(dir).toString());
   return m == null || m.matches() || m.hitEnd()
       ? FileVisitResult.CONTINUE
       : FileVisitResult.SKIP_SUBTREE;
 }
Exemplo n.º 7
0
 public static String removePrimerLR(String pname) {
   Matcher m = primerLRPattern.matcher(pname);
   if (!m.matches()) {
     throw new IllegalArgumentException(pname);
   }
   return m.group(1);
 }
Exemplo n.º 8
0
  private static String expand(String str) {
    if (str == null) {
      return null;
    }

    StringBuilder result = new StringBuilder();
    Pattern re = Pattern.compile("^(.*?)\\$\\{([^}]*)\\}(.*)");
    while (true) {
      Matcher matcher = re.matcher(str);
      if (matcher.matches()) {
        result.append(matcher.group(1));
        String property = matcher.group(2);
        if (property.equals("/")) {
          property = "file.separator";
        }
        String value = System.getProperty(property);
        if (value != null) {
          result.append(value);
        }
        str = matcher.group(3);
      } else {
        result.append(str);
        break;
      }
    }
    return result.toString();
  }
Exemplo n.º 9
0
 /**
  * Returns the value of a specified fieldname from the specified hashmap and returns an integer
  * value or throws an exception if the value is not an integer
  */
 private int getIntValue(String fieldname, Map<String, String> extraparams) {
   Matcher checkint = Pattern.compile("^\\d+$").matcher(fieldname);
   int rv;
   if (checkint.matches()) {
     rv = Integer.parseInt(fieldname);
   } else {
     if (extraparams.containsKey(fieldname)) {
       rv = Integer.parseInt(extraparams.get(fieldname));
     } else {
       rv = -1;
       throw new TDTException(
           "No integer value for " + fieldname + " can be found - check extraparams");
     }
   }
   return rv;
 }
Exemplo n.º 10
0
 public static String getChrom(String chromName) {
   Matcher m = chromPattern.matcher(chromName);
   if (!m.matches()) {
     return chromName;
   }
   return m.group(1);
 }
Exemplo n.º 11
0
 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
   if (attrs.isRegularFile()) {
     if (m != null) m.reset(root.relativize(file).toString());
     if (m == null || m.matches())
       futures.add(exec.submit(new FileLoader(root, file, blocSize)));
   }
   return FileVisitResult.CONTINUE;
 }
Exemplo n.º 12
0
 public String getArtifactIdFromCoord(String coord) {
   Matcher m = COORD_P.matcher(coord);
   if (m.matches()) {
     return m.group(2);
   } else {
     return null;
   }
 }
Exemplo n.º 13
0
 public Coords(String entry) {
   Matcher m = coordsPattern.matcher(entry);
   if (!m.matches()) {
     throw new IllegalArgumentException(entry);
   }
   chrom = m.group(1);
   start = Integer.parseInt(m.group(2));
   end = Integer.parseInt(m.group(3));
   strand = m.group(4).charAt(0);
 }
  // todo: give options for document splitting. A line or the whole file or
  // sentence splitting as now
  public Iterator<List<IN>> getIterator(Reader r) {
    Tokenizer<IN> tokenizer = tokenizerFactory.getTokenizer(r);
    // PTBTokenizer.newPTBTokenizer(r, false, true);
    List<IN> words = new ArrayList<IN>();
    IN previous = tokenFactory.makeToken();
    StringBuilder prepend = new StringBuilder();

    /*
     * This changes SGML tags into whitespace -- it should maybe be moved
     * elsewhere
     */
    while (tokenizer.hasNext()) {
      IN w = tokenizer.next();
      String word = w.get(CoreAnnotations.TextAnnotation.class);
      Matcher m = sgml.matcher(word);
      if (m.matches()) {

        String before = StringUtils.getNotNullString(w.get(CoreAnnotations.BeforeAnnotation.class));
        String after = StringUtils.getNotNullString(w.get(CoreAnnotations.AfterAnnotation.class));
        prepend.append(before).append(word);
        String previousTokenAfter =
            StringUtils.getNotNullString(previous.get(CoreAnnotations.AfterAnnotation.class));
        previous.set(AfterAnnotation.class, previousTokenAfter + word + after);
        // previous.appendAfter(w.word() + w.after());
      } else {

        String before = StringUtils.getNotNullString(w.get(CoreAnnotations.BeforeAnnotation.class));
        if (prepend.length() > 0) {
          w.set(BeforeAnnotation.class, prepend.toString() + before);
          // w.prependBefore(prepend.toString());
          prepend = new StringBuilder();
        }
        words.add(w);
        previous = w;
      }
    }

    List<List<IN>> sentences = wts.process(words);
    String after = "";
    IN last = null;
    for (List<IN> sentence : sentences) {
      int pos = 0;
      for (IN w : sentence) {
        w.set(PositionAnnotation.class, Integer.toString(pos));
        after = StringUtils.getNotNullString(w.get(CoreAnnotations.AfterAnnotation.class));
        w.remove(AfterAnnotation.class);
        last = w;
      }
    }
    if (last != null) {
      last.set(AfterAnnotation.class, after);
    }

    return sentences.iterator();
  }
Exemplo n.º 15
0
 public static int[] decodePrimerName(String pname) {
   Matcher m = primerNamePattern.matcher(pname);
   if (!m.matches()) {
     throw new IllegalArgumentException(pname);
   }
   int[] a = new int[3];
   a[0] = Integer.parseInt(m.group(1));
   a[1] = Integer.parseInt(m.group(2));
   a[2] = Integer.parseInt(m.group(3));
   return a;
 }
 protected boolean shouldIgnoreBCCAddress(String address) {
   MilterServerService milterService = Config.getConfig().getMilterServerService();
   List<String> ignoreAddresses = milterService.getIgnoreBCCAddress();
   Matcher m = headerPattern2.matcher(address.toLowerCase(Locale.ENGLISH).trim());
   if (m.matches()) {
     String mailAddress = m.group(1);
     for (String ignoreAddress : ignoreAddresses) {
       if (ignoreAddress.equalsIgnoreCase(mailAddress)) return true;
     }
   } else {
     m = headerPattern3.matcher(address.toLowerCase(Locale.ENGLISH).trim());
     if (m.matches()) {
       String mailAddress = m.group(1);
       for (String ignoreAddress : ignoreAddresses) {
         if (ignoreAddress.equalsIgnoreCase(mailAddress)) return true;
       }
     }
   }
   return false;
 }
Exemplo n.º 17
0
 /**
  * Converts a colour from #rrggbb to Java Color object.
  *
  * @param rgb String e.g. #ff00ee
  * @return Colour
  * @throws IllegalArgumentException If colour string is not valid
  */
 protected Color convertRgb(String rgb) throws IllegalArgumentException {
   // Get colour parameter
   Matcher m = REGEX_RGB.matcher(rgb);
   if (!m.matches()) {
     throw new IllegalArgumentException(
         "MathML invalid colour '" + rgb + "'; expected #rrggbb (lower-case)");
   }
   return new Color(
       Integer.parseInt(m.group(1), 16),
       Integer.parseInt(m.group(2), 16),
       Integer.parseInt(m.group(3), 16));
 }
 /**
  * Returns an integer corresponding to the given experiment name. If the argument matches an
  * experiment name exactly, then that index is returned. Otherwise, the argument is treated as a
  * regexp, and the index of some experiment that matches it is returned.
  *
  * @param key The name, or regexp for the name, of the experiment to find.
  * @return The array index of the experiment, or -1 if not found.
  */
 public int findExperiment(String key) {
   if (exptIndices.containsKey(key)) {
     return exptIndices.get(key);
   }
   Pattern p = Pattern.compile(key);
   for (String k : exptIndices.keySet()) {
     Matcher m = p.matcher(k);
     if (m.matches()) {
       return exptIndices.get(k);
     }
   }
   return -1;
 }
  protected static String getMethodName(Test test) {
    String className;
    String desc = test.toString();
    Matcher matcher = methodpattern.matcher(desc);
    if (matcher.matches()) {
      className = matcher.group(1);

    } else {
      className = desc;
    }

    return className;
  }
Exemplo n.º 20
0
  /**
   * Handles info messages resulting from a query execution.
   *
   * @param msg info message
   * @return true if error was found
   */
  private boolean error(final String msg) {
    final String line = msg.replaceAll("[\\r\\n].*", "");
    Matcher m = XQERROR.matcher(line);
    int el, ec = 2;
    if (!m.matches()) {
      m = XMLERROR.matcher(line);
      if (!m.matches()) return true;
      el = Integer.parseInt(m.group(1));
      errFile = getEditor().file.path();
    } else {
      el = Integer.parseInt(m.group(1));
      ec = Integer.parseInt(m.group(2));
      errFile = m.group(3);
    }

    final EditorArea edit = find(IO.get(errFile), false);
    if (edit == null) return true;

    // find approximate error position
    final int ll = edit.last.length;
    int ep = ll;
    for (int e = 1, l = 1, c = 1; e < ll; ++c, e += cl(edit.last, e)) {
      if (l > el || l == el && c == ec) {
        ep = e;
        break;
      }
      if (edit.last[e] == '\n') {
        ++l;
        c = 0;
      }
    }
    if (ep < ll && Character.isLetterOrDigit(cp(edit.last, ep))) {
      while (ep > 0 && Character.isLetterOrDigit(cp(edit.last, ep - 1))) ep--;
    }
    edit.error(ep);
    errPos = ep;
    return true;
  }
  public JilterStatus header(String headerf, String headerv) {

    logger.debug("jilter header {name='" + headerf + "',value='" + headerv + "'}");
    StringBuffer header = new StringBuffer();
    header.append(headerf);
    header.append(": ");
    header.append(headerv);
    header.append("\n");
    try {
      bos.write(header.toString().getBytes());
    } catch (IOException io) {
      logger.error("jilter failed to write header field", io);
    }
    Matcher m = headerPattern1.matcher(headerf.toLowerCase(Locale.ENGLISH).trim());
    if (m.matches()) {
      logger.debug("jilter found to/bcc/cc header");
      String[] addresses = headerv.split(",");
      for (int i = 0; i < addresses.length; i++) {
        includeBCC = includeBCC | rcpts.remove(addresses[i].toLowerCase(Locale.ENGLISH).trim());
        logger.debug("jilter del recipient {recipient='" + addresses[i] + "'}");
        m = headerPattern2.matcher(addresses[i].toLowerCase(Locale.ENGLISH).trim());
        if (m.matches()) {
          String mailAddress = m.group(1);
          includeBCC = includeBCC | rcpts.remove(mailAddress);
          logger.debug("jilter del recipient {recipient='" + mailAddress + "'}");
        } else {
          m = headerPattern3.matcher(addresses[i].toLowerCase(Locale.ENGLISH).trim());
          if (m.matches()) {
            String mailAddress = m.group(1);
            includeBCC = includeBCC | rcpts.remove(mailAddress);
            logger.debug("jilter del recipient {recipient='" + mailAddress + "'}");
          }
        }
      }
    }
    return JilterStatus.SMFIS_CONTINUE;
  }
Exemplo n.º 22
0
 public static BlockNode create(String blockText) { // {{{
   String elements[] = blockText.trim().split("\\s+");
   String blockType = elements[0].toLowerCase();
   if (blockType.equals(BLOCK_IF)) {
     return new IfBlock(blockText.trim().substring(2).trim());
   } else if (blockType.equals(BLOCK_ELSE)) {
     return new ElseBlock();
   } else if (blockType.equals(BLOCK_ELSEIF)) {
     return new ElseBlock(blockText.trim().substring(6).trim());
   } else if (blockType.equals(BLOCK_ENDIF)) {
     return new EndIfBlock();
   } else if (blockType.equals(BLOCK_FOR)) {
     Matcher m = FOR_PATTERN.matcher(blockText);
     if (m.matches()) {
       return new ForBlock(m.group(1), m.group(2));
     } else {
       Matcher m2 = FOR_KV_PATTERN.matcher(blockText);
       if (m2.matches()) {
         return new ForKeyValBlock(m2.group(1), m2.group(2), m2.group(3));
       } else {
         System.out.println("badly formed for block");
         return null;
       }
     }
   } else if (blockType.equals(BLOCK_ENDFOR)) {
     return new EndForBlock();
   } else if (blockType.equals(BLOCK_NAMEDBLOCK)) {
     if (elements.length != 2) return null; // badly formed block
     return new StartNamedBlock(elements[1]);
   } else if (blockType.equals(BLOCK_ENDNAMEDBLOCK)) {
     return new EndNamedBlock();
   } else if (blockType.equals(BLOCK_EXTENDS)) {
     if (elements.length != 2) return null; // badly formed block
     return new ExtendsNode(elements[1]);
   }
   return null; // TODO
 } // }}}
Exemplo n.º 23
0
 private String htmlize(String msg) {
   StringBuilder sb = new StringBuilder();
   Pattern patMsgCat = Pattern.compile("\\[(.+?)\\].*");
   msg = msg.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
   for (String line : msg.split(lineSep)) {
     Matcher m = patMsgCat.matcher(line);
     String cls = "normal";
     if (m.matches()) {
       cls = m.group(1);
     }
     line = "<span class='" + cls + "'>" + line + "</span>";
     sb.append(line).append("<br>");
   }
   return sb.toString();
 }
Exemplo n.º 24
0
 @Override
 @EventHandler
 public void onChatReceived(ChatReceivedEvent event) {
   super.onChatReceived(event);
   String message = Util.stripColors(event.getMessage());
   if (message.startsWith("Please register with \"/register")) {
     String password = Util.generateRandomString(10 + random.nextInt(6));
     bot.say("/register " + password + " " + password);
   } else if (message.contains("You are not member of any faction.")
       && spamMessage != null
       && createFaction) {
     String msg = "/f create " + Util.generateRandomString(7 + random.nextInt(4));
     bot.say(msg);
   }
   for (String s : captchaList) {
     Matcher captchaMatcher = Pattern.compile(s).matcher(message);
     if (captchaMatcher.matches()) bot.say(captchaMatcher.group(1));
   }
 }
  private void buildXmlPropertiesFile() {
    System.out.println(
        "\nBuilding and checking your pipeline properties file -> " + truncPipePropFile);
    StringBuilder toPrint = new StringBuilder();

    // walk through the prop file
    String[] prop = IO.loadFileIntoStringArray(truncPipePropFile);
    Pattern val = Pattern.compile("(<entry key.+>)([D|A|B].*)</entry>");
    boolean missingFile = false;
    for (String s : prop) {
      // does it match a file needing prepending? Data/, Apps/, Bed/
      Matcher mat = val.matcher(s);
      if (mat.matches()) {
        File test = new File(referenceDir, mat.group(2));
        if (test.exists()) {
          System.out.println("Found\t" + test);
          toPrint.append(mat.group(1));
          toPrint.append(test.toString());
          toPrint.append("</entry>");
        } else {
          System.out.println("Misssing\t" + test);
          missingFile = true;
        }
      }
      // threads?
      else if (s.contains("threads"))
        toPrint.append("<entry key=\"threads\">" + threads + "</entry>");

      // nope just save it and add a line return
      else toPrint.append(s);
      toPrint.append("\n");
    }
    // anything missing? if so exit
    if (missingFile)
      Misc.printErrAndExit(
          "\nFailed to find all of the files in your properties file, see above.\n");

    // OK, write it out
    completePipelinePropFile = new File(outputDirectory, "pipelineProperties.xml");
    if (IO.writeString(toPrint.toString(), completePipelinePropFile) == false)
      Misc.printErrAndExit("Problem writing -> " + truncPipePropFile);
  }
Exemplo n.º 26
0
  public static void loadPermissions(URL url) throws IOException, PermissionParseException {

    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line;
    Pattern ignore = Pattern.compile("^\\s*(//.*)?$");
    Pattern valid =
        Pattern.compile("^\\s*permission\\s+(\\S+)" + "(\\s+\"([^\"]*)\"(,\\s+\"([^\"]*)\")?)?;$");

    Set<Permission> perms = new HashSet<Permission>();

    while ((line = in.readLine()) != null) {
      if (ignore.matcher(line).matches()) {
        continue;
      }

      Matcher matcher = valid.matcher(line);
      if (!matcher.matches()) {
        throw new PermissionParseException("invalid syntax: " + line);
      }

      int nGroups = matcher.groupCount();
      String type = matcher.group(1);
      String name = expand(nGroups >= 3 ? matcher.group(3) : null);
      String actions = expand(nGroups >= 5 ? matcher.group(5) : null);

      try {
        Permission perm = getPermission(type, name, actions);
        perms.add(perm);
      } catch (Throwable e) {
        String message =
            String.format(
                "could not instantiate permission: " + "type=%s name=%s actions=",
                type, name, actions);
        throw new PermissionParseException(message, e);
      }
    }

    in.close();

    permSet.addAll(perms);
  }
  public static void testParseRunProperties() throws Exception {
    Workspace ws = Workspace.getWorkspace(new File("src/test/ws"));
    Project project = ws.getProject("p1");

    ProjectLauncherImpl launcher = new ProjectLauncherImpl(project);
    launcher.prepare();

    String arg = launcher.getRunVM().iterator().next();
    String s = "-D" + LauncherConstants.LAUNCHER_PROPERTIES + "=";
    String propertiesPath = arg.substring(s.length());
    Matcher matcher = Pattern.compile("^([\"'])(.*)\\1$").matcher(propertiesPath);
    if (matcher.matches()) {
      propertiesPath = matcher.group(2);
    }

    Properties launchProps = new Properties();
    launchProps.load(new FileInputStream(new File(propertiesPath)));
    assertEquals(
        new File("src/test/ws/p1/generated/p1.jar").getAbsolutePath(),
        launchProps.get("launch.bundles"));
  }
Exemplo n.º 28
0
 /** This method will process each argument and assign new varibles */
 public void processArgs(String[] args) {
   Pattern pat = Pattern.compile("-[a-z]");
   for (int i = 0; i < args.length; i++) {
     String lcArg = args[i].toLowerCase();
     Matcher mat = pat.matcher(lcArg);
     if (mat.matches()) {
       char test = args[i].charAt(1);
       try {
         switch (test) {
           case 'f':
             fastas = IO.extractFiles(args[i + 1], "fasta");
             i++;
             break;
           case 'n':
             numberOfBases = Integer.parseInt(args[i + 1]);
             i++;
             break;
           case 'i':
             indexDirectory = new File(args[i + 1]);
             i++;
             break;
           case 'h':
             printDocs();
             System.exit(0);
           default:
             Misc.printExit("\nError: unknown option! " + mat.group());
         }
       } catch (Exception e) {
         Misc.printExit(
             "\nSorry, something doesn't look right with this parameter: -" + test + "\n");
       }
     }
   }
   // make index directory?
   if (indexDirectory == null) {
     indexDirectory = new File(fastas[0].getParentFile(), "IndexedSequences");
     indexDirectory.mkdir();
   }
 }
Exemplo n.º 29
0
 public static void processFile(BufferedReader in, BufferedWriter out, String context)
     throws Throwable {
   String tmpLine = in.readLine();
   while (tmpLine != null) {
     // check to see if the line matches the import directive
     Matcher matcher = includePattern.matcher(tmpLine);
     // if it doesn't match, just output the line, followed by a newline
     if (!matcher.matches()) {
       out.write(tmpLine);
       out.newLine();
       // if it matches
     } else {
       String fileName = matcher.group(1);
       // check if it has already been included
       if (!includeNames.contains(fileName)) {
         // if it hasn't, process it
         String newContext = contextFromFilename(fileName);
         processFile(getBufferedReader(fileName, context), out, context + newContext);
       }
     }
     tmpLine = in.readLine();
   }
   in.close();
 }
Exemplo n.º 30
0
  /**
   * Updates the config file during the upgrade process.
   *
   * @param configPath The original path to the file.
   * @param filter The filter to select entries. Only useful for modify change type.
   * @param changeType The change type which must be applied to ldif lines.
   * @param ldifLines The change record ldif lines. For ADD change type, the first line must be the
   *     dn. For DELETE change type, the first and only line must be the dn.
   * @throws IOException If an Exception occurs during the input output methods.
   * @return The changes number that have occurred.
   */
  static int updateConfigFile(
      final String configPath,
      final Filter filter,
      final ChangeOperationType changeType,
      final String... ldifLines)
      throws IOException {
    final File original = new File(configPath);
    final File copyConfig = File.createTempFile("copyConfig", ".tmp", original.getParentFile());

    int changeCount = 0;
    LDIFEntryReader entryReader = null;
    LDIFEntryWriter writer = null;
    try {
      final Schema schema = getUpgradeSchema();
      entryReader = new LDIFEntryReader(new FileInputStream(configPath)).setSchema(schema);

      writer = new LDIFEntryWriter(new FileOutputStream(copyConfig));
      writer.setWrapColumn(80);

      // Writes the header on the new file.
      writer.writeComment(INFO_CONFIG_FILE_HEADER.get());
      writer.setWrapColumn(0);

      boolean entryAlreadyExist = false;
      DN ldifDN = null;
      if (filter == null && (changeType == ADD || changeType == DELETE)) {
        // The first line should start with dn:
        ldifDN = DN.valueOf(ldifLines[0].replaceFirst("dn: ", ""));
      }
      final Filter f = filter != null ? filter : Filter.alwaysFalse();
      final Matcher matcher = f.matcher(schema);
      while (entryReader.hasNext()) {
        Entry entry = entryReader.readEntry();
        final DN entryDN = entry.getName();
        // Searching for the related entries
        if (changeType == MODIFY && matcher.matches(entry) == ConditionResult.TRUE) {
          try {
            final ModifyRequest mr =
                Requests.newModifyRequest(readLDIFLines(entryDN, changeType, ldifLines));
            entry = Entries.modifyEntryPermissive(entry, mr.getModifications());
            changeCount++;
            logger.debug(
                LocalizableMessage.raw("The following entry has been modified : %s", entryDN));
          } catch (Exception ex) {
            logger.error(LocalizableMessage.raw(ex.getMessage()));
          }
        }

        if (entryDN.equals(ldifDN)) {
          logger.debug(LocalizableMessage.raw("Entry %s found", entryDN));
          entryAlreadyExist = true;

          if (changeType == DELETE) {
            entry = null;
            changeCount++;
            logger.debug(
                LocalizableMessage.raw("The following entry has been deleted : %s", entryDN));
          }
        }

        if (entry != null) {
          writer.writeEntry(entry);
        }
      }

      if (changeType == ADD && !entryAlreadyExist) {
        final AddRequest ar = Requests.newAddRequest(ldifLines);
        writer.writeEntry(ar);
        logger.debug(
            LocalizableMessage.raw(
                "Entry successfully added %s in %s", ldifDN, original.getAbsolutePath()));
        changeCount++;
      }
    } catch (Exception ex) {
      throw new IOException(ex.getMessage());
    } finally {
      // The reader and writer must be close before renaming files.
      // Otherwise it causes exceptions under windows OS.
      StaticUtils.close(entryReader, writer);
    }

    try {
      // Renaming the file, overwriting previous one.
      rename(copyConfig, new File(configPath));
    } catch (IOException e) {
      logger.error(LocalizableMessage.raw(e.getMessage()));
      deleteRecursively(original);
      throw e;
    }

    return changeCount;
  }