Example #1
0
 public boolean compare(String baselinecontent, String testresult) throws Exception {
   StringReader baserdr = new StringReader(baselinecontent);
   StringReader resultrdr = new StringReader(testresult);
   // Diff the two files
   Diff diff = new Diff("Testing " + getTitle());
   boolean pass = !diff.doDiff(baserdr, resultrdr);
   baserdr.close();
   resultrdr.close();
   return pass;
 }
  public static List<String> analyze(String content) {
    List<String> resultList = null;
    try {
      // 创建分词对象
      resultList = new ArrayList<String>(1);
      resultList.add(content);
      IKAnalyzer analyer = new IKAnalyzer(true);
      analyer.setUseSmart(true);
      StringReader reader = new StringReader(content);
      // 分词
      TokenStream tokenStream = analyer.tokenStream("", reader);
      CharTermAttribute term = tokenStream.getAttribute(CharTermAttribute.class);
      // 遍历分词数据
      while (tokenStream.incrementToken()) {
        if (!term.toString().isEmpty()) {
          resultList.add(term.toString());
        }
      }
      reader.close();

    } catch (IOException ex) {
      logger.error("分词出错", ex);
    }
    return resultList;
  }
 /**
  * A static convience method for decoding an object from a String.
  *
  * <p>All exceptions are logged using LogMgr internally and then rethrown as GlueException with
  * the same message as written to the log.
  *
  * @param title The name to be given to the object when decoded.
  * @param text The Glue format text to be decoded.
  * @throws GlueException If unable to decode the string.
  */
 public static Object decodeString(String title, String text) throws GlueException {
   try {
     GlueDecoderImpl gd = new GlueDecoderImpl();
     StringReader in = null;
     try {
       in = new StringReader(text);
       GlueParser parser = new GlueParser(in);
       return parser.Decode(gd, gd.getState());
     } catch (ParseException ex) {
       throw new GlueException(ex);
     } catch (TokenMgrError ex) {
       throw new GlueException(ex);
     } finally {
       in.close();
     }
   } catch (GlueException ex) {
     String msg = ("Unable to Glue decode: " + title + "\n" + "  " + ex.getMessage());
     LogMgr.getInstance().log(LogMgr.Kind.Glu, LogMgr.Level.Severe, msg);
     throw new GlueException(msg);
   } catch (Exception ex) {
     String msg = Exceptions.getFullMessage("INTERNAL ERROR:", ex, true, true);
     LogMgr.getInstance().log(LogMgr.Kind.Glu, LogMgr.Level.Severe, msg);
     throw new GlueException(msg);
   }
 }
    public List<String> getAVDList() {
      if (buffer == null || buffer.length() < 1) return null;

      StringReader reader = new StringReader(buffer.toString());
      BufferedReader read = new BufferedReader(reader);
      String line = null;
      ArrayList<String> list = new ArrayList<String>();
      try {
        while ((line = read.readLine()) != null) {
          int idx = line.indexOf(PREFIX_NAME);
          if (idx > -1) {
            list.add(line.substring(idx + PREFIX_NAME.length()).trim());
          }
        }
      } catch (IOException e) {
        AndroidCore.log(IStatus.ERROR, "Error parsing the AVD list", e);
        return null;
      } finally {
        try {
          read.close();
          reader.close();
        } catch (IOException e) {
          /*ignored*/
        }
      }
      return list;
    }
 public Document getTestDocument(String s) throws Exception {
   StringReader reader = new StringReader(s);
   InputSource inputSource = new InputSource(reader);
   Document doc = parser.parse(inputSource);
   reader.close();
   return doc;
 }
  // Advance to next row and set input stream
  private boolean advanceToNextRow() throws IOException {
    // ignore rows with null value in char column
    while (inputIterator.advanceToNextRow()) {
      if (inputIterator.isNullAt(columnIdx)) continue;

      if (stringReader != null) stringReader.close();
      stringReader = new StringReader(inputIterator.getStringAt(columnIdx));
      return true;
    }
    stringReader = null;
    return false;
  }
