@Test
  public void testImportExcel2007() throws Exception {

    long beginTime = System.currentTimeMillis();

    String fileName = "D:\\Backup\\test.xlsx";

    List<ExcelData> dataList = Lists.newArrayList();

    OPCPackage pkg = OPCPackage.open(fileName);
    XSSFReader r = new XSSFReader(pkg);

    XMLReader parser = XMLReaderFactory.createXMLReader();
    ContentHandler handler = new Excel2007SheetHandler(dataList);
    parser.setContentHandler(handler);

    Iterator<InputStream> sheets = r.getSheetsData();
    while (sheets.hasNext()) {
      InputStream sheet = sheets.next();
      InputSource sheetSource = new InputSource(sheet);
      parser.parse(sheetSource);
      sheet.close();
    }

    // 把最后剩下的不足batchSize大小
    if (dataList.size() > 0) {
      doBatchSave(dataList);
    }

    long endTime = System.currentTimeMillis();
    log.info("耗时(秒):" + (endTime - beginTime) / 1000);
  }
  /** ** Main entery point for debugging/testing */
  public static void main(String argv[]) {
    RTConfig.setCommandLineArgs(argv);
    Print.setAllOutputToStdout(true);
    Print.setEncoding(ENCODING_UTF8);
    String accountID = RTConfig.getString(ARG_ACCOUNT, "demo");
    GoogleGeocodeV2 gn = new GoogleGeocodeV2("google", null, null);

    /* reverse geocode */
    if (RTConfig.hasProperty(ARG_REVGEOCODE)) {
      GeoPoint gp = new GeoPoint(RTConfig.getString(ARG_REVGEOCODE, null));
      if (!gp.isValid()) {
        Print.logInfo("Invalid GeoPoint specified");
        System.exit(1);
      }
      Print.logInfo("Reverse-Geocoding GeoPoint: " + gp);
      Print.sysPrintln(
          "RevGeocode = " + gn.getReverseGeocode(gp, null /*localeStr*/, false /*cache*/));
      // Note: Even though the values are printed in UTF-8 character encoding, the
      // characters may not appear to be property displayed if the console display
      // does not support UTF-8.
      System.exit(0);
    }

    /* no options */
    Print.sysPrintln("No options specified");
    System.exit(1);
  }
  @Override
  public VPackage parse() {

    logger.debug("Starting parsing package: " + xmlFile.getAbsolutePath());

    long startParsing = System.currentTimeMillis();

    try {
      Document document = getDocument();
      Element root = document.getDocumentElement();

      _package = new VPackage(xmlFile);

      Node name = root.getElementsByTagName(EL_NAME).item(0);
      _package.setName(name.getTextContent());
      Node descr = root.getElementsByTagName(EL_DESCRIPTION).item(0);
      _package.setDescription(descr.getTextContent());

      NodeList list = root.getElementsByTagName(EL_CLASS);

      boolean initPainters = false;
      for (int i = 0; i < list.getLength(); i++) {
        PackageClass pc = parseClass((Element) list.item(i));
        if (pc.getPainterName() != null) {
          initPainters = true;
        }
      }

      if (initPainters) {
        _package.initPainters();
      }

      logger.info(
          "Parsing the package '{}' finished in {}ms.\n",
          _package.getName(),
          (System.currentTimeMillis() - startParsing));
    } catch (Exception e) {
      collector.collectDiagnostic(e.getMessage(), true);
      if (RuntimeProperties.isLogDebugEnabled()) {
        e.printStackTrace();
      }
    }

    try {
      checkProblems("Error parsing package file " + xmlFile.getName());
    } catch (Exception e) {
      return null;
    }

    return _package;
  }
  /** csv格式 */
  @Test
  public void testImportCsv() throws IOException {

    long beginTime = System.currentTimeMillis();

    File file = new File("D:\\Backup\\test.csv");
    InputStream is = new BufferedInputStream(new FileInputStream(file));
    String encoding = FileCharset.getCharset(file);

    LineIterator iterator = IOUtils.lineIterator(is, encoding);

    String separator = ",";
    int batchSize = 100; // 批处理大小
    int totalSize = 0; // 总大小

    final List<ExcelData> dataList = Lists.newArrayList();

    if (iterator.hasNext()) {
      iterator.nextLine(); // 跳过第一行标题
    }

    while (iterator.hasNext()) {

      totalSize++;

      String line = iterator.nextLine();
      String[] dataArray = StringUtils.split(line, separator);

      ExcelData data = new ExcelData();
      data.setId(Long.valueOf(dataArray[0]));
      data.setContent(dataArray[1]);
      dataList.add(data);

      if (totalSize % batchSize == 0) {
        try {
          doBatchSave(dataList);
        } catch (Exception e) {
          Long fromId = dataList.get(0).getId();
          Long endId = dataList.get(dataList.size() - 1).getId();
          log.error("from " + fromId + " to " + endId + ", error", e);
        }
        dataList.clear();
      }
    }
    IOUtils.closeQuietly(is);

    long endTime = System.currentTimeMillis();
    log.info("耗时(秒):" + (endTime - beginTime) / 1000);
  }
Exemple #5
0
  private static SAXParserFactory createFastSAXParserFactory()
      throws ParserConfigurationException, SAXException {
    if (fastParserFactoryClass == null) {
      try {
        fastParserFactoryClass =
            Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl"); // NOI18N
      } catch (Exception ex) {
        useFastSAXParserFactory = false;
        if (System.getProperty("java.version").startsWith("1.4")) { // NOI18N
          ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
        }
      }
    }
    if (fastParserFactoryClass != null) {
      try {
        SAXParserFactory factory = (SAXParserFactory) fastParserFactoryClass.newInstance();

        return factory;
      } catch (Exception ex) {
        useFastSAXParserFactory = false;
        throw new ParserConfigurationException(ex.getMessage());
      }
    }

    return SAXParserFactory.newInstance();
  }
 private Document getXMLDocument(InputStream is) {
   SAXBuilder builder = new SAXBuilder();
   builder.setValidation(false);
   builder.setIgnoringElementContentWhitespace(true);
   Document doc = null;
   try {
     doc = builder.build(is);
   } catch (JDOMException e) {
     e.printStackTrace();
     System.exit(-1);
   } catch (IOException e) {
     e.printStackTrace();
     System.exit(-1);
   }
   return doc;
 }
 public static void main(String[] args) {
   if (args.length < 1) {
     System.out.println("Usage: java Parser [input]");
     System.exit(0);
   }
   Parser p = new Parser(args[0]);
 }
  // Start a new line
  // and indent the next line appropriately
  private void nl() throws SAXException {
    String lineEnd = System.getProperty("line.separator");

    try {
      out.write(lineEnd);

      for (int i = 0; i < indentLevel; i++) out.write(indentString);
    } catch (IOException e) {
      throw new SAXException("I/O error", e);
    }
  }
