Exemplo n.º 1
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();
  }
 /** For internal use only. */
 private static Object makeDerivedWrapper(Element elt, String baseTypeName) {
   synchronized (DOMUtils.getDOMLock(elt)) {
     QName typeName = XArchUtils.getXSIType(elt);
     if (typeName == null) {
       return null;
     } else {
       if (!DOMUtils.hasXSIType(
           elt, "http://www.ics.uci.edu/pub/arch/xArch/changesets.xsd", baseTypeName)) {
         try {
           String packageTitle = XArchUtils.getPackageTitle(typeName.getNamespaceURI());
           String packageName = XArchUtils.getPackageName(packageTitle);
           String implName = XArchUtils.getImplName(packageName, typeName.getName());
           Class c = Class.forName(implName);
           java.lang.reflect.Constructor con = c.getConstructor(new Class[] {Element.class});
           Object o = con.newInstance(new Object[] {elt});
           return o;
         } catch (Exception e) {
           // Lots of bad things could happen, but this
           // is OK, because this is best-effort anyway.
         }
       }
       return null;
     }
   }
 }
 Document parseDocument(String filename) throws Exception {
   FileReader reader = new FileReader(filename);
   String firstLine = new BufferedReader(reader).readLine();
   reader.close();
   Document document = null;
   if (firstLine.startsWith("<?xml")) {
     System.err.println("XML detected; using default XML parser.");
   } else {
     try {
       Class nekoParserClass = Class.forName("org.cyberneko.html.parsers.DOMParser");
       Object parser = nekoParserClass.newInstance();
       Method parse = nekoParserClass.getMethod("parse", new Class[] {String.class});
       Method getDocument = nekoParserClass.getMethod("getDocument", new Class[0]);
       parse.invoke(parser, filename);
       document = (Document) getDocument.invoke(parser);
     } catch (Exception e) {
       System.err.println("NekoHTML HTML parser not found; HTML4 support disabled.");
     }
   }
   if (document == null) {
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     try { // http://www.w3.org/blog/systeam/2008/02/08/w3c_s_excessive_dtd_traffic
       factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
     } catch (ParserConfigurationException e) {
       System.err.println("Warning: Could not disable external DTD loading");
     }
     DocumentBuilder builder = factory.newDocumentBuilder();
     document = builder.parse(filename);
   }
   return document;
 }
