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.º 2
0
  @Override
  public Transformer newTransformer(Source source, ByteArrayOutputStream errors)
      throws TransformerConfigurationException {

    TransformerFactory transformerFactory =
        TransformerFactory.newInstance(TRANSFORMER_FACTORY_CLASS_NAME, saxon6ClassLoader);

    try {
      ErrorListener errorListener = transformerFactory.getErrorListener();
      Class StandardErrorListenerClass =
          saxon6ClassLoader.loadClass(STANDARD_ERROR_LISTENER_CLASS_NAME);
      StandardErrorListenerClass.getMethod(SET_ERROR_OUTPUT_METHOD, PrintStream.class)
          .invoke(errorListener, new PrintStream(errors));

      return transformerFactory.newTransformer(source);

    } catch (ClassNotFoundException e) {
      throw new TransformerConfigurationException(TRANSFORMER_FACTORY_CLASS_NAME + " not found");
    } catch (NoSuchMethodException e) {
      throw new TransformerConfigurationException(
          TRANSFORMER_FACTORY_CLASS_NAME + ": no such method for error listener");
    } catch (IllegalAccessException e) {
      throw new TransformerConfigurationException(
          TRANSFORMER_FACTORY_CLASS_NAME + " not accessible");
    } catch (InvocationTargetException e) {
      throw new TransformerConfigurationException(
          TRANSFORMER_FACTORY_CLASS_NAME + ": could invoke method for error listener");
    }
  }
  /**
   * Method updates existing Spring bean definitions in a XML application context file. Bean
   * definition is identified by its type defining class.
   *
   * @param project
   * @param type
   * @param jaxbElement
   */
  public void updateBeanDefinitions(
      File configFile, Project project, Class<?> type, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(
              new ClassPathResource("transform/update-bean-type.xsl").getInputStream());
      xsltSource.setSystemId("update-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      LSParser parser = XMLUtils.createLSParser();
      GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null);
      parser.setFilter(getBeanFilter);

      for (File file : configFiles) {
        parser.parseURI(file.toURI().toString());
        if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) {
          xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file)));

          String beanElement = type.getAnnotation(XmlRootElement.class).name();
          String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace();

          // create transformer
          Transformer transformer = transformerFactory.newTransformer(xsltSource);
          transformer.setParameter("bean_element", beanElement);
          transformer.setParameter("bean_namespace", beanNamespace);
          transformer.setParameter(
              "bean_content",
              getXmlContent(jaxbElement)
                  .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1")
                  .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

          // transform
          StringResult result = new StringResult();
          transformer.transform(xmlSource, result);
          FileUtils.writeToFile(
              format(result.toString(), project.getSettings().getTabSize()), file);
          return;
        }
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
Exemplo n.º 4
0
 private static Class getTransformerClass(String clazz) throws ClassNotFoundException {
   Class transformerClass = classNameToHandlerClass.get(clazz);
   if (transformerClass == null) {
     transformerClass = Class.forName(clazz);
     classNameToHandlerClass.put(clazz, transformerClass);
   }
   return transformerClass;
 }
  /**
   * Method removes all Spring bean definitions of given type from the XML application context file.
   *
   * @param project
   * @param type
   */
  public void removeBeanDefinitions(File configFile, Project project, Class<?> type) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(
              new ClassPathResource("transform/delete-bean-type.xsl").getInputStream());
      xsltSource.setSystemId("delete-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      for (File file : configFiles) {
        xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

        String beanElement = type.getAnnotation(XmlRootElement.class).name();
        String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace();

        // create transformer
        Transformer transformer = transformerFactory.newTransformer(xsltSource);
        transformer.setParameter("bean_element", beanElement);
        transformer.setParameter("bean_namespace", beanNamespace);

        // transform
        StringResult result = new StringResult();
        transformer.transform(xmlSource, result);
        FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
        return;
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
Exemplo n.º 6
0
  static {
    try {
      // Try to load Saxon implementation before defaulting to default implementation.
      transformerFactory =
          (TransformerFactoryImpl)
              Class.forName("net.sf.saxon.TransformerFactoryImpl").getConstructor().newInstance();
      logger.info("Using Saxon transformer.");
    } catch (Exception e) {
      transformerFactory = TransformerFactory.newInstance();
      logger.info("Using default transformer.");
    }

    transformerFactory.setURIResolver(
        new URIResolver() {
          @Override
          public Source resolve(String href, String base) throws TransformerException {
            return !"".equals(base)
                ? null
                : new StreamSource(
                    getClass()
                        .getResourceAsStream(String.format("/iso-schematron-xslt2/%s", href)));
          }
        });
  }
Exemplo n.º 7
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);
          }
        }
      }
    }
  }
 /**
  * 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()]);
 }