Exemple #9
0
 private static short[] load(String name, Reader input, Model.Translator translator)
     throws java.io.IOException {
   short[] sequence = null;
   char[] buffer = new char[10240];
   int len;
   while ((len = input.read(buffer)) > 0) {
     for (int i = len - 1; i >= 0; i--) {
       if (Character.isWhitespace(buffer[i])) {
         if (i == (len - 1)) {
           len--;
         } else {
           System.arraycopy(buffer, i + 1, buffer, i, len - i - 1);
         }
       }
     }
     int start;
     if (sequence == null) {
       sequence = new short[len];
       start = 0;
     } else {
       start = sequence.length;
       short[] newseq = new short[sequence.length + len];
       System.arraycopy(sequence, 0, newseq, 0, sequence.length);
       sequence = newseq;
     }
     for (int i = 0; i < len; i++) {
       sequence[start + i] = translator.translate(buffer[i]);
       if (sequence[start + i] < 0) {
         throw new IOException(
             "Sequence character '"
                 + buffer[i]
                 + "' ("
                 + ((int) buffer[i])
                 + ") at offset "
                 + (start + i)
                 + " is not in the model's lexicon.");
       }
     }
   }
   return sequence;
 }
  /**
   * Main program.
   *
   * <p>\u0040param args Program parameters.
   */
  public static void main(String[] args) {
    //  Initialize.
    try {
      if (!initialize(args)) {
        System.exit(1);
      }
      //  Process all files.

      long startTime = System.currentTimeMillis();

      int filesProcessed = processFiles(args);

      long processingTime = (System.currentTimeMillis() - startTime + 999) / 1000;

      //  Terminate.

      terminate(filesProcessed, processingTime);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
  /** 导入 excel 2003 biff格式 如果是xml格式的 可以使用SAX(未测试) */
  @Test
  public void testImportExcel2003() throws Exception {

    long beginTime = System.currentTimeMillis();

    String fileName = "D:\\Backup\\Book1.xls";

    List<ExcelData> dataList = Lists.newArrayList();

    // 输入流
    InputStream fis = new BufferedInputStream(new FileInputStream(fileName));
    // 创建 org.apache.poi.poifs.filesystem.Filesystem
    POIFSFileSystem poifs = new POIFSFileSystem(fis);
    // 从输入流 得到 Workbook(excel 部分)流
    InputStream din = poifs.createDocumentInputStream("Workbook");
    // 构造 HSSFRequest
    HSSFRequest req = new HSSFRequest();

    // 添加监听器
    req.addListenerForAllRecords(new Excel2003Listener(dataList));
    //  创建事件工厂
    HSSFEventFactory factory = new HSSFEventFactory();
    // 根据文档输入流处理事件
    factory.processEvents(req, din);
    // 关闭输入流
    fis.close();
    // 关闭文档流
    din.close();

    System.out.println(dataList.size());
    // 把最后剩下的不足batchSize大小
    if (dataList.size() > 0) {
      doBatchSave(dataList);
    }

    long endTime = System.currentTimeMillis();
    log.info("耗时(秒):" + (endTime - beginTime) / 1000);
  }
  public void saveGlyphFile(OutputStream a_output) {
    try {
      Transformer transformer = getTransformer();
      Document document = m_glyph.makeDocument();
      DOMSource source = new DOMSource(document);
      StreamResult result = new StreamResult(a_output);
      transformer.transform(source, result);
    } catch (ParserConfigurationException | TransformerException e) {
      e.printStackTrace();
    }

    m_savedTime = System.currentTimeMillis();
    m_modifiedTime = m_savedTime;
  }
  /**
   * Checks {@link GridSystemProperties#GG_JETTY_PORT} system property and overrides default
   * connector port if it present. Then initializes {@code port} with the found value.
   *
   * @param con Jetty connector.
   */
  private void override(AbstractNetworkConnector con) {
    String host = System.getProperty(GG_JETTY_HOST);

    if (!F.isEmpty(host)) con.setHost(host);

    int currPort = con.getPort();

    Integer overridePort = Integer.getInteger(GG_JETTY_PORT);

    if (overridePort != null && overridePort != 0) currPort = overridePort;

    con.setPort(currPort);
    port = currPort;
  }
  /**
   * Main entry point. Expects two arguments: the schema document, and the source document.
   *
   * @param args
   */
  public static void main(String[] args) {
    try {
      if (args.length != 2) {
        printUsage();
        return;
      }

      SchemaFactory schemaFactory;

      // Set a system property to force selection of the Saxon SchemaFactory implementation

      System.setProperty(
          "javax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema",
          "com.saxonica.schema.SchemaFactoryImpl");

      schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");

      schemaFactory.setErrorHandler(new LocalErrorHandler());
      // create a grammar object.
      Schema schemaGrammar = schemaFactory.newSchema(new File(args[0]));

      System.err.println("Created Grammar object for schema : " + args[0]);

      Resolver resolver = new Resolver();

      // create a validator to validate against the schema.
      ValidatorHandler schemaValidator = schemaGrammar.newValidatorHandler();
      schemaValidator.setResourceResolver(resolver);
      schemaValidator.setErrorHandler(new LocalErrorHandler());
      schemaValidator.setContentHandler(
          new LocalContentHandler(schemaValidator.getTypeInfoProvider()));

      System.err.println("Validating " + args[1] + " against grammar " + args[0]);
      SAXParserFactory parserFactory = SAXParserFactory.newInstance();
      parserFactory.setNamespaceAware(true);
      SAXParser parser = parserFactory.newSAXParser();
      XMLReader reader = parser.getXMLReader();
      reader.setContentHandler(schemaValidator);
      reader.parse(new InputSource(new File(args[1]).toURI().toString()));

      System.err.println("Validation successful");
    } catch (SAXException saxe) {
      exit(1, "Error: " + saxe.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      exit(2, "Fatal Error: " + e);
    }
  }
  static Parser getParser() throws SAXException, ParserConfigurationException {
    //
    // turn it into an in-memory object.
    //

    Parser parser;
    SAXParserFactory spf = SAXParserFactory.newInstance();
    String validation =
        System.getProperty("javax.xml.parsers.validation", "false"); // NOT LOCALIZABLE
    if (validation.equalsIgnoreCase("true")) // NOT LOCALIZABLE
    spf.setValidating(true);

    SAXParser sp = spf.newSAXParser();
    parser = sp.getParser();
    return parser;
  }
Exemple #16
0
  /**
   * EPML2PNML
   *
   * @param args String[]
   */
  private static void EPML2PNML(String[] args) {
    if (args.length != 2) {
      System.out.println("���ṩEPML�ļ�·����PNML���Ŀ¼!");
      System.exit(-1);
    }
    epmlImport epml = new epmlImport();
    // load the single epml file
    String filename = args[0];
    try {
      EPCResult epcRes = (EPCResult) epml.importFile(new FileInputStream(filename));
      // convert all epc models to pnml files
      ArrayList<ConfigurableEPC> alEPCs = epcRes.getAllEPCs();
      PnmlExport export = new PnmlExport();
      for (ConfigurableEPC epc : alEPCs) {
        String id = epc.getIdentifier();
        if (id.equals("1An_klol")
            || id.equals("1An_l1y8")
            || id.equals("1Ex_dzq9")
            || id.equals("1Ex_e6dx")
            || id.equals("1Ku_9soy")
            || id.equals("1Ku_a4cg")
            || id.equals("1Or_lojl")
            || id.equals("1Pr_d1ur")
            || id.equals("1Pr_djki")
            || id.equals("1Pr_dkfa")
            || id.equals("1Pr_dl73")
            || id.equals("1Ve_musj")
            || id.equals("1Ve_mvwz")) continue;
        // save pnml files to the same folder
        File outFile = new File(args[1] + "/" + id + ".pnml");
        if (outFile.exists()) continue;
        FileOutputStream fos = new FileOutputStream(outFile);
        PetriNet petri = AMLtoPNML.convert(epc);
        try {
          export.export(new ProvidedObject("PetriNet", new Object[] {petri}), fos);
        } catch (Exception ex1) {
          ex1.printStackTrace(System.out);
        }
      }
    } catch (IOException ex) {
      ex.printStackTrace(System.out);
    }

    System.out.println("EPML Conversion Done");
  }
Exemple #17
0
  public static Parser getDefaultParser() {
    Parser parser = null;
    String parserClass = System.getProperty("org.xml.sax.parser");
    try {
      if ((parserClass == null) || (parserClass.length() == 0)) parserClass = DEFAULT_PARSER_CLASS;

      parser = ParserFactory.makeParser(parserClass);
    } catch (java.lang.IllegalAccessException iae) {
    } catch (java.lang.ClassNotFoundException cnfe) {
    } catch (java.lang.InstantiationException ie) {
    }
    ;
    if (parser == null) {
      System.out.print("unable to create SAX parser: ");
      System.out.println(parserClass);
      return null;
    }

    return parser;
  } // -- getDefaultParser
Exemple #18
0
  private static void AML2PNML(String[] args) {
    if (args.length != 3) {
      System.out.println("���ṩAML����Ŀ¼��PNML���Ŀ¼�Լ��ֵ��ļ�!");
      System.exit(-1);
    }
    System.out.println("����Ŀ¼��" + args[0]);
    System.out.println("���Ŀ¼��" + args[1]);
    System.out.println("�ֵ��ļ���" + args[2]);
    // load the dict
    AMLtoPNML.loadDict(args[2]);
    File srcDir = new File(args[0]);
    File[] lstAML = srcDir.listFiles();
    PnmlExport export = new PnmlExport();
    for (int i = 0; i < lstAML.length; i++) {
      if (lstAML[i].isDirectory()) {
        continue;
      }
      System.out.print(lstAML[i].getName() + "==>");
      try {
        FileInputStream fis = new FileInputStream(lstAML[i]);
        int idx = lstAML[i].getName().indexOf(".xml");
        File outFile = new File(args[1] + "/" + lstAML[i].getName().substring(0, idx) + ".pnml");
        FileOutputStream fos = new FileOutputStream(outFile);
        EPCResult epcRes = (EPCResult) AMLtoPNML.importFile(fis);
        ConfigurableEPC epc = epcRes.getMainEPC();
        PetriNet petri = AMLtoPNML.convert(epc);
        export.export(new ProvidedObject("PetriNet", new Object[] {petri}), fos);
        System.out.println(outFile.getName());
      } catch (FileNotFoundException ex) {
        ex.printStackTrace(System.out);
      } catch (IOException ioe) {
        ioe.printStackTrace(System.out);
      } catch (Exception e) {
        e.printStackTrace(System.out);
      }
    }

    System.out.println("Conversion Done");
  }
Exemple #19
0
  /** ** Main entery point for debugging/testing */
  public static void main(String argv[]) {
    RTConfig.setCommandLineArgs(argv);
    Print.setAllOutputToStdout(true);
    Print.setEncoding(ENCODING_UTF8);

    /* host */
    String host = RTConfig.getString("host", null);
    if (!StringTools.isBlank(host)) {
      HOST_PRIMARY = host;
    }

    /* GeoPoint */
    GeoPoint gp = new GeoPoint(RTConfig.getString("gp", null));
    if (!gp.isValid()) {
      Print.logInfo("Invalid GeoPoint specified");
      System.exit(1);
    }
    Print.logInfo("Reverse-Geocoding GeoPoint: " + gp);

    /* Reverse Geocoding */
    Nominatim gn = new Nominatim("nominatim", null, RTConfig.getCommandLineProperties());
    Print.sysPrintln("RevGeocode = " + gn.getReverseGeocode(gp, null /*localeStr*/));
  }
  public static void main(String[] args) throws IOException {
    String filename = "z.xml"; // NOT LOCALIZABLE, main

    try {
      String uri = "file:" + new File(filename).getAbsolutePath(); // NOT LOCALIZABLE, main

      //
      // turn it into an in-memory object.
      //
      Parser parser = getParser();
      parser.setDocumentHandler(new XmlParser());
      parser.setErrorHandler(new MyErrorHandler());
      parser.parse(uri);

    } catch (SAXParseException err) {
      Debug.trace(
          "** Parsing error" // NOT LOCALIZABLE, main
              + ", line "
              + err.getLineNumber() // NOT LOCALIZABLE
              + ", uri "
              + err.getSystemId()); // NOT LOCALIZABLE
      Debug.trace("   " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e;
      if (e.getException() != null) x = e.getException();
      x.printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }

    byte[] buf = new byte[256];
    Debug.trace("Press ENTER to exit."); // NOT LOCALIZABLE
    System.in.read(buf, 0, 256);
    System.exit(0);
  }
 public Memento createMemento(String a_description) {
   m_modifiedTime = System.currentTimeMillis();
   byte[] bytes = m_glyph.makeTextDocument().getBytes();
   return new Memento(a_description, bytes);
 }
Exemple #22
0
/** Create and configure DocumentBuilderFactory instances. */
public class DbfFactory {

  private static final Logger LOGGER = FacesLogger.CONFIG.getLogger();

  private static final String AS_INSTALL_ROOT = "com.sun.aas.installRoot";

  private static final String AS_SCHEMA_DIR =
      System.getProperty(AS_INSTALL_ROOT)
          + File.separatorChar
          + "lib"
          + File.separatorChar
          + "schemas"
          + File.separatorChar;

  private static final String AS_DTD_DIR =
      System.getProperty(AS_INSTALL_ROOT)
          + File.separatorChar
          + "lib"
          + File.separatorChar
          + "dtds"
          + File.separatorChar;

  /** Location of the facelet-taglib 2.0 Schema */
  private static final String FACELET_TAGLIB_2_0_XSD =
      "/com/sun/faces/web-facelettaglibrary_2_0.xsd";

  /** Location of the Faces 2.0 Schema */
  private static final String FACES_2_0_XSD = "/com/sun/faces/web-facesconfig_2_0.xsd";

  /** Location of the Faces 2.0 Schema */
  private static final String FACES_2_1_XSD = "/com/sun/faces/web-facesconfig_2_1.xsd";

  /** Location of the Faces 1.2 Schema */
  private static final String FACES_1_2_XSD = "/com/sun/faces/web-facesconfig_1_2.xsd";

  /** Location of the Faces private 1.1 Schema */
  private static final String FACES_1_1_XSD = "/com/sun/faces/web-facesconfig_1_1.xsd";

  /** Location of the facelet taglib xsd within GlassFish. */
  private static final String FACELET_TAGLIB_2_0_XSD_FILE =
      AS_SCHEMA_DIR + "web-facelettaglibrary_2_0.xsd";

  /** Location of the facelet taglib xsd within GlassFish. */
  private static final String FACELET_TAGLIB_2_2_XSD_FILE =
      AS_SCHEMA_DIR + "web-facelettaglibrary_2_2.xsd";

  /** Location of the faces 2.0 xsd within GlassFish. */
  private static final String FACES_2_0_XSD_FILE = AS_SCHEMA_DIR + "web-facesconfig_2_0.xsd";

  /** Location of the faces 2.1 xsd within GlassFish. */
  private static final String FACES_2_1_XSD_FILE = AS_SCHEMA_DIR + "web-facesconfig_2_0.xsd";

  /** Location of the faces 1.2 xsd within GlassFish. */
  private static final String FACES_1_2_XSD_FILE = AS_SCHEMA_DIR + "web-facesconfig_1_2.xsd";

  /** Our cached 2.0 facelet-taglib Schema object for validation */
  private static Schema FACELET_TAGLIB_20_SCHEMA;

  /** Our cached 2.2 facelet-taglib Schema object for validation */
  private static Schema FACELET_TAGLIB_22_SCHEMA;

  /** Our cached 2.0 Schema object for validation */
  private static Schema FACES_20_SCHEMA;

  /** Our cached 2.1 Schema object for validation */
  private static Schema FACES_21_SCHEMA;

  /** Our cached 1.2 Schema object for validation */
  private static Schema FACES_12_SCHEMA;

  /** Our cached 1.1 Schema object for validation */
  private static Schema FACES_11_SCHEMA;

  /** EntityResolver */
  public static final EntityResolver FACES_ENTITY_RESOLVER = new FacesEntityResolver();

  public enum FacesSchema {
    FACES_20(FACES_20_SCHEMA),
    FACES_21(FACES_21_SCHEMA),
    FACES_12(FACES_12_SCHEMA),
    FACES_11(FACES_11_SCHEMA),
    FACELET_TAGLIB_20(FACELET_TAGLIB_20_SCHEMA),
    FACELET_TAGLIB_22(FACELET_TAGLIB_22_SCHEMA);

    private Schema schema;

    FacesSchema(Schema schema) {
      this.schema = schema;
    }

    public Schema getSchema() {
      return schema;
    }
  }

  /** ErrorHandler */
  public static final FacesErrorHandler FACES_ERROR_HANDLER = new FacesErrorHandler();

  static {
    initStatics();
  }

  // ---------------------------------------------------------- Public Methods

  public static DocumentBuilderFactory getFactory() {

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setIgnoringComments(true);
    factory.setIgnoringElementContentWhitespace(true);
    return factory;
  }

  /** Init our cache objects. */
  private static void initStatics() {
    // First, cache the various files
    // PENDING_RELEASE (rlubke) clean this up
    try {
      URL url = DbfFactory.class.getResource(FACES_1_2_XSD);
      if (url == null) {
        // try to load from the file
        File f = new File(FACES_1_2_XSD_FILE);
        if (!f.exists()) {
          throw new IllegalStateException("Unable to find web-facesconfig_1_2.xsd");
        }
        url = f.toURI().toURL();
      }
      URLConnection conn = url.openConnection();
      conn.setUseCaches(false);
      InputStream in = conn.getInputStream();
      SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      factory.setResourceResolver((LSResourceResolver) DbfFactory.FACES_ENTITY_RESOLVER);
      FACES_12_SCHEMA = factory.newSchema(new StreamSource(in));

      url = DbfFactory.class.getResource(FACES_1_1_XSD);
      conn = url.openConnection();
      conn.setUseCaches(false);
      in = conn.getInputStream();
      factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      factory.setResourceResolver((LSResourceResolver) DbfFactory.FACES_ENTITY_RESOLVER);
      FACES_11_SCHEMA = factory.newSchema(new StreamSource(in));

      url = DbfFactory.class.getResource(FACES_2_1_XSD);
      if (url == null) {
        // try to load from the file
        File f = new File(FACES_2_1_XSD_FILE);
        if (!f.exists()) {
          throw new IllegalStateException("Unable to find web-facesconfig_2_1.xsd");
        }
        url = f.toURI().toURL();
      }
      conn = url.openConnection();
      conn.setUseCaches(false);
      in = conn.getInputStream();
      factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      factory.setResourceResolver((LSResourceResolver) DbfFactory.FACES_ENTITY_RESOLVER);
      FACES_21_SCHEMA = factory.newSchema(new StreamSource(in));

      url = DbfFactory.class.getResource(FACES_2_0_XSD);
      if (url == null) {
        // try to load from the file
        File f = new File(FACES_2_0_XSD_FILE);
        if (!f.exists()) {
          throw new IllegalStateException("Unable to find web-facesconfig_2_0.xsd");
        }
        url = f.toURI().toURL();
      }
      conn = url.openConnection();
      conn.setUseCaches(false);
      in = conn.getInputStream();
      factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      factory.setResourceResolver((LSResourceResolver) DbfFactory.FACES_ENTITY_RESOLVER);
      FACES_20_SCHEMA = factory.newSchema(new StreamSource(in));

      url = DbfFactory.class.getResource(FACELET_TAGLIB_2_0_XSD);
      if (url == null) {
        // try to load from the file
        File f = new File(FACELET_TAGLIB_2_0_XSD_FILE);
        if (!f.exists()) {
          throw new IllegalStateException("Unable to find web-facelettaglibrary_2_0.xsd");
        }
        url = f.toURI().toURL();
      }
      conn = url.openConnection();
      conn.setUseCaches(false);
      in = conn.getInputStream();
      factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
      factory.setResourceResolver((LSResourceResolver) DbfFactory.FACES_ENTITY_RESOLVER);
      FACELET_TAGLIB_20_SCHEMA = factory.newSchema(new StreamSource(in));

    } catch (Exception e) {
      throw new ConfigurationException(e);
    }
  }

  // ----------------------------------------------------------- Inner Classes

  private static class FacesEntityResolver extends DefaultHandler implements LSResourceResolver {

    /** Contains associations between grammar name and the physical resource. */
    private static final String[][] DTD_SCHEMA_INFO = {
      {
        "web-facesconfig_1_0.dtd",
        "/com/sun/faces/web-facesconfig_1_0.dtd",
        AS_DTD_DIR + "web-facesconfig_1_0.dtd"
      },
      {
        "web-facesconfig_1_1.dtd",
        "/com/sun/faces/web-facesconfig_1_1.dtd",
        AS_DTD_DIR + "web-facesconfig_1_1.dtd"
      },
      {"web-facesconfig_2_0.xsd", FACES_2_0_XSD, FACES_2_0_XSD_FILE},
      {"web-facesconfig_2_1.xsd", FACES_2_1_XSD, FACES_2_1_XSD_FILE},
      {"facelet-taglib_1_0.dtd", "/com/sun/faces/facelet-taglib_1_0.dtd", null},
      {"web-facelettaglibrary_2_0.xsd", FACELET_TAGLIB_2_0_XSD, FACELET_TAGLIB_2_0_XSD_FILE},
      {"web-facesconfig_1_2.xsd", FACES_1_2_XSD, FACES_1_2_XSD_FILE},
      {"web-facesconfig_1_1.xsd", FACES_1_1_XSD, null},
      {"javaee_5.xsd", "/com/sun/faces/javaee_5.xsd", AS_SCHEMA_DIR + "javaee_5.xsd"},
      {
        "javaee_web_services_client_1_2.xsd",
        "/com/sun/faces/javaee_web_services_client_1_2.xsd",
        AS_SCHEMA_DIR + "javaee_web_services_client_1_2.xsd"
      },
      {"xml.xsd", "/com/sun/faces/xml.xsd", AS_SCHEMA_DIR + "xml.xsd"},
      {"datatypes.dtd", "/com/sun/faces/datatypes.dtd", AS_SCHEMA_DIR + "datatypes.dtd"},
      {"XMLSchema.dtd", "/com/sun/faces/XMLSchema.dtd", AS_SCHEMA_DIR + "XMLSchema.dtd"}
    };

    /** Contains mapping between grammar name and the local URL to the physical resource. */
    private HashMap<String, String> entities = new HashMap<String, String>(12, 1.0f);

    // -------------------------------------------------------- Constructors

    public FacesEntityResolver() {

      // Add mappings between last segment of system ID and
      // the expected local physical resource.  If the resource
      // cannot be found, then rely on default entity resolution
      // and hope a firewall isn't in the way or a proxy has
      // been configured
      for (String[] aDTD_SCHEMA_INFO : DTD_SCHEMA_INFO) {
        URL url = this.getClass().getResource(aDTD_SCHEMA_INFO[1]);
        if (url == null) {
          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(
                Level.FINE,
                "jsf.config.cannot_resolve_entities",
                new Object[] {aDTD_SCHEMA_INFO[1], aDTD_SCHEMA_INFO[0]});
          }
          // the resource isn't available on the classpath, so
          // assume that we're running within a GF environment
          String path = aDTD_SCHEMA_INFO[2];
          if (path != null) {
            File f = new File(path);
            if (f.exists()) {
              try {
                url = f.toURI().toURL();
              } catch (MalformedURLException mue) {
                if (LOGGER.isLoggable(Level.SEVERE)) {
                  LOGGER.log(Level.SEVERE, mue.toString(), mue);
                }
              }
              if (url == null) {
                if (LOGGER.isLoggable(Level.FINE)) {
                  LOGGER.log(
                      Level.FINE,
                      "jsf.config.cannot_resolve_entities",
                      new Object[] {aDTD_SCHEMA_INFO[1], aDTD_SCHEMA_INFO[2]});
                }
              } else {
                entities.put(aDTD_SCHEMA_INFO[0], url.toString());
              }
            }
          }
        } else {
          entities.put(aDTD_SCHEMA_INFO[0], url.toString());
        }
      }
    } // END JsfEntityResolver

    // ----------------------------------------- Methods from DefaultHandler

    /**
     * Resolves the physical resource using the last segment of the <code>systemId</code> (e.g.
     * http://java.sun.com/dtds/web-facesconfig_1_1.dtd, the last segment would be
     * web-facesconfig_1_1.dtd). If a mapping cannot be found for the segment, then defer to the
     * <code>DefaultHandler</code> for resolution.
     */
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {

      // publicId is ignored.  Resolution performed using
      // the systemId.

      // If no system ID, defer to superclass
      if (systemId == null) {
        InputSource result;
        try {
          result = super.resolveEntity(publicId, null);
        } catch (Exception e) {
          throw new SAXException(e);
        }
        return result;
      }

      String grammarName = systemId.substring(systemId.lastIndexOf('/') + 1);

      String entityURL = entities.get(grammarName);

      InputSource source;
      if (entityURL == null) {
        // we don't have a registered mapping, so defer to our
        // superclass for resolution
        if (LOGGER.isLoggable(Level.FINE)) {
          LOGGER.log(Level.FINE, "Unknown entity, deferring to superclass.");
        }

        try {
          source = super.resolveEntity(publicId, systemId);
        } catch (Exception e) {
          throw new SAXException(e);
        }

      } else {

        try {
          source = new InputSource(new URL(entityURL).openStream());
        } catch (Exception e) {
          if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, "jsf.config.cannot_create_inputsource", entityURL);
          }
          source = null;
        }
      }

      // Set the System ID of the InputSource with the URL of the local
      // resource - necessary to prevent parsing errors
      if (source != null) {
        source.setSystemId(entityURL);

        if (publicId != null) {
          source.setPublicId(publicId);
        }
      }

      return source;
    } // END resolveEntity

    public LSInput resolveResource(
        String type, String namespaceURI, String publicId, String systemId, String baseURI) {
      try {
        InputSource source = resolveEntity(publicId, systemId);
        if (source != null) {
          return new Input(source.getByteStream());
        }
      } catch (Exception e) {
        throw new ConfigurationException(e);
      }
      return null;
    }
  } // END FacesEntityResolver

  private static class FacesErrorHandler implements ErrorHandler {
    public void warning(SAXParseException exception) throws SAXException {
      // do nothing
    }

    public void error(SAXParseException exception) throws SAXException {
      throw exception;
    }

    public void fatalError(SAXParseException exception) throws SAXException {
      throw exception;
    }
  } // END FacesErrorHandler

  private static final class Input implements LSInput {
    InputStream in;

    public Input(InputStream in) {
      this.in = in;
    }

    public Reader getCharacterStream() {
      return null;
    }

    public void setCharacterStream(Reader characterStream) {}

    public InputStream getByteStream() {
      return in;
    }

    public void setByteStream(InputStream byteStream) {}

    public String getStringData() {
      return null;
    }

    public void setStringData(String stringData) {}

    public String getSystemId() {
      return null;
    }

    public void setSystemId(String systemId) {}

    public String getPublicId() {
      return null;
    }

    public void setPublicId(String publicId) {}

    public String getBaseURI() {
      return null;
    }

    public void setBaseURI(String baseURI) {}

    public String getEncoding() {
      return null;
    }

    public void setEncoding(String encoding) {}

    public boolean getCertifiedText() {
      return false;
    }

    public void setCertifiedText(boolean certifiedText) {}
  }
}
Exemple #23
0
  /** The main entry point */
  public static void main(String[] args) throws FileNotFoundException, IOException {

    String xmlfile = null;
    int debug = 0;
    int maxErrs = 10;
    boolean nsAware = true;
    boolean validating = true;
    boolean showWarnings = (debug > 2);
    boolean showErrors = true;
    Vector catalogFiles = new Vector();

    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-c")) {
        ++i;
        catalogFiles.add(args[i]);
        continue;
      }

      if (args[i].equals("-w")) {
        validating = false;
        continue;
      }

      if (args[i].equals("-v")) {
        validating = true;
        continue;
      }

      if (args[i].equals("-n")) {
        nsAware = false;
        continue;
      }

      if (args[i].equals("-N")) {
        nsAware = true;
        continue;
      }

      if (args[i].equals("-d")) {
        ++i;
        String debugstr = args[i];
        try {
          debug = Integer.parseInt(debugstr);
          if (debug >= 0) {
            Debug.setDebug(debug);
            showWarnings = (debug > 2);
          }
        } catch (Exception e) {
          // nop
        }
        continue;
      }

      if (args[i].equals("-E")) {
        ++i;
        String errstr = args[i];
        try {
          int errs = Integer.parseInt(errstr);
          if (errs >= 0) {
            maxErrs = errs;
          }
        } catch (Exception e) {
          // nop
        }
        continue;
      }

      xmlfile = args[i];
    }

    if (xmlfile == null) {
      System.out.println("Usage: org.apache.xml.resolver.apps.xread [opts] xmlfile");
      System.exit(1);
    }

    ResolvingXMLReader reader = new ResolvingXMLReader();

    try {
      reader.setFeature("http://xml.org/sax/features/namespaces", nsAware);
      reader.setFeature("http://xml.org/sax/features/validation", validating);
    } catch (SAXException e) {
      // nop;
    }

    Catalog catalog = reader.getCatalog();

    for (int count = 0; count < catalogFiles.size(); count++) {
      String file = (String) catalogFiles.elementAt(count);
      catalog.parseCatalog(file);
    }

    XParseError xpe = new XParseError(showErrors, showWarnings);
    xpe.setMaxMessages(maxErrs);
    reader.setErrorHandler(xpe);

    String parseType = validating ? "validating" : "well-formed";
    String nsType = nsAware ? "namespace-aware" : "namespace-ignorant";
    if (maxErrs > 0) {
      System.out.println("Attempting " + parseType + ", " + nsType + " parse");
    }

    Date startTime = new Date();

    try {
      reader.parse(xmlfile);
    } catch (SAXException sx) {
      System.out.println("SAX Exception: " + sx);
    } catch (Exception e) {
      e.printStackTrace();
    }

    Date endTime = new Date();

    long millisec = endTime.getTime() - startTime.getTime();
    long secs = 0;
    long mins = 0;
    long hours = 0;

    if (millisec > 1000) {
      secs = millisec / 1000;
      millisec = millisec % 1000;
    }

    if (secs > 60) {
      mins = secs / 60;
      secs = secs % 60;
    }

    if (mins > 60) {
      hours = mins / 60;
      mins = mins % 60;
    }

    if (maxErrs > 0) {
      System.out.print("Parse ");
      if (xpe.getFatalCount() > 0) {
        System.out.print("failed ");
      } else {
        System.out.print("succeeded ");
        System.out.print("(");
        if (hours > 0) {
          System.out.print(hours + ":");
        }
        if (hours > 0 || mins > 0) {
          System.out.print(mins + ":");
        }
        System.out.print(secs + "." + millisec);
        System.out.print(") ");
      }
      System.out.print("with ");

      int errCount = xpe.getErrorCount();
      int warnCount = xpe.getWarningCount();

      if (errCount > 0) {
        System.out.print(errCount + " error");
        System.out.print(errCount > 1 ? "s" : "");
        System.out.print(" and ");
      } else {
        System.out.print("no errors and ");
      }

      if (warnCount > 0) {
        System.out.print(warnCount + " warning");
        System.out.print(warnCount > 1 ? "s" : "");
        System.out.print(".");
      } else {
        System.out.print("no warnings.");
      }

      System.out.println("");
    }

    if (xpe.getErrorCount() > 0) {
      System.exit(1);
    }
  }