Exemplo n.º 4
0
  /**
   * @param args 1. rddl description file name (can be directory), in RDDL format, with complete
   *     path 2. (optional) port number 3. (optional) random seed
   */
  public static void main(String[] args) {

    // StateViz state_viz = new GenericScreenDisplay(true);
    StateViz state_viz = new NullScreenDisplay(false);

    ArrayList<RDDL> rddls = new ArrayList<RDDL>();
    int port = PORT_NUMBER;
    if (args.length < 1) {
      System.out.println(
          "usage: rddlfilename (optional) portnumber random-seed state-viz-class-name");
      System.out.println("\nexample 1: Server rddlfilename");
      System.out.println("example 2: Server rddlfilename 2323");
      System.out.println("example 3: Server rddlfilename 2323 0 rddl.viz.GenericScreenDisplay");
      System.exit(1);
    }

    try {
      // Load RDDL files
      RDDL rddl = new RDDL();
      File f = new File(args[0]);
      if (f.isDirectory()) {
        for (File f2 : f.listFiles())
          if (f2.getName().endsWith(".rddl")) {
            System.out.println("Loading: " + f2);
            rddl.addOtherRDDL(parser.parse(f2));
          }
      } else rddl.addOtherRDDL(parser.parse(f));

      if (args.length > 1) {
        port = Integer.valueOf(args[1]);
      }
      ServerSocket socket1 = new ServerSocket(port);
      if (args.length > 2) {
        Server.rand = new Random(Integer.valueOf(args[2]));
      } else {
        Server.rand = new Random(DEFAULT_SEED);
      }
      if (args.length > 3) {
        state_viz = (StateViz) Class.forName(args[3]).newInstance();
      }
      System.out.println("RDDL Server Initialized");
      while (true) {
        Socket connection = socket1.accept();
        Runnable runnable = new Server(connection, ++ID, rddl, state_viz);
        Thread thread = new Thread(runnable);
        thread.start();
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      System.out.println(e);
      e.printStackTrace();
    }
  }
  /** This method generates the output given a context and output stream */
  public boolean generate(XPathContext context, ProgramWriter out) {
    try {
      String collectionName = Strings.firstUpper(collection.getName());

      if (ejb) {
        out.print(" \n\t/**\n\t * @ejb:interface-method\n\t */");
      }
      out.print(" \n\tpublic java.util.Collection get");
      out.print(collectionName);
      out.print("() {");
      if (ejb) {
        out.print(
            " \n\t\tboolean cmtActivated = false;\n\t\tif (!org.openxava.hibernate.XHibernate.isCmt()) {\n\t\t\torg.openxava.hibernate.XHibernate.setCmt(true);\n\t\t\tcmtActivated = true;\n\t\t}");
      }
      out.print(" \n\t\ttry {");

      MetaCalculator calculator = collection.getMetaCalculator();
      String calculatorClass = calculator.getClassName();

      out.print(" \t\t\n\t\t\t");
      out.print(calculatorClass);
      out.print(" ");
      out.print(collection.getName());
      out.print("Calculator= (");
      out.print(calculatorClass);
      out.print(")\n\t\t\t\tgetMetaModel().getMetaCollection(\"");
      out.print(collection.getName());
      out.print("\").getMetaCalculator().createCalculator();");

      Iterator itSets = calculator.getMetaSetsWithoutValue().iterator();
      while (itSets.hasNext()) {
        MetaSet set = (MetaSet) itSets.next();
        String propertyNameInCalculator = Strings.firstUpper(set.getPropertyName());
        String propertyNameFrom = set.getPropertyNameFrom();
        MetaProperty p = metaModel.getMetaProperty(propertyNameFrom);
        if (propertyNameFrom.indexOf('.') >= 0) {
          if (p.isKey() || p.getMetaModel() instanceof MetaAggregate) {
            propertyNameFrom = Strings.firstUpper(Strings.change(propertyNameFrom, ".", "_"));
          } else {
            StringTokenizer st = new StringTokenizer(propertyNameFrom, ".");
            String ref = st.nextToken();
            String pro = st.nextToken();
            propertyNameFrom = Strings.firstUpper(ref) + "().get" + Strings.firstUpper(pro);
          }
        } else {
          propertyNameFrom = Strings.firstUpper(propertyNameFrom);
        }
        String getPropertyFrom = "boolean".equals(p.getTypeName()) ? "is" : "get";
        String value = set.getValue();
        if (set.hasValue()) {

          out.print(" \n\t\t\t");
          out.print(collection.getName());
          out.print("Calculator.set");
          out.print(propertyNameInCalculator);
          out.print("(\"");
          out.print(value);
          out.print("\");");

        } else {

          out.print("  \t\n\t\t\t");
          out.print(collection.getName());
          out.print("Calculator.set");
          out.print(propertyNameInCalculator);
          out.print("(");
          out.print(getPropertyFrom);
          out.print(propertyNameFrom);
          out.print("());");
        }
      } // else/sets
      if (IModelCalculator.class.isAssignableFrom(Class.forName(calculatorClass))) {

        out.print(" \n\t\t\t\t");
        out.print(collection.getName());
        out.print("Calculator.setModel(this);");
      }
      if (IEntityCalculator.class.isAssignableFrom(Class.forName(calculatorClass))) {

        out.print(" \n\t\t\t\t");
        out.print(collection.getName());
        out.print("Calculator.setEntity(this);");
      }
      if (IJDBCCalculator.class.isAssignableFrom(Class.forName(calculatorClass))) {

        out.print(" \n\t\t\t\t");
        out.print(collection.getName());
        out.print("Calculator.setConnectionProvider(getPortableContext());");
      }
      String calculateValueSentence = collection.getName() + "Calculator.calculate()";

      out.print(" \n\t\t\treturn ");
      out.print(Generators.generateCast("java.util.Collection", calculateValueSentence));
      out.print(
          ";\n\t\t}\n\t\tcatch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t\tthrow new ");
      out.print(getException());
      out.print("(XavaResources.getString(\"generator.calculate_value_error\", \"");
      out.print(collection.getName());
      out.print("\", \"");
      out.print(metaModel.getName());
      out.print("\", ex.getLocalizedMessage()));\n\t\t}");
      if (ejb) {
        out.print(
            " \n\t\tfinally {\n\t\t\tif (cmtActivated) {\n\t\t\t\torg.openxava.hibernate.XHibernate.setCmt(false);\n\t\t\t}\n\t\t}");
      }
      out.print(" \t\t\t\t\n\t}");

    } catch (Exception e) {
      System.out.println("Exception: " + e.getMessage());
      e.printStackTrace();
      return false;
    }
    return true;
  }
Exemplo n.º 6
0
  /**
   * XML Circuit constructor
   *
   * @param file the file that contains the XML description of the circuit
   * @param g the graphics that will paint the node
   * @throws CircuitLoadingException if the internal circuit can not be loaded
   */
  public CircuitUI(File file, Graphics g) throws CircuitLoadingException {
    this("");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    Document doc;
    Element root;

    Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>();

    try {
      builder = factory.newDocumentBuilder();
      doc = builder.parse(file);
    } catch (SAXException sxe) {
      throw new CircuitLoadingException("SAX exception raised, invalid XML file.");
    } catch (ParserConfigurationException pce) {
      throw new CircuitLoadingException(
          "Parser exception raised, parser configuration is invalid.");
    } catch (IOException ioe) {
      throw new CircuitLoadingException("I/O exception, file cannot be loaded.");
    }

    root = (Element) doc.getElementsByTagName("Circuit").item(0);
    this.setName(root.getAttribute("name"));

    NodeList nl = root.getElementsByTagName("Node");
    Element e;
    Node n;
    Class cl;

    for (int i = 0; i < nl.getLength(); ++i) {
      e = (Element) nl.item(i);

      try {
        cl = Class.forName(e.getAttribute("class"));
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      try {
        n = ((Node) cl.newInstance());
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      this.nodes.add(n);
      n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y")));

      if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name"));

      if (n instanceof giraffe.ui.CompositeNode) {
        try {
          ((CompositeNode) n)
              .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g);
        } catch (Exception exc) {
          /* try to load from the lib */
          ((CompositeNode) n)
              .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g);
        }
      }

      NodeList nlist = e.getElementsByTagName("Anchor");
      Element el;

      for (int j = 0; j < nlist.getLength(); ++j) {
        el = (Element) nlist.item(j);

        Anchor a = n.getAnchor(new Integer(el.getAttribute("id")));
        NodeList linklist = el.getElementsByTagName("Link");
        Element link;
        Link l;

        for (int k = 0; k < linklist.getLength(); ++k) {
          link = (Element) linklist.item(k);
          int id = new Integer(link.getAttribute("id"));
          int index = new Integer(link.getAttribute("index"));

          if (id >= this.linkID) linkID = id + 1;

          if (linkstable.containsKey(id)) {
            l = linkstable.get(id);
            l.addLinkedAnchorAt(a, index);
            a.addLink(l);
          } else {
            l = new Link(id);
            l.addLinkedAnchorAt(a, index);
            this.links.add(l);
            linkstable.put(id, l);
            a.addLink(l);
          }
        }
      }
    }
  }
Exemplo n.º 7
0
  /**
   * Read a catalog from an input stream.
   *
   * <p>This class reads a catalog from an input stream:
   *
   * <ul>
   *   <li>Based on the QName of the root element, it determines which parser to instantiate for
   *       this catalog.
   *   <li>It constructs a DOM Document from the catalog and
   *   <li>For each child of the root node, it calls the parser's parseCatalogEntry method. This
   *       method is expected to make appropriate calls back into the catalog to add entries for the
   *       entries in the catalog. It is free to do this in whatever manner is appropriate (perhaps
   *       using just the node passed in, perhaps wandering arbitrarily throughout the tree).
   * </ul>
   *
   * @param catalog The catalog for which this reader is called.
   * @param is The input stream that is to be read.
   * @throws IOException if the URL cannot be read.
   * @throws UnknownCatalogFormatException if the catalog format is not recognized.
   * @throws UnparseableCatalogException if the catalog cannot be parsed. (For example, if it is
   *     supposed to be XML and isn't well-formed or if the parser class cannot be instantiated.)
   */
  public void readCatalog(Catalog catalog, InputStream is) throws IOException, CatalogException {

    DocumentBuilderFactory factory = null;
    DocumentBuilder builder = null;

    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    try {
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    }

    Document doc = null;

    try {
      doc = builder.parse(is);
    } catch (SAXException se) {
      throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
    }

    Element root = doc.getDocumentElement();

    String namespaceURI = Namespaces.getNamespaceURI(root);
    String localName = Namespaces.getLocalName(root);

    String domParserClass = getCatalogParser(namespaceURI, localName);

    if (domParserClass == null) {
      if (namespaceURI == null) {
        catalog.getCatalogManager().debug.message(1, "No Catalog parser for " + localName);
      } else {
        catalog
            .getCatalogManager()
            .debug
            .message(1, "No Catalog parser for " + "{" + namespaceURI + "}" + localName);
      }
      return;
    }

    DOMCatalogParser domParser = null;

    try {
      domParser = (DOMCatalogParser) Class.forName(domParserClass).newInstance();
    } catch (ClassNotFoundException cnfe) {
      catalog
          .getCatalogManager()
          .debug
          .message(1, "Cannot load XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (InstantiationException ie) {
      catalog
          .getCatalogManager()
          .debug
          .message(1, "Cannot instantiate XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (IllegalAccessException iae) {
      catalog
          .getCatalogManager()
          .debug
          .message(1, "Cannot access XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (ClassCastException cce) {
      catalog
          .getCatalogManager()
          .debug
          .message(1, "Cannot cast XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    }

    Node node = root.getFirstChild();
    while (node != null) {
      domParser.parseCatalogEntry(catalog, node);
      node = node.getNextSibling();
    }
  }
 /**
  * Unmarshall a Chromosome instance from a given XML Element representation.
  *
  * @param a_activeConfiguration current Configuration object
  * @param a_xmlElement the XML Element representation of the Chromosome
  * @return a new Chromosome instance setup with the data from the XML Element representation
  * @throws ImproperXMLException if the given Element is improperly structured or missing data
  * @throws UnsupportedRepresentationException if the actively configured Gene implementation does
  *     not support the string representation of the alleles used in the given XML document
  * @throws GeneCreationException if there is a problem creating or populating a Gene instance
  * @author Neil Rotstan
  * @since 1.0
  */
 public static Gene[] getGenesFromElement(
     Configuration a_activeConfiguration, Element a_xmlElement)
     throws ImproperXMLException, UnsupportedRepresentationException, GeneCreationException {
   // Do some sanity checking. Make sure the XML Element isn't null and
   // that it in fact represents a set of genes.
   // -----------------------------------------------------------------
   if (a_xmlElement == null || !(a_xmlElement.getTagName().equals(GENES_TAG))) {
     throw new ImproperXMLException(
         "Unable to build Chromosome instance from XML Element: "
             + "given Element is not a 'genes' element.");
   }
   List genes = Collections.synchronizedList(new ArrayList());
   // Extract the nested gene elements.
   // ---------------------------------
   NodeList geneElements = a_xmlElement.getElementsByTagName(GENE_TAG);
   if (geneElements == null) {
     throw new ImproperXMLException(
         "Unable to build Gene instances from XML Element: "
             + "'"
             + GENE_TAG
             + "'"
             + " sub-elements not found.");
   }
   // For each gene, get the class attribute so we know what class
   // to instantiate to represent the gene instance, and then find
   // the child text node, which is where the string representation
   // of the allele is located, and extract the representation.
   // -------------------------------------------------------------
   int numberOfGeneNodes = geneElements.getLength();
   for (int i = 0; i < numberOfGeneNodes; i++) {
     Element thisGeneElement = (Element) geneElements.item(i);
     thisGeneElement.normalize();
     // Fetch the class attribute and create an instance of that
     // class to represent the current gene.
     // --------------------------------------------------------
     String geneClassName = thisGeneElement.getAttribute(CLASS_ATTRIBUTE);
     Gene thisGeneObject;
     Class geneClass = null;
     try {
       geneClass = Class.forName(geneClassName);
       try {
         Constructor constr = geneClass.getConstructor(new Class[] {Configuration.class});
         thisGeneObject = (Gene) constr.newInstance(new Object[] {a_activeConfiguration});
       } catch (NoSuchMethodException nsme) {
         // Try it by calling method newGeneInternal.
         // -----------------------------------------
         Constructor constr = geneClass.getConstructor(new Class[] {});
         thisGeneObject = (Gene) constr.newInstance(new Object[] {});
         thisGeneObject =
             (Gene)
                 PrivateAccessor.invoke(
                     thisGeneObject, "newGeneInternal", new Class[] {}, new Object[] {});
       }
     } catch (Throwable e) {
       throw new GeneCreationException(geneClass, e);
     }
     // Find the text node and fetch the string representation of
     // the allele.
     // ---------------------------------------------------------
     NodeList children = thisGeneElement.getChildNodes();
     int childrenSize = children.getLength();
     String alleleRepresentation = null;
     for (int j = 0; j < childrenSize; j++) {
       Element alleleElem = (Element) children.item(j);
       if (alleleElem.getTagName().equals(ALLELE_TAG)) {
         alleleRepresentation = alleleElem.getAttribute("value");
       }
       if (children.item(j).getNodeType() == Node.TEXT_NODE) {
         // We found the text node. Extract the representation.
         // ---------------------------------------------------
         alleleRepresentation = children.item(j).getNodeValue();
         break;
       }
     }
     // Sanity check: Make sure the representation isn't null.
     // ------------------------------------------------------
     if (alleleRepresentation == null) {
       throw new ImproperXMLException(
           "Unable to build Gene instance from XML Element: "
               + "value (allele) is missing representation.");
     }
     // Now set the value of the gene to that reflect the
     // string representation.
     // -------------------------------------------------
     try {
       thisGeneObject.setValueFromPersistentRepresentation(alleleRepresentation);
     } catch (UnsupportedOperationException e) {
       throw new GeneCreationException(
           "Unable to build Gene because it does not support the "
               + "setValueFromPersistentRepresentation() method.");
     }
     // Finally, add the current gene object to the list of genes.
     // ----------------------------------------------------------
     genes.add(thisGeneObject);
   }
   return (Gene[]) genes.toArray(new Gene[genes.size()]);
 }