Example #7
0
 public static Properties stringToProperties(String str) {
   ParamChecker.notNull(str, "str");
   try {
     StringReader sr = new StringReader(str);
     Properties props = new Properties();
     props.load(sr);
     sr.close();
     return props;
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   }
 }
 private Ruleset unmarshallRuleset(String documentAsString) {
   // unmarshall doc
   StringReader stringReader = new StringReader(documentAsString);
   try {
     return (Ruleset) sbb.getUnmarshaller().unmarshal(stringReader);
   } catch (Exception e) {
     logger.error("unmarshalling of ruleset failed", e);
     return null;
   } finally {
     stringReader.close();
   }
 }
Example #9
0
 static Properties info(BulkReply reply) {
   Properties info = new Properties();
   // use the same charset as the library
   StringReader stringReader = new StringReader(new String(reply.data(), Charsets.UTF_8));
   try {
     info.load(stringReader);
   } catch (Exception ex) {
     throw new RedisSystemException("Cannot read Redis info", ex);
   } finally {
     stringReader.close();
   }
   return info;
 }
  private void dummy(String xmlstring) {
    try {
      xmlstring = xmlstring.trim();
      log.info("xmlstring:\r\n" + xmlstring);
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      StringReader reader = new StringReader(xmlstring);
      InputSource inputSource = new InputSource(reader);
      Document doc = db.parse(inputSource);

      //            CharArrayReader characterStream = new CharArrayReader(xmlstring.toCharArray());
      //            InputSource is = new InputSource(characterStream);
      //            Document doc = db.parse(is);

      // doc.getDocumentElement().normalize();
      log.info("Root element " + doc.getDocumentElement().getNodeName());
      NodeList nodeLst = doc.getElementsByTagName("PersoneFisiche");
      log.info("cycling...");
      for (int s = 0; s < nodeLst.getLength(); s++) {

        Node fstNode = nodeLst.item(s);

        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {

          Element fstElmnt = (Element) fstNode;

          NodeList idElmntLst = fstElmnt.getElementsByTagName("Id");
          Element idElmnt = (Element) idElmntLst.item(0);
          NodeList idList = idElmnt.getChildNodes();
          log.info("Id : " + ((Node) idList.item(0)).getNodeValue());

          NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("Nome");
          Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
          NodeList fstNm = fstNmElmnt.getChildNodes();
          log.info("First Name : " + ((Node) fstNm.item(0)).getNodeValue());

          NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("Cognome");
          Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
          NodeList lstNm = lstNmElmnt.getChildNodes();
          log.info("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
        }
      }
      reader.close();
    } catch (IOException e) {
      log.severe("Eccezione IO: " + e.getMessage());
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public Properties convert(String source) {
   if (source == null) {
     return null;
   }
   Properties info = new Properties();
   StringReader stringReader = new StringReader(source);
   try {
     info.load(stringReader);
   } catch (Exception ex) {
     throw new RedisSystemException("Cannot read Redis info", ex);
   } finally {
     stringReader.close();
   }
   return info;
 }
  public void transform(OntModel inputModel, OntModel outputModel, NIFParameters nifParameters) {
    this.prefix = nifParameters.getPrefix();

    String uri = this.prefix + "char=0,";
    // only supporting RFC5147 string atm
    contextResource =
        outputModel.createIndividual(
            uri, outputModel.createClass(NIFOntClasses.RFC5147String.getUri()));
    contextResource.addOntClass(NIFOntClasses.Context.getOntClass(outputModel));
    contextResource.addOntClass(NIFOntClasses.String.getOntClass(outputModel));
    contextResource.addProperty(
        NIFDatatypeProperties.beginIndex.getDatatypeProperty(outputModel), "0");

    if (!nifParameters.getOptions().has("informat")) {
      log.warn("informat parameter empty, please choose informat=file or informat=text");
    }

    if (!nifParameters.getOptions().has("tagset")) {
      log.warn(
          "No tagset chosen, please choose an OLiA tagset from: https://github.com/NLP2RDF/software/blob/master/java-maven/vocabularymodule/OLiA/src/main/java/org/nlp2rdf/vm/olia/models");
    } else {
      loadTagset(nifParameters.getOptions().valueOf("tagset").toString());
    }

    if (nifParameters.getOptions().valueOf("intype").equals("file")) {
      if (nifParameters.getOptions().valueOf("informat").equals("text")) {
        File input = new File(nifParameters.getOptions().valueOf("i").toString());
        FileReader reader = null;
        try {
          reader = new FileReader(input);
          this.transformConLL(reader, inputModel, outputModel, nifParameters);
          reader.close();
        } catch (FileNotFoundException fnf) {
          log.error("Could not open file " + nifParameters.getOptions().valueOf("i").toString());
        } catch (IOException e) {
          log.error("Could not read file " + nifParameters.getOptions().valueOf("i").toString());
        }
      }
    } else if (nifParameters.getOptions().valueOf("intype").equals("url")) {
      log.error("URL input not yet supported");
    } else {
      if (nifParameters.getOptions().valueOf("informat").equals("text")) {
        StringReader reader = new StringReader(nifParameters.getOptions().valueOf("i").toString());
        this.transformConLL(reader, inputModel, outputModel, nifParameters);
        reader.close();
      }
    }
  }
Example #13
0
 protected static NodeList xpathGetNodesMatching(final String xml, final String expression)
     throws XPathExpressionException {
   final XPath query = XPathFactory.newInstance().newXPath();
   StringReader sr = null;
   InputSource is = null;
   NodeList nodes = null;
   try {
     sr = new StringReader(xml);
     is = new InputSource(sr);
     nodes = (NodeList) query.evaluate(expression, is, XPathConstants.NODESET);
   } finally {
     sr.close();
     IOUtils.closeQuietly(sr);
   }
   return nodes;
 }
    public void testDispatcher() throws Exception {
      ProcessingContext processingContext;
      StringReader reader;
      StringWriter writer;
      String message;

      message = createMessage();
      reader = new StringReader(message);
      writer = new StringWriter();
      processingContext =
          new ProcessingContext(
              new WebRequestContextImpl(reader), new WebResponseContextImpl(writer));

      assertEquals(Dispatcher.OK, dispatcher.dispatch(processingContext));
      reader.close();
      writer.close();
      assertEquals(message, writer.toString());
    }
  /**
   * Same as parseFile but for a string
   *
   * @param stream
   * @return
   */
  public static Document parse(String stream) {
    System.out.println("Parsing XML ... " + stream);
    StringReader reader = new StringReader(stream);
    InputSource inputSource = new InputSource(reader);
    SAXBuilder saxBuilder = new SAXBuilder();
    Document doc = null;

    try {
      doc = saxBuilder.build(inputSource);
    } catch (IOException e) {
      System.out.println("Could not read source file: " + e.getMessage());
    } catch (JDOMException e) {
      System.err.println("cannot build doc");
      e.printStackTrace();
    }
    reader.close();
    return doc;
  }
 public String checkx(String text) {
   String finish = "";
   try {
     text = text.replace('\t', ' ');
     StringReader sr = new StringReader(text);
     BufferedReader br = new BufferedReader(sr);
     String temp = br.readLine();
     int i = 1;
     while (temp != null) {
       temp = temp.trim();
       if (temp.indexOf(':') != -1
           && (temp.indexOf(';') == -1 || temp.indexOf(':') < temp.indexOf(';'))) {
         flags.put(temp.substring(0, temp.indexOf(':')), i);
         temp = "";
       }
       for (String flag : flags.keySet()) {
         if (temp.contains(flag)) {
           //						System.err.println(temp);
           temp += " ";
           if (temp.contains("," + flag + ";")
               || temp.contains("," + flag + " ")
               || temp.contains("," + flag + ",")
               || temp.contains(" " + flag + ";")
               || temp.contains(" " + flag + " ")) {
             //							System.err.println("+++++" + temp);
             temp = temp.replace(flag, String.valueOf(flags.get(flag) - i - 1)).trim();
             break;
           }
         }
       }
       if (temp.length() != 0 && !temp.startsWith(";")) i++;
       finish += temp;
       finish += NEWLINE;
       temp = br.readLine();
     }
     br.close();
     sr.close();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return finish;
 }
  private static <T> T unmarshal(Class<?> elementClass, String body, Class<T> resultClass) {
    verifyStartsAsXML(body);
    body = removeBadTags(elementClass, body);

    String configFile = fromRedmineMap.get(elementClass);
    Unmarshaller unmarshaller = getUnmarshaller(configFile, resultClass);

    StringReader reader = null;
    try {
      reader = new StringReader(body);
      return resultClass.cast(unmarshaller.unmarshal(reader));
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      if (reader != null) {
        reader.close();
      }
    }
  }
    public List<AndroidSDK> getSDKList() {
      if (buffer == null || buffer.length() < 1) return null;

      StringReader reader = new StringReader(buffer.toString());
      BufferedReader read = new BufferedReader(reader);
      ArrayList<AndroidSDK> sdkList = new ArrayList<AndroidSDK>();

      String line = null;
      try {
        AndroidSDK sdk = null;
        while ((line = read.readLine()) != null) {
          final int scolIdx = line.indexOf(':');
          if (scolIdx < 0) {
            continue;
          }
          String[] pair = new String[2];
          pair[0] = line.substring(0, scolIdx).trim();
          pair[1] = line.substring(scolIdx + 1).trim();
          if ("id".equalsIgnoreCase(pair[0])) {
            sdk = new AndroidSDK();
            sdkList.add(sdk);
            int vIndex = pair[1].indexOf("or");
            sdk.setId(pair[1].substring(vIndex + "or".length()).replace("\"", ""));
          } else if ("Type".equalsIgnoreCase(pair[0])) {
            Assert.isNotNull(sdk);
            sdk.setType(pair[1].trim());
          } else if ("API level".equalsIgnoreCase(pair[0])) {
            Assert.isNotNull(sdk);
            sdk.setApiLevel(Integer.parseInt(pair[1]));
          }
        }
      } catch (IOException e) {
        AndroidCore.log(IStatus.ERROR, "Error parsing the SDK list", e);
      } finally {
        try {
          read.close();
          reader.close();
        } catch (IOException e) {
          // ignored
        }
      }
      return sdkList;
    }
Example #19
0
  /**
   * Decodes a Quoted-Printable string of any size into it's original text.
   *
   * @param encoded The encoded string to decode.
   * @return The decoded string.
   * @throws ArgumentNullException A string is passed in as a null reference.
   *     <p>Decodes a quoted-printable encoded string into a string of unencoded text of any size.
   */
  public static String decode(String encoded) throws Exception {
    if (encoded == null) throw new ArgumentNullException();

    String line;
    StringWriter sw = new StringWriter();
    StringReader sr = new StringReader(encoded);
    try {
      while ((line = sr.readLine()) != null) {
        if (line.endsWith("=")) sw.print(hexDecoder(line.substring(0, (0) + (line.length() - 1))));
        else sw.println(hexDecoder(line));
        sw.Flush();
      }
      return sw.toString();
    } finally {
      sw.close();
      sr.close();
      sw = null;
      sr = null;
    }
  }
Example #20
0
 public static Document string2Document(String src) {
   if (src == null || src.trim().length() == 0) return null;
   if (src.charAt(0) != '<') {
     int i = src.indexOf('<');
     if (i == -1) return null;
     src = src.substring(i, src.length());
   }
   StringReader sreader = null;
   try {
     DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
     sreader = new StringReader(src);
     InputSource is = new InputSource(sreader);
     return builder.parse(is);
   } catch (Exception e) {
     CONST.log.error("Parse xml error: ", e);
     return null;
   } finally {
     if (sreader != null) sreader.close();
   }
 }
Example #21
0
 public void Write(String fileName, String content) {
   System.out.println("保存密文,写入文件");
   StringBuffer str = new StringBuffer();
   try {
     StringReader inOne = new StringReader(content);
     BufferedReader inTwo = new BufferedReader(inOne);
     java.io.FileWriter outOne = new java.io.FileWriter(fileName);
     BufferedWriter outTwo = new BufferedWriter(outOne);
     String s = null;
     while ((s = inTwo.readLine()) != null) {
       outTwo.write(s);
       outTwo.newLine();
       outTwo.flush();
     }
     inOne.close();
     inTwo.close();
     outOne.close();
     outTwo.close();
   } catch (IOException exp) {
   }
 }
Example #22
0
  @Test
  public void testRead() throws Exception {
    String pcapFile =
        new StringBuilder()
            .append(resourceDirPath)
            .append("/")
            .append(getClass().getSimpleName())
            .append(".pcap")
            .toString();
    PcapHandle ph = Pcaps.openOffline(pcapFile);
    StringBuilder sb = new StringBuilder(1000);
    sb.append(ph.getNextPacket().toString())
        .append(System.getProperty("line.separator"))
        .append(ph.getNextPacket().toString());
    ph.close();

    FileReader fr =
        new FileReader(
            new StringBuilder()
                .append(resourceDirPath)
                .append("/")
                .append(getClass().getSimpleName())
                .append(".log")
                .toString());
    BufferedReader fbr = new BufferedReader(fr);
    StringReader sr = new StringReader(sb.toString());
    BufferedReader sbr = new BufferedReader(sr);

    String line;
    while ((line = fbr.readLine()) != null) {
      assertEquals(line, sbr.readLine());
    }

    assertNull(sbr.readLine());

    fbr.close();
    fr.close();
    sr.close();
    sbr.close();
  }
  public JSONTrace(String nomFichier, String padid) throws FileNotFoundException, IOException {
    VectorClockCSMapper vectorClockMapper = new VectorClockCSMapper();
    Gson gson = new Gson();
    this.ops = new ArrayList<TraceOperation>();

    FileReader f = new FileReader(nomFichier);
    BufferedReader buf = new BufferedReader(f);
    String res = buf.readLine();

    // FileWriter fw = new FileWriter("/home/damien/test1.txt");

    while (res != null) {
      StringReader s = new StringReader(res);
      ElementJSON e = gson.fromJson(s, ElementJSON.class);

      if (e.getKey().contains("key:padid:" + padid)) {
        String op = e.getVal().getOperation();
        int offset = e.getVal().getNumber_charDeleted();
        String str = e.getVal().getChars_inserted();
        int pos = e.getVal().getPosition();
        String uid = e.getVal().getUserId();
        VectorClockCS vc = e.getVal().getVector_clock();
        int repli = vectorClockMapper.userId(uid);
        VectorClock v = vectorClockMapper.toVectorClock(vc);

        ElementCS ecs = new ElementCS(op, offset, str, pos, repli, v);
        ElementJSON ejs = new ElementJSON(e.getKey(), ecs);
        // String sir = gson.toJson(ejs);
        // fw.write(sir+"\n");

        TraceOperation so = TraceGenerator.oneJSON2OP(e, vectorClockMapper);
        ops.add(so);
      }
      s.close();
      res = buf.readLine();
    }
    buf.close();
    // fw.close();
    f.close();
  }
 @SuppressWarnings("unchecked")
 private <T> T fromXML(final String object, final XStream xstream) {
   final StringReader xmlReader = new StringReader(object);
   ObjectInputStream in = null;
   try {
     in = xstream.createObjectInputStream(xmlReader);
     try {
       return (T) in.readObject();
     } catch (final IOException e) {
       throw new BonitaRuntimeException("unable to deserialize object " + object, e);
     } catch (final ClassNotFoundException e) {
       throw new BonitaRuntimeException("unable to deserialize object " + object, e);
     } catch (final CannotResolveClassException e) {
       throw new BonitaRuntimeException("unable to deserialize object " + object, e);
     } finally {
       in.close();
       xmlReader.close();
     }
   } catch (final IOException e) {
     throw new BonitaRuntimeException("unable to deserialize object " + object, e);
   }
 }
    public List<AndroidDevice> getDeviceList() {
      if (buffer == null || buffer.length() < 1) return null;

      StringReader reader = new StringReader(buffer.toString());
      BufferedReader read = new BufferedReader(reader);
      String line = null;
      ArrayList<AndroidDevice> list = new ArrayList<AndroidDevice>();
      try {
        while ((line = read.readLine()) != null) {
          if (line.isEmpty() || line.contains("List of devices attached")) continue;
          String[] values = line.split("\t");
          if (values.length == 2) {
            AndroidDevice device = new AndroidDevice();
            device.setSerialNumber(values[0].trim());
            device.setEmulator(values[0].contains("emulator"));

            if ("device".equals(values[1].trim())) {
              device.setState(AndroidDevice.STATE_DEVICE);
            } else if ("offline".equals(values[1].trim())) {
              device.setState(AndroidDevice.STATE_OFFLINE);
            }
            list.add(device);
          }
        }
      } catch (IOException e) {
        AndroidCore.log(IStatus.ERROR, "Error parsing the Android device list", e);
        return null;
      } finally {
        try {
          read.close();
          reader.close();
        } catch (IOException e) {
          /*ignored*/
        }
      }
      return list;
    }
 /**
  * Returns an error string or null if it is OK
  *
  * @return
  */
 public String getErrorString() {
   String text = buffer.toString();
   if (text.startsWith("Error:")) {
     StringReader reader = new StringReader(text);
     BufferedReader read = new BufferedReader(reader);
     try {
       String line = read.readLine();
       if (line == null) {
         return "";
       }
       return line.substring(7);
     } catch (IOException e) {
       AndroidCore.log(IStatus.ERROR, "Error parsing the create project command result", e);
     } finally {
       try {
         read.close();
         reader.close();
       } catch (IOException e) {
         // ignored
       }
     }
   }
   return null;
 }
  /*
   * Reads and decode an XML classpath string
   */
  public static EList<MindPathEntry> decodeMindpath(String xmlMindpath) throws IOException {
    BasicEList<MindPathEntry> paths = new BasicEList<MindPathEntry>();
    StringReader reader = new StringReader(xmlMindpath);
    Element cpElement;
    try {
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      cpElement = parser.parse(new InputSource(reader)).getDocumentElement();
    } catch (SAXException e) {
      e.printStackTrace();
      throw new IOException("Bad format");
    } catch (ParserConfigurationException e) {
      throw new IOException("Bad format");
    } finally {
      reader.close();
    }

    if (!cpElement
        .getNodeName()
        .equalsIgnoreCase(MindPathEntryCustomImpl.TAG_MINDPATH)) { // $NON-NLS-1$
      throw new IOException("Bad format");
    }
    NodeList list =
        cpElement.getElementsByTagName(MindPathEntryCustomImpl.TAG_MINDPATHENTRY); // $NON-NLS-1$
    int length = list.getLength();

    for (int i = 0; i < length; ++i) {
      Node node = list.item(i);
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        MindPathEntry entry = MindPathEntryCustomImpl.elementDecode((Element) node);
        if (entry != null) {
          paths.add(entry);
        }
      }
    }
    return paths;
  }
Example #28
0
 @Override
 public void close() {
   isCloseInvoked.set(true);
   super.close();
 }
Example #29
0
  public void process() {
    boolean exceptionWhenWritingLexerFile = false;
    String lexerGrammarFileName = null; // necessary at this scope to have access in the catch below

    // Have to be tricky here when Maven or build tools call in and must new Tool()
    // before setting options. The banner won't display that way!
    if (isVerbose() && showBanner) {
      ErrorManager.info("ANTLR Parser Generator  Version " + VERSION);
      showBanner = false;
    }

    try {
      sortGrammarFiles(); // update grammarFileNames
    } catch (Exception e) {
      ErrorManager.error(ErrorManager.MSG_INTERNAL_ERROR, e);
    } catch (Error e) {
      ErrorManager.error(ErrorManager.MSG_INTERNAL_ERROR, e);
    }

    for (String grammarFileName : grammarFileNames) {
      // If we are in make mode (to support build tools like Maven) and the
      // file is already up to date, then we do not build it (and in verbose mode
      // we will say so).
      if (make) {
        try {
          if (!buildRequired(grammarFileName)) continue;
        } catch (Exception e) {
          ErrorManager.error(ErrorManager.MSG_INTERNAL_ERROR, e);
        }
      }

      if (isVerbose() && !isDepend()) {
        System.out.println(grammarFileName);
      }
      try {
        if (isDepend()) {
          BuildDependencyGenerator dep = new BuildDependencyGenerator(this, grammarFileName);
          /*
          List outputFiles = dep.getGeneratedFileList();
          List dependents = dep.getDependenciesFileList();
          System.out.println("output: "+outputFiles);
          System.out.println("dependents: "+dependents);
           */
          System.out.println(dep.getDependencies());
          continue;
        }

        Grammar grammar = getRootGrammar(grammarFileName);
        // we now have all grammars read in as ASTs
        // (i.e., root and all delegates)
        grammar.composite.assignTokenTypes();
        grammar.composite.defineGrammarSymbols();
        grammar.composite.createNFAs();

        generateRecognizer(grammar);

        if (isPrintGrammar()) {
          grammar.printGrammar(System.out);
        }

        if (isReport()) {
          GrammarReport greport = new GrammarReport(grammar);
          System.out.println(greport.toString());
          // print out a backtracking report too (that is not encoded into log)
          System.out.println(greport.getBacktrackingReport());
          // same for aborted NFA->DFA conversions
          System.out.println(greport.getAnalysisTimeoutReport());
        }
        if (isProfile()) {
          GrammarReport greport = new GrammarReport(grammar);
          Stats.writeReport(GrammarReport.GRAMMAR_STATS_FILENAME, greport.toNotifyString());
        }

        // now handle the lexer if one was created for a merged spec
        String lexerGrammarStr = grammar.getLexerGrammar();
        // System.out.println("lexer grammar:\n"+lexerGrammarStr);
        if (grammar.type == Grammar.COMBINED && lexerGrammarStr != null) {
          lexerGrammarFileName = grammar.getImplicitlyGeneratedLexerFileName();
          try {
            Writer w = getOutputFile(grammar, lexerGrammarFileName);
            w.write(lexerGrammarStr);
            w.close();
          } catch (IOException e) {
            // emit different error message when creating the implicit lexer fails
            // due to write permission error
            exceptionWhenWritingLexerFile = true;
            throw e;
          }
          try {
            StringReader sr = new StringReader(lexerGrammarStr);
            Grammar lexerGrammar = new Grammar();
            lexerGrammar.composite.watchNFAConversion = internalOption_watchNFAConversion;
            lexerGrammar.implicitLexer = true;
            lexerGrammar.setTool(this);
            File lexerGrammarFullFile =
                new File(getFileDirectory(lexerGrammarFileName), lexerGrammarFileName);
            lexerGrammar.setFileName(lexerGrammarFullFile.toString());

            lexerGrammar.importTokenVocabulary(grammar);
            lexerGrammar.parseAndBuildAST(sr);

            sr.close();

            lexerGrammar.composite.assignTokenTypes();
            lexerGrammar.composite.defineGrammarSymbols();
            lexerGrammar.composite.createNFAs();

            generateRecognizer(lexerGrammar);
          } finally {
            // make sure we clean up
            if (deleteTempLexer) {
              File outputDir = getOutputDirectory(lexerGrammarFileName);
              File outputFile = new File(outputDir, lexerGrammarFileName);
              outputFile.delete();
            }
          }
        }
      } catch (IOException e) {
        if (exceptionWhenWritingLexerFile) {
          ErrorManager.error(ErrorManager.MSG_CANNOT_WRITE_FILE, lexerGrammarFileName, e);
        } else {
          ErrorManager.error(ErrorManager.MSG_CANNOT_OPEN_FILE, grammarFileName);
        }
      } catch (Exception e) {
        ErrorManager.error(ErrorManager.MSG_INTERNAL_ERROR, grammarFileName, e);
      }
      /*
      finally {
      System.out.println("creates="+ Interval.creates);
      System.out.println("hits="+ Interval.hits);
      System.out.println("misses="+ Interval.misses);
      System.out.println("outOfRange="+ Interval.outOfRange);
      }
       */
    }
  }
Example #30
0
 @Override
 public void close() throws IOException {
   sourceReader.close();
 }