/**
 * This class wrapps WikiTableWriter
 *
 * @author shahzad bhatti
 *     <p>modification history date who what 1/9/06 SB created.
 */
public class WikiTableWriter implements ExtendedHierarchicalStreamWriter {
  private final PointableWriter writer;
  private final FastStack elementStack = new FastStack(16);
  private final char[] lineIndenter;

  private boolean useLineSeparateBetweenTags;
  private boolean tagInProgress;
  private int startPointer;
  private int depth;
  private boolean readyForNewLine;
  private boolean tagIsEmpty;
  private boolean quickNodeValue;
  private boolean lastTagHadAttributes;

  private static final char[] AMP = "&amp;".toCharArray();
  private static final char[] LT = "&lt;".toCharArray();
  private static final char[] GT = "&gt;".toCharArray();
  private static final char[] SLASH_R = "&#x0D;".toCharArray();
  private static final char[] QUOT = "&quot;".toCharArray();
  private static final char[] APOS = "&apos;".toCharArray();
  private static final char[] CLOSE = "</".toCharArray();
  private static final String LF = System.getProperty("line.separator");

  /**
   * WikiTableWriter constructor
   *
   * @param writer - output writer object
   * @param lineIdenter - indentation
   */
  public WikiTableWriter(Writer writer, char[] lineIndenter) {
    this.writer = new PointableWriter(writer);
    this.lineIndenter = lineIndenter;
    this.useLineSeparateBetweenTags =
        true; // context.getConfig().getBoolean("testplayer.fitnesse.use.line.separator.between.tags", true);
  }

  /**
   * WikiTableWriter constructor
   *
   * @param writer - output writer object
   * @param lineIdenter - indentation
   */
  public WikiTableWriter(Writer writer, String lineIndenter) {
    this(writer, lineIndenter.toCharArray());
  }

  /**
   * WikiTableWriter constructor
   *
   * @param writer - print writer object
   */
  public WikiTableWriter(PrintWriter writer) {
    this(writer, new char[] {'|'});
  }

  /**
   * WikiTableWriter constructor
   *
   * @param writer - writer object
   */
  public WikiTableWriter(Writer writer) {
    this(new PrintWriter(writer));
  }

  /**
   * Marks start of XML node
   *
   * @param name - name of node
   */
  public void startNode(String name, Class clazz) {
    startNode(name);
  }

  public void startNode(String name) {
    startPointer = writer.getPointer();
    quickNodeValue = false;
    lastTagHadAttributes = false;
    tagIsEmpty = false;
    finishTag();
    if (depth != 0) writer.write(LF);
    writer.write(
        WikiTableDriver.DELIM
            + WikiTableDriver.QUOTES
            + WikiTableDriver.START_NODE
            + WikiTableDriver.QUOTES
            + WikiTableDriver.DELIM);

    if (this.useLineSeparateBetweenTags) {
      writer.write(LF + WikiTableDriver.DELIM);
    }

    writer.write(name + WikiTableDriver.DELIM);
    elementStack.push(name);
    tagInProgress = true;
    depth++;
    readyForNewLine = true;
    tagIsEmpty = true;
  }

  /**
   * Stores value of previously defined XML node
   *
   * @param text - value of node
   */
  public void setValue(String text) {
    readyForNewLine = false;
    tagIsEmpty = false;
    finishTag();

    if (lastTagHadAttributes) {
      writer.write(
          LF
              + WikiTableDriver.DELIM
              + WikiTableDriver.QUOTES
              + WikiTableDriver.SET_VALUE
              + WikiTableDriver.QUOTES
              + WikiTableDriver.DELIM);
      quickNodeValue = false;
    } else {
      String startTag =
          StringHelper.replace(
              writer.substring(startPointer),
              WikiTableDriver.START_NODE,
              WikiTableDriver.SET_NODE_VALUE);

      if (this.useLineSeparateBetweenTags) {
        writer.write(LF + WikiTableDriver.DELIM);
      }

      writer.setPointer(startPointer);
      writer.write(startTag);
      quickNodeValue = true;
    }

    writeText(writer, text);
    writer.write(WikiTableDriver.DELIM);
  }

  /**
   * Adds attribute for XML node
   *
   * @param key - name of attribute
   * @param value - value of attribute
   */
  public void addAttribute(String key, String value) {
    writer.write(
        LF
            + WikiTableDriver.DELIM
            + WikiTableDriver.QUOTES
            + WikiTableDriver.ADD_ATTRIBUTE
            + WikiTableDriver.QUOTES
            + WikiTableDriver.DELIM);

    if (this.useLineSeparateBetweenTags) {
      writer.write(LF + WikiTableDriver.DELIM);
    }

    writer.write(key + WikiTableDriver.DELIM);

    writeAttributeValue(writer, value);
    writer.write(WikiTableDriver.DELIM);
    lastTagHadAttributes = true;
  }

  /** Marks end of node */
  public void endNode() {
    depth--;
    if (tagIsEmpty) {
      String prevTag = (String) elementStack.pop(); // Silently();
      if (!quickNodeValue) {
        writer.write(
            LF
                + WikiTableDriver.DELIM
                + WikiTableDriver.QUOTES
                + WikiTableDriver.END_NODE
                + WikiTableDriver.QUOTES
                + WikiTableDriver.DELIM);
        if (this.useLineSeparateBetweenTags) {
          writer.write(LF + WikiTableDriver.DELIM);
        }
        writer.write(prevTag + WikiTableDriver.DELIM);
      }
      readyForNewLine = false;
    } else {
      String prevTag = (String) elementStack.pop();
      if (!quickNodeValue) {
        writer.write(
            LF
                + WikiTableDriver.DELIM
                + WikiTableDriver.QUOTES
                + WikiTableDriver.END_NODE
                + WikiTableDriver.QUOTES
                + WikiTableDriver.DELIM);
        if (this.useLineSeparateBetweenTags) {
          writer.write(LF + WikiTableDriver.DELIM);
        }
        writer.write(prevTag + WikiTableDriver.DELIM);
      }
    }
    finishTag();
    readyForNewLine = true;
    if (depth == 0) {
      writer.flush();
    }
    quickNodeValue = false;
  }

  /** Flushes output */
  public void flush() {
    writer.flush();
  }

  /** Closes output */
  public void close() {
    writer.close();
  }

  /** Returns underlying writer */
  public HierarchicalStreamWriter underlyingWriter() {
    return this;
  }

  /////////////////////////////////////////////////////////////////////////
  //
  private void finishTag() {
    tagInProgress = false;
    readyForNewLine = false;
    tagIsEmpty = false;
  }

  private void endOfLine() {
    writer.write(LF);
    for (int i = 0; i < depth; i++) {
      writer.write(lineIndenter);
    }
  }

  private void writeAttributeValue(PointableWriter writer, String text) {
    int length = text.length();
    for (int i = 0; i < length; i++) {
      char c = text.charAt(i);
      switch (c) {
        case '&':
          this.writer.write(AMP);
          break;
        case '<':
          this.writer.write(LT);
          break;
        case '>':
          this.writer.write(GT);
          break;
        case '"':
          this.writer.write(QUOT);
          break;
        case '\'':
          this.writer.write(APOS);
          break;
        case '\r':
          this.writer.write(SLASH_R);
          break;
        default:
          this.writer.write(c);
      }
    }
  }

  private void writeText(PointableWriter writer, String text) {
    int length = text.length();
    for (int i = 0; i < length; i++) {
      char c = text.charAt(i);
      switch (c) {
        case '&':
          this.writer.write(AMP);
          break;
        case '<':
          this.writer.write(LT);
          break;
        case '>':
          this.writer.write(GT);
          break;
        case '"':
          this.writer.write(QUOT);
          break;
        case '\'':
          this.writer.write(APOS);
          break;
        case '\r':
          this.writer.write(SLASH_R);
          break;
        default:
          this.writer.write(c);
      }
    }
  }
}
  /**
   * Loads jetty configuration from the given URL.
   *
   * @param cfgUrl URL to load configuration from.
   * @throws GridException if load failed.
   */
  private void loadJettyConfiguration(@Nullable URL cfgUrl) throws GridException {
    if (cfgUrl == null) {
      HttpConfiguration httpCfg = new HttpConfiguration();

      httpCfg.setSecureScheme("https");
      httpCfg.setSecurePort(8443);
      httpCfg.setSendServerVersion(true);
      httpCfg.setSendDateHeader(true);

      String srvPortStr = System.getProperty(GG_JETTY_PORT, "8080");

      int srvPort;

      try {
        srvPort = Integer.valueOf(srvPortStr);
      } catch (NumberFormatException ignore) {
        throw new GridException(
            "Failed to start Jetty server because GRIDGAIN_JETTY_PORT system property "
                + "cannot be cast to integer: "
                + srvPortStr);
      }

      httpSrv = new Server(new QueuedThreadPool(20, 200));

      ServerConnector srvConn = new ServerConnector(httpSrv, new HttpConnectionFactory(httpCfg));

      srvConn.setHost(System.getProperty(GG_JETTY_HOST, "localhost"));
      srvConn.setPort(srvPort);
      srvConn.setIdleTimeout(30000L);
      srvConn.setReuseAddress(true);

      httpSrv.addConnector(srvConn);

      httpSrv.setStopAtShutdown(false);
    } else {
      XmlConfiguration cfg;

      try {
        cfg = new XmlConfiguration(cfgUrl);
      } catch (FileNotFoundException e) {
        throw new GridSpiException("Failed to find configuration file: " + cfgUrl, e);
      } catch (SAXException e) {
        throw new GridSpiException("Failed to parse configuration file: " + cfgUrl, e);
      } catch (IOException e) {
        throw new GridSpiException("Failed to load configuration file: " + cfgUrl, e);
      } catch (Exception e) {
        throw new GridSpiException(
            "Failed to start HTTP server with configuration file: " + cfgUrl, e);
      }

      try {
        httpSrv = (Server) cfg.configure();
      } catch (Exception e) {
        throw new GridException("Failed to start Jetty HTTP server.", e);
      }
    }

    assert httpSrv != null;

    httpSrv.setHandler(jettyHnd);

    override(getJettyConnector());
  }
  /** {@inheritDoc} */
  @SuppressWarnings("BusyWait")
  @Override
  public void start(GridRestProtocolHandler hnd) throws GridException {
    InetAddress locHost;

    try {
      locHost = U.resolveLocalHost(ctx.config().getLocalHost());
    } catch (IOException e) {
      throw new GridException(
          "Failed to resolve local host to bind address: " + ctx.config().getLocalHost(), e);
    }

    System.setProperty(GG_JETTY_HOST, locHost.getHostAddress());

    jettyHnd =
        new GridJettyRestHandler(
            hnd,
            new C1<String, Boolean>() {
              @Override
              public Boolean apply(String tok) {
                return F.isEmpty(secretKey) || authenticate(tok);
              }
            },
            log);

    String jettyPath = ctx.config().getRestJettyPath();

    final URL cfgUrl;

    if (jettyPath == null) {
      cfgUrl = null;

      if (log.isDebugEnabled())
        log.debug("Jetty configuration file is not provided, using defaults.");
    } else {
      cfgUrl = U.resolveGridGainUrl(jettyPath);

      if (cfgUrl == null)
        throw new GridSpiException("Invalid Jetty configuration file: " + jettyPath);
      else if (log.isDebugEnabled()) log.debug("Jetty configuration file: " + cfgUrl);
    }

    loadJettyConfiguration(cfgUrl);

    AbstractNetworkConnector connector = getJettyConnector();

    try {
      host = InetAddress.getByName(connector.getHost());
    } catch (UnknownHostException e) {
      throw new GridException("Failed to resolve Jetty host address: " + connector.getHost(), e);
    }

    int initPort = connector.getPort();

    int lastPort = initPort + ctx.config().getRestPortRange() - 1;

    for (port = initPort; port <= lastPort; port++) {
      connector.setPort(port);

      if (startJetty()) {
        if (log.isInfoEnabled()) log.info(startInfo());

        return;
      }
    }

    U.warn(
        log,
        "Failed to start Jetty REST server (possibly all ports in range are in use) "
            + "[firstPort="
            + initPort
            + ", lastPort="
            + lastPort
            + ']');
  }
Exemple #27
0
  /**
   * Format this XML data as a String.
   *
   * @webref xml:method
   * @brief Formats XML data as a String
   * @param indent -1 for a single line (and no declaration), >= 0 for indents and newlines
   * @return the content
   * @see XML#toString()
   */
  public String format(int indent) {
    try {
      // entities = doctype.getEntities()
      boolean useIndentAmount = false;
      TransformerFactory factory = TransformerFactory.newInstance();
      if (indent != -1) {
        try {
          factory.setAttribute("indent-number", indent);
        } catch (IllegalArgumentException e) {
          useIndentAmount = true;
        }
      }
      Transformer transformer = factory.newTransformer();

      // Add the XML declaration at the top if this node is the root and we're
      // not writing to a single line (indent = -1 means single line).
      if (indent == -1 || parent == null) {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      } else {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      }

      //      transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "sample.dtd");

      transformer.setOutputProperty(OutputKeys.METHOD, "xml");

      //      transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes");  // huh?

      //      transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
      //          "-//W3C//DTD XHTML 1.0 Transitional//EN");
      //      transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
      //          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");

      // For Android, because (at least 2.3.3) doesn't like indent-number
      if (useIndentAmount) {
        transformer.setOutputProperty(
            "{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
      }

      //      transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
      //      transformer.setOutputProperty(OutputKeys.ENCODING,"UTF8");
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      //      transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS

      // Always indent, otherwise the XML declaration will just be jammed
      // onto the first line with the XML code as well.
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");

      //      Properties p = transformer.getOutputProperties();
      //      for (Object key : p.keySet()) {
      //        System.out.println(key + " -> " + p.get(key));
      //      }

      // If you smell something, that's because this code stinks. No matter
      // the settings of the Transformer object, if the XML document already
      // has whitespace elements, it won't bother re-indenting/re-formatting.
      // So instead, transform the data once into a single line string.
      // If indent is -1, then we're done. Otherwise re-run and the settings
      // of the factory will kick in. If you know a better way to do this,
      // please contribute. I've wasted too much of my Sunday on it. But at
      // least the Giants are getting blown out by the Falcons.

      final String decl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
      final String sep = System.getProperty("line.separator");

      StringWriter tempWriter = new StringWriter();
      StreamResult tempResult = new StreamResult(tempWriter);
      transformer.transform(new DOMSource(node), tempResult);
      String[] tempLines = PApplet.split(tempWriter.toString(), sep);
      //      PApplet.println(tempLines);
      if (tempLines[0].startsWith("<?xml")) {
        // Remove XML declaration from the top before slamming into one line
        int declEnd = tempLines[0].indexOf("?>") + 2;
        // if (tempLines[0].length() == decl.length()) {
        if (tempLines[0].length() == declEnd) {
          // If it's all the XML declaration, remove it
          //          PApplet.println("removing first line");
          tempLines = PApplet.subset(tempLines, 1);
        } else {
          //          PApplet.println("removing part of first line");
          // If the first node has been moved to this line, be more careful
          // tempLines[0] = tempLines[0].substring(decl.length());
          tempLines[0] = tempLines[0].substring(declEnd);
        }
      }
      String singleLine = PApplet.join(PApplet.trim(tempLines), "");
      if (indent == -1) {
        return singleLine;
      }

      // Might just be whitespace, which won't be valid XML for parsing below.
      // https://github.com/processing/processing/issues/1796
      // Since indent is not -1, that means they want valid XML,
      // so we'll give them the single line plus the decl... Lame? sure.
      if (singleLine.trim().length() == 0) {
        // You want whitespace? I've got your whitespace right here.
        return decl + sep + singleLine;
      }

      // Since the indent is not -1, bring back the XML declaration
      // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

      StringWriter stringWriter = new StringWriter();
      StreamResult xmlOutput = new StreamResult(stringWriter);
      //      DOMSource source = new DOMSource(node);
      Source source = new StreamSource(new StringReader(singleLine));
      transformer.transform(source, xmlOutput);
      String outgoing = stringWriter.toString();

      // Add the XML declaration to the top if it's not there already
      if (outgoing.startsWith(decl)) {
        int declen = decl.length();
        int seplen = sep.length();
        if (outgoing.length() > declen + seplen
            && !outgoing.substring(declen, declen + seplen).equals(sep)) {
          // make sure there's a line break between the XML decl and the code
          return outgoing.substring(0, decl.length()) + sep + outgoing.substring(decl.length());
        }
        return outgoing;
      } else {
        return decl + sep + outgoing;
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
 /**
  * @param errCode
  * @param msg
  */
 public static void exit(int errCode, String msg) {
   System.err.println(msg);
   System.exit(errCode);
 }
Exemple #29
0
  public static MiningResult importFile(InputStream input) throws IOException {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      Document doc;
      // NodeList netNodes;
      dbf.setValidating(false);
      dbf.setIgnoringComments(true);
      dbf.setIgnoringElementContentWhitespace(true);
      // dbf.setExpandEntityReferences(false);
      // dbf.setNamespaceAware(false);

      DocumentBuilder db = dbf.newDocumentBuilder();

      db.setEntityResolver(
          new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
              if (systemId.indexOf("ARIS-Export") != -1) {
                return new InputSource("file:" + About.EXTLIBLOCATION() + "ARIS-Export101.dtd");
              } else {
                return null;
              }
            }
          });

      InputSource inpStream = new InputSource(input);
      inpStream.setSystemId("file:" + System.getProperty("user.dir", ""));
      doc = db.parse(inpStream);

      // check if root element is a aml tag
      Message.add("parsing done" + doc, Message.DEBUG);
      if (!(doc.getDocumentElement().getNodeName().equals("AML"))) {
        Message.add("aml tag not found", Message.ERROR);
        throw new Exception("aml tag not found");
      } else {
        Message.add("aml root element found");
      }

      EPCResult result = new EPCResult(null, (EPC) null);
      HashMap ObjDef_LinkId = new HashMap();
      HashMap modelid_net = new HashMap();
      HashMap ObjDef_Name = new HashMap();
      HashMap function_LinkId = new HashMap();
      HashMap ModelId_ModelType = new HashMap();
      traverseAMLforObjectNames(
          ObjDef_Name, doc.getDocumentElement(), ObjDef_LinkId, ModelId_ModelType);
      Iterator findLinkToEpc = ObjDef_LinkId.keySet().iterator();
      while (findLinkToEpc.hasNext()) {
        String currentObjDef = (String) findLinkToEpc.next();
        String Links = (String) ObjDef_LinkId.get(currentObjDef);
        StringTokenizer linkSet = new StringTokenizer(Links);
        String realEpcLink = "";
        while (linkSet.hasMoreTokens()) {
          String currentLink = linkSet.nextToken();
          if (ModelId_ModelType.get(currentLink).equals("MT_EEPC")) {
            realEpcLink = currentLink;
            break;
          }
        }
        if (realEpcLink.equals(" ")) {
          ObjDef_LinkId.remove(currentObjDef);
        } else {
          ObjDef_LinkId.put(currentObjDef, realEpcLink);
        }
      }
      result =
          traverseAML(
              result,
              doc.getDocumentElement(),
              null,
              ObjDef_Name,
              ObjDef_LinkId,
              modelid_net,
              function_LinkId);
      Iterator hierarchicalFunctions = function_LinkId.keySet().iterator();
      while (hierarchicalFunctions.hasNext()) {
        EPCSubstFunction f = (EPCSubstFunction) hierarchicalFunctions.next();
        f.setSubstitutedEPC((EPC) modelid_net.get(function_LinkId.get(f)));
        // Message.add(f.getSubstitutedEPC().getName());
      }

      return result;

    } catch (Throwable x) {
      Message.add(x.toString());
      throw new IOException(x.getMessage());
    }
  }
Exemple #30
0
  public static void main(String[] args) {
    AML2PNML(args);
    // EPML2PNML(args);

    System.exit(0);
  }