private static Transformer getTransformer() throws TransformerException {
    if (_transformer == null) {
      TransformerFactory factory = TransformerFactory.newInstance();
      _transformer = factory.newTransformer();
    }

    return _transformer;
  }
Пример #2
0
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      DateFormat df = DateFormat.getDateTimeInstance();
      String titleStr = "C3P0 Status - " + df.format(new Date());

      DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fact.newDocumentBuilder();
      Document doc = db.newDocument();

      Element htmlElem = doc.createElement("html");
      Element headElem = doc.createElement("head");

      Element titleElem = doc.createElement("title");
      titleElem.appendChild(doc.createTextNode(titleStr));

      Element bodyElem = doc.createElement("body");

      Element h1Elem = doc.createElement("h1");
      h1Elem.appendChild(doc.createTextNode(titleStr));

      Element h3Elem = doc.createElement("h3");
      h3Elem.appendChild(doc.createTextNode("PooledDataSources"));

      Element pdsDlElem = doc.createElement("dl");
      pdsDlElem.setAttribute("class", "PooledDataSources");
      for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) {
        PooledDataSource pds = (PooledDataSource) ii.next();
        StatusReporter sr = findStatusReporter(pds, doc);
        pdsDlElem.appendChild(sr.reportDtElem());
        pdsDlElem.appendChild(sr.reportDdElem());
      }

      headElem.appendChild(titleElem);
      htmlElem.appendChild(headElem);

      bodyElem.appendChild(h1Elem);
      bodyElem.appendChild(h3Elem);
      bodyElem.appendChild(pdsDlElem);
      htmlElem.appendChild(bodyElem);

      res.setContentType("application/xhtml+xml");

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      Source src = new DOMSource(doc);
      Result result = new StreamResult(res.getOutputStream());
      transformer.transform(src, result);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
  void outputDocument(Writer out) throws Exception {
    // Set up the output transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    //		trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.METHOD, "html");

    // Print the DOM node
    StreamResult result = new StreamResult(out);
    DOMSource source = new DOMSource(this.document);
    trans.transform(source, result);
  }
Пример #4
0
  /**
   * http://www.atmarkit.co.jp/fxml/rensai2/xmltool04/02.html
   *
   * @return
   */
  private static Transformer getTransformer() {
    if (s_transformer == null) {
      TransformerFactory transFactory = TransformerFactory.newInstance();
      try {
        s_transformer = transFactory.newTransformer();
      } catch (TransformerConfigurationException e) {
      }

      s_transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      s_transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    } // if

    return s_transformer;
  }
Пример #5
0
  /** Check for required facilities. If not available, an exception will be thrown. */
  public TemplatesPool(boolean templateCaching) throws Exception {
    final TransformerFactory tFactory = TransformerFactory.newInstance();
    final String processorClass = tFactory.getClass().getName();

    /*
     * Only report XSLT processor class once.
     */
    if (!reportedProcessors.contains(processorClass)) {
      logger.info("XSLT transformer factory: " + processorClass);
      reportedProcessors.add(processorClass);
    }

    if (!tFactory.getFeature(SAXSource.FEATURE) || !tFactory.getFeature(SAXResult.FEATURE)) {
      throw new Exception("Required source types not supported by the transformer factory.");
    }

    if (!tFactory.getFeature(SAXResult.FEATURE) || !tFactory.getFeature(StreamResult.FEATURE)) {
      throw new Exception("Required result types not supported by the transformer factory.");
    }

    if (!(tFactory instanceof SAXTransformerFactory)) {
      throw new Exception(
          "TransformerFactory not an instance of SAXTransformerFactory: "
              + tFactory.getClass().getName());
    }

    this.tFactory = ((SAXTransformerFactory) tFactory);
    this.tFactory.setErrorListener(new StylesheetErrorListener());
    this.templateCaching = templateCaching;
  }
Пример #6
0
  /**
   * Loads nested schema type definitions from wsdl.
   *
   * @throws IOException
   * @throws WSDLException
   * @throws TransformerFactoryConfigurationError
   * @throws TransformerException
   * @throws TransformerConfigurationException
   */
  private void loadSchemas()
      throws WSDLException, IOException, TransformerConfigurationException, TransformerException,
          TransformerFactoryConfigurationError {
    Definition definition =
        WSDLFactory.newInstance().newWSDLReader().readWSDL(wsdl.getFile().getAbsolutePath());

    Types types = definition.getTypes();
    List<?> schemaTypes = types.getExtensibilityElements();

    for (Object schemaObject : schemaTypes) {
      if (schemaObject instanceof SchemaImpl) {
        SchemaImpl schema = (SchemaImpl) schemaObject;

        inheritNamespaces(schema, definition);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Source source = new DOMSource(schema.getElement());
        Result result = new StreamResult(bos);

        TransformerFactory.newInstance().newTransformer().transform(source, result);
        Resource schemaResource = new ByteArrayResource(bos.toByteArray());

        schemas.add(schemaResource);

        if (definition
            .getTargetNamespace()
            .equals(schema.getElement().getAttribute("targetNamespace"))) {
          setXsd(schemaResource);
        }
      } else {
        log.warn("Found unsupported schema type implementation " + schemaObject.getClass());
      }
    }
  }
  /**
   * Method removes a Spring bean definition from the XML application context file. Bean definition
   * is identified by its id or bean name.
   *
   * @param project
   * @param id
   */
  public void removeBeanDefinition(File configFile, Project project, String id) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/delete-bean.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)));

        // create transformer
        Transformer transformer = transformerFactory.newTransformer(xsltSource);
        transformer.setParameter("bean_id", id);

        // 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);
    }
  }
  /**
   * Marshal jaxb element and try to perform basic formatting like namespace clean up and attribute
   * formatting with xsl transformation.
   *
   * @param jaxbElement
   * @return
   */
  private String getXmlContent(Object jaxbElement) {
    StringResult jaxbContent = new StringResult();

    springBeanMarshaller.marshal(jaxbElement, jaxbContent);

    Source xsltSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/format-bean.xsl").getInputStream());
      Transformer transformer = transformerFactory.newTransformer(xsltSource);

      // transform
      StringResult result = new StringResult();
      transformer.transform(new StringSource(jaxbContent.toString()), result);

      if (log.isDebugEnabled()) {
        log.debug("Created bean definition:\n" + result.toString());
      }

      return result.toString();
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
  /**
   * Method adds a new Spring bean definition to the XML application context file.
   *
   * @param project
   * @param jaxbElement
   */
  public void addBeanDefinition(File configFile, Project project, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream());
      xsltSource.setSystemId("add-bean");
      xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

      // create transformer
      Transformer transformer = transformerFactory.newTransformer(xsltSource);
      transformer.setParameter(
          "bean_content",
          getXmlContent(jaxbElement)
              .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()), configFile);
      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);
    }
  }
 /**
  * Writes an XML file from a Document object.
  *
  * @param doc the Document object to be written to file
  * @param file the file to be written
  * @throws IOException
  * @author Klaus Meffert
  * @since 2.0
  */
 public static void writeFile(Document doc, File file) throws IOException {
   // Use a Transformer for output
   TransformerFactory tFactory = TransformerFactory.newInstance();
   Transformer transformer;
   try {
     transformer = tFactory.newTransformer();
   } catch (TransformerConfigurationException tex) {
     throw new IOException(tex.getMessage());
   }
   DOMSource source = new DOMSource(doc);
   FileOutputStream fos = new FileOutputStream(file);
   StreamResult result = new StreamResult(fos);
   try {
     transformer.transform(source, result);
     fos.close();
   } catch (TransformerException tex) {
     throw new IOException(tex.getMessage());
   }
 }
Пример #11
0
  /**
   * Save the XML description of the circuit
   *
   * @param output an output stream to write in
   * @return true if the dump was successful, false either
   */
  public boolean dumpToXml(OutputStream output) {
    Document doc;
    Element root;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    try {
      builder = factory.newDocumentBuilder();
      doc = builder.newDocument();
    } catch (ParserConfigurationException pce) {
      System.err.println("dumpToXmlFile: unable to write XML save file.");
      return false;
    }

    root = doc.createElement("Circuit");
    root.setAttribute("name", this.getName());

    for (iterNodes = this.nodes.iterator(); iterNodes.hasNext(); )
      iterNodes.next().dumpToXml(doc, root);

    root.normalize();
    doc.appendChild(root);

    try {
      TransformerFactory tffactory = TransformerFactory.newInstance();
      Transformer transformer = tffactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(output);
      transformer.transform(source, result);
    } catch (TransformerConfigurationException tce) {
      System.err.println("dumpToXmlFile:  Configuration Transformer exception.");
      return false;
    } catch (TransformerException te) {
      System.err.println("dumpToXmlFile: Transformer exception.");
      return false;
    }

    return true;
  }
Пример #12
0
  private Transformer buildTransformer(String name, File xslDir, TransformerFactory tf)
      throws Exception {

    Transformer tr =
        tf.newTransformer(
            new StreamSource(
                new FileReader(xslDir.getAbsolutePath() + File.separatorChar + name + ".xsl")));
    tr.setOutputProperty(OutputKeys.INDENT, "yes");
    tr.setOutputProperty(OutputKeys.METHOD, "html");
    tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");

    return tr;
  }
Пример #13
0
 @PostConstruct
 protected void init() {
   transformerFactory.setURIResolver(
       new URIResolver() {
         @Override
         public Source resolve(String href, String base) throws TransformerException {
           try {
             return new StreamSource(new ClassPathResource("transform/" + href).getInputStream());
           } catch (IOException e) {
             throw new TransformerException("Failed to resolve uri: " + href, e);
           }
         }
       });
 }
Пример #14
0
  /**
   * 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);
    }
  }
Пример #15
0
  public static boolean writeXML(File file, Document document) {

    javax.xml.transform.Transformer transformer = null;
    try {
      transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
      return false;
    }

    transformer.setOutputProperty("indent", "yes");
    transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "2");
    transformer.setOutputProperty("encoding", "UTF-8");

    try {
      transformer.transform(new DOMSource(document), new StreamResult(file));
    } catch (TransformerException e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }
Пример #16
0
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
    context = config.getServletContext();

    TextProcessor tp = new CaseFolder();

    try {
      wikipedia =
          new Wikipedia(
              context.getInitParameter("mysql_server"),
              context.getInitParameter("mysql_database"),
              context.getInitParameter("mysql_user"),
              context.getInitParameter("mysql_password"));
    } catch (Exception e) {
      throw new ServletException("Could not connect to wikipedia database.");
    }

    // Escaper escaper = new Escaper() ;

    definer = new Definer(this);
    comparer = new Comparer(this);
    searcher = new Searcher(this);

    try {
      wikifier = new Wikifier(this, tp);

    } catch (Exception e) {
      System.err.println("Could not initialize wikifier");
    }

    try {
      File dataDirectory = new File(context.getInitParameter("data_directory"));

      if (!dataDirectory.exists() || !dataDirectory.isDirectory()) {
        throw new Exception();
      }

      cachingThread = new CacherThread(dataDirectory, tp);
      cachingThread.start();
    } catch (Exception e) {
      throw new ServletException("Could not locate wikipedia data directory.");
    }

    try {
      TransformerFactory tf = TransformerFactory.newInstance();

      transformersByName = new HashMap<String, Transformer>();
      transformersByName.put(
          "help", buildTransformer("help", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "loading", buildTransformer("loading", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "search", buildTransformer("search", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "compare", buildTransformer("compare", new File("/research/wikipediaminer/web/xsl"), tf));
      transformersByName.put(
          "wikify", buildTransformer("wikify", new File("/research/wikipediaminer/web/xsl"), tf));

      Transformer serializer = TransformerFactory.newInstance().newTransformer();
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty(OutputKeys.METHOD, "xml");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
      transformersByName.put("serializer", serializer);

    } catch (Exception e) {
      throw new ServletException("Could not load xslt library.");
    }
  }
Пример #17
0
/** @author Christoph Deppisch */
@Service
public class SpringBeanService {

  public static final String FAILED_TO_UPDATE_BEAN_DEFINITION = "Failed to update bean definition";
  public static final String UNABLE_TO_READ_TRANSFORMATION_SOURCE =
      "Unable to read update bean definition transformation source";

  @Autowired private SpringBeanMarshaller springBeanMarshaller;

  /** XSLT transformer factory */
  private TransformerFactory transformerFactory = TransformerFactory.newInstance();

  /** Logger */
  private static Logger log = LoggerFactory.getLogger(SpringBeanService.class);

  @PostConstruct
  protected void init() {
    transformerFactory.setURIResolver(
        new URIResolver() {
          @Override
          public Source resolve(String href, String base) throws TransformerException {
            try {
              return new StreamSource(new ClassPathResource("transform/" + href).getInputStream());
            } catch (IOException e) {
              throw new TransformerException("Failed to resolve uri: " + href, e);
            }
          }
        });
  }

  /**
   * Reads file import locations from Spring bean application context.
   *
   * @param project
   * @return
   */
  public List<File> getConfigImports(File configFile, Project project) {
    LSParser parser = XMLUtils.createLSParser();

    GetSpringImportsFilter filter = new GetSpringImportsFilter(configFile);
    parser.setFilter(filter);
    parser.parseURI(configFile.toURI().toString());

    return filter.getImportedFiles();
  }

  /**
   * Finds bean definition element by id and type in Spring application context and performs
   * unmarshalling in order to return JaxB object.
   *
   * @param project
   * @param id
   * @param type
   * @return
   */
  public <T> T getBeanDefinition(File configFile, Project project, String id, Class<T> type) {
    LSParser parser = XMLUtils.createLSParser();

    GetSpringBeanFilter filter = new GetSpringBeanFilter(id, type);
    parser.setFilter(filter);

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

    for (File file : configFiles) {
      parser.parseURI(file.toURI().toString());

      if (filter.getBeanDefinition() != null) {
        return createJaxbObjectFromElement(filter.getBeanDefinition());
      }
    }

    return null;
  }

  /**
   * Finds all bean definition elements by type in Spring application context and performs
   * unmarshalling in order to return a list of JaxB object.
   *
   * @param project
   * @param type
   * @return
   */
  public <T> List<T> getBeanDefinitions(File configFile, Project project, Class<T> type) {
    return getBeanDefinitions(configFile, project, type, null);
  }

  /**
   * Finds all bean definition elements by type and attribute values in Spring application context
   * and performs unmarshalling in order to return a list of JaxB object.
   *
   * @param project
   * @param type
   * @param attributes
   * @return
   */
  public <T> List<T> getBeanDefinitions(
      File configFile, Project project, Class<T> type, Map<String, String> attributes) {
    List<T> beanDefinitions = new ArrayList<T>();

    List<File> importedFiles = getConfigImports(configFile, project);
    for (File importLocation : importedFiles) {
      beanDefinitions.addAll(getBeanDefinitions(importLocation, project, type, attributes));
    }

    LSParser parser = XMLUtils.createLSParser();

    GetSpringBeansFilter filter = new GetSpringBeansFilter(type, attributes);
    parser.setFilter(filter);
    parser.parseURI(configFile.toURI().toString());

    for (Element element : filter.getBeanDefinitions()) {
      beanDefinitions.add(createJaxbObjectFromElement(element));
    }

    return beanDefinitions;
  }

  /**
   * Find all Spring bean definitions in application context for given bean type.
   *
   * @param project
   * @param beanType
   * @return
   */
  public List<String> getBeanNames(File configFile, Project project, String beanType) {
    List<SpringBean> beanDefinitions =
        getBeanDefinitions(
            configFile, project, SpringBean.class, Collections.singletonMap("class", beanType));

    List<String> beanNames = new ArrayList<String>();
    for (SpringBean beanDefinition : beanDefinitions) {
      beanNames.add(beanDefinition.getId());
    }

    return beanNames;
  }

  /**
   * Method adds a new Spring bean definition to the XML application context file.
   *
   * @param project
   * @param jaxbElement
   */
  public void addBeanDefinition(File configFile, Project project, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream());
      xsltSource.setSystemId("add-bean");
      xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

      // create transformer
      Transformer transformer = transformerFactory.newTransformer(xsltSource);
      transformer.setParameter(
          "bean_content",
          getXmlContent(jaxbElement)
              .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()), configFile);
      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);
    }
  }

  /**
   * Method removes a Spring bean definition from the XML application context file. Bean definition
   * is identified by its id or bean name.
   *
   * @param project
   * @param id
   */
  public void removeBeanDefinition(File configFile, Project project, String id) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/delete-bean.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)));

        // create transformer
        Transformer transformer = transformerFactory.newTransformer(xsltSource);
        transformer.setParameter("bean_id", id);

        // 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);
    }
  }

  /**
   * 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);
    }
  }

  /**
   * Method updates an existing Spring bean definition in a XML application context file. Bean
   * definition is identified by its id or bean name.
   *
   * @param project
   * @param id
   * @param jaxbElement
   */
  public void updateBeanDefinition(
      File configFile, Project project, String id, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/update-bean.xsl").getInputStream());
      xsltSource.setSystemId("update-bean");

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

      LSParser parser = XMLUtils.createLSParser();
      GetSpringBeanFilter getBeanFilter = new GetSpringBeanFilter(id, jaxbElement.getClass());
      parser.setFilter(getBeanFilter);

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

          // create transformer
          Transformer transformer = transformerFactory.newTransformer(xsltSource);
          transformer.setParameter("bean_id", id);
          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);
    }
  }

  /**
   * 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);
    }
  }

  /**
   * Marshal jaxb element and try to perform basic formatting like namespace clean up and attribute
   * formatting with xsl transformation.
   *
   * @param jaxbElement
   * @return
   */
  private String getXmlContent(Object jaxbElement) {
    StringResult jaxbContent = new StringResult();

    springBeanMarshaller.marshal(jaxbElement, jaxbContent);

    Source xsltSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/format-bean.xsl").getInputStream());
      Transformer transformer = transformerFactory.newTransformer(xsltSource);

      // transform
      StringResult result = new StringResult();
      transformer.transform(new StringSource(jaxbContent.toString()), result);

      if (log.isDebugEnabled()) {
        log.debug("Created bean definition:\n" + result.toString());
      }

      return result.toString();
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }

  /**
   * Do final formatting with Spring bean XML configuration content. Removes empty double lines and
   * formats schemaLocation attribute value with new lines.
   *
   * @param content
   * @param tabSize
   * @return
   */
  private String format(String content, int tabSize) {
    return content
        .replaceAll("(?m)(^\\s*$)+", "")
        .replaceAll("\\.xsd\\s", ".xsd\n" + getTabs(3, tabSize));
  }

  /**
   * Construct tabs according to project settings.
   *
   * @param amount
   * @param tabSize
   * @return
   */
  private String getTabs(int amount, int tabSize) {
    StringBuilder tabs = new StringBuilder();

    for (int i = 1; i <= amount; i++) {
      for (int k = 1; k <= tabSize; k++) {
        tabs.append(" ");
      }
    }

    return tabs.toString();
  }

  /**
   * Creates a DOM element node from JAXB element.
   *
   * @param element
   * @return
   */
  private <T> T createJaxbObjectFromElement(Element element) {
    LSSerializer serializer = XMLUtils.createLSSerializer();
    return (T)
        springBeanMarshaller.unmarshal(
            new StreamSource(new StringReader(serializer.writeToString(element))));
  }

  /**
   * Sets the springBeanMarshaller property.
   *
   * @param springBeanMarshaller
   */
  public void setSpringBeanMarshaller(SpringBeanMarshaller springBeanMarshaller) {
    this.springBeanMarshaller = springBeanMarshaller;
  }
}
Пример #18
0
  public void CollectData(String link) {

    try {
      // Creating an empty XML Document

      DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
      Document doc = docBuilder.newDocument();
      int flag = 0;
      // create the root element and add it to the document
      Element movie = doc.createElement("movie");
      doc.appendChild(movie);
      movie.setAttribute("id", String.valueOf(n));
      n++;
      // create sub elements
      Element genres = doc.createElement("genres");
      Element actors = doc.createElement("actors");
      Element reviews = doc.createElement("reviews");

      URL movieUrl = new URL(link);
      URL reviewsURL = new URL(link + "reviews/#type=top_critics");
      BufferedWriter bw3 = new BufferedWriter(new FileWriter("movies.xml", true));
      int count = -1;
      String auth = "";
      BufferedReader br3 = new BufferedReader(new InputStreamReader(movieUrl.openStream()));
      String str2 = "";
      String info = "";
      while (null != (str2 = br3.readLine())) {
        // start reading the html document
        if (str2.isEmpty()) continue;
        if (count == 14) break;
        if (count == 12) {
          if (!str2.contains("<h3>Cast</h3>")) continue;
          else count++;
        }
        if (count == 13) {
          if (str2.contains(">ADVERTISEMENT</p>")) {
            count++;
            movie.appendChild(actors);
            continue;
          } else {
            if (str2.contains("itemprop=\"name\">")) {
              Element actor = doc.createElement("actor");
              actors.appendChild(actor);
              Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text());
              actor.appendChild(text);
            } else continue;
          }
        }

        if (count <= 11) {
          switch (count) {
            case -1:
              {
                if (!str2.contains("property=\"og:image\"")) continue;
                else {
                  Pattern image =
                      Pattern.compile("http://.*.jpg", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
                  Matcher match = image.matcher(str2);
                  while (match.find()) {

                    Element imageLink = doc.createElement("imageLink");
                    movie.appendChild(imageLink);
                    Text text = doc.createTextNode(match.group());
                    imageLink.appendChild(text);
                    count++;
                  }
                }
                break;
              }
            case 0:
              {
                if (str2.contains("<title>")) {

                  Element name = doc.createElement("name");
                  movie.appendChild(name);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(str2.toString().replace(" - Rotten Tomatoes", "")).text());
                  name.appendChild(text);
                  count++;
                }
                break;
              }
            case 1:
              {
                if (!str2.contains("itemprop=\"ratingValue\"")) break;
                else {
                  Element score = doc.createElement("score");
                  movie.appendChild(score);
                  Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text());
                  score.appendChild(text);
                  count++;
                }
                break;
              }
            case 2:
              {
                if (!str2.contains("itemprop=\"description\">")) continue;
                else count++;
                break;
              }
            case 3:
              {
                if (!str2.contains("itemprop=\"duration\"")) info = info.concat(str2);
                else {
                  Element MovieInfo = doc.createElement("MovieInfo");
                  movie.appendChild(MovieInfo);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  MovieInfo.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 4:
              {
                if (!str2.contains("itemprop=\"genre\"")) info = info.concat(str2);
                else {
                  Element duration = doc.createElement("duration");
                  movie.appendChild(duration);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  duration.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 5:
              {
                if (info.contains("itemprop=\"genre\"")) {
                  Element genre = doc.createElement("genre");
                  genres.appendChild(genre);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  genre.appendChild(text);
                  info = "";
                }
                if (str2.contains(">Directed By:<")) {
                  count++;
                  movie.appendChild(genres);
                  continue;
                } else {

                  if (str2.contains("itemprop=\"genre\"")) {
                    Element genre = doc.createElement("genre");
                    genres.appendChild(genre);
                    Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text());
                    genre.appendChild(text);
                  } else continue;
                }
                break;
              }
            case 6:
              {
                if (!str2.contains(">Written By:<")) {
                  if (str2.contains(">In Theaters:<")) {
                    Element director = doc.createElement("director");
                    movie.appendChild(director);
                    Text text =
                        doc.createTextNode(
                            Jsoup.parse(info.toString().replace("Directed By: ", "")).text());
                    director.appendChild(text);
                    info = str2;
                    count += 2;
                    break;
                  }
                  info = info.concat(str2);
                } else {
                  Element director = doc.createElement("director");
                  movie.appendChild(director);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("Directed By: ", "")).text());
                  director.appendChild(text);
                  info = "";
                  count++;
                }
                break;
              }
            case 7:
              {
                if (!str2.contains(">In Theaters:<")) {
                  if (str2.contains(">On DVD:<")) {
                    Element writer = doc.createElement("writer");
                    movie.appendChild(writer);
                    Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                    writer.appendChild(text);
                    info = str2;
                    count += 2;
                    break;
                  }
                  info = info.concat(str2);
                } else {
                  Element writer = doc.createElement("writer");
                  movie.appendChild(writer);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  writer.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 8:
              {
                if (!str2.contains(">On DVD:<")) info = info.concat(str2);
                else {
                  Element TheatreRelease = doc.createElement("TheatreRelease");
                  movie.appendChild(TheatreRelease);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("In Theaters:", "")).text());
                  TheatreRelease.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 9:
              {
                if (!str2.contains(">US Box Office:<")) {
                  if (str2.contains("itemprop=\"productionCompany\"")) {
                    Element DvdRelease = doc.createElement("DvdRelease");
                    movie.appendChild(DvdRelease);
                    Text text =
                        doc.createTextNode(
                            Jsoup.parse(info.toString().replace("On DVD:", "")).text());
                    DvdRelease.appendChild(text);
                    info = str2;
                    count += 2;
                    break;
                  }
                  info = info.concat(str2);
                } else {
                  Element DvdRelease = doc.createElement("DvdRelease");
                  movie.appendChild(DvdRelease);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("On DVD:", "")).text());
                  DvdRelease.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 10:
              {
                if (!str2.contains("itemprop=\"productionCompany\"")) info = info.concat(str2);
                else {
                  Element BOCollection = doc.createElement("BOCollection");
                  movie.appendChild(BOCollection);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("US Box Office:", "")).text());
                  BOCollection.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 11:
              {
                if (!str2.contains(">Official Site")) info = info.concat(str2);
                else {
                  Element Production = doc.createElement("Production");
                  movie.appendChild(Production);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  Production.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }

            default:
              break;
          }
        }
      }
      BufferedReader br4 = new BufferedReader(new InputStreamReader(reviewsURL.openStream()));
      String str3 = "";
      String info2 = "";
      int count2 = 0;
      while (null != (str3 = br4.readLine())) {
        if (count2 == 0) {

          if (!str3.contains("<div class=\"reviewsnippet\">")) continue;
          else count2++;
        }
        if (count2 == 1) {
          if (!str3.contains("<p class=\"small subtle\">")) info2 = info2.concat(str3);
          else {
            Element review = doc.createElement("review");
            reviews.appendChild(review);
            Text text = doc.createTextNode(Jsoup.parse(info2.toString()).text());
            review.appendChild(text);
            info2 = "";
            count2 = 0;
          }
        }
      }
      movie.appendChild(reviews);
      TransformerFactory transfac = TransformerFactory.newInstance();
      Transformer trans = transfac.newTransformer();
      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      trans.setOutputProperty(OutputKeys.INDENT, "yes");

      // create string from xml tree
      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);
      DOMSource source = new DOMSource(doc);
      trans.transform(source, result);
      String xmlString = sw.toString();
      bw3.write(xmlString);
      br3.close();
      br4.close();
      bw3.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Пример #19
0
  /** @param args the command line arguments */
  public static void main(String[] args) {
    // TODO code application logic here
    Model model;
    String insertstmt;
    String insertmodel = "",
        insertspecies = "",
        insertcompartment = "",
        insertfunction = "",
        insertunitdef = "",
        insertunits = "",
        insertreaction = "",
        insertreactant = "",
        insertproduct = "";
    String insertmodifier = "",
        insertklaw = "",
        insertrules = "",
        insertconstraint = "",
        insertdelay = "",
        inserttrigger = "",
        insertevent = "",
        inserteventassign = "",
        insertparameter = "";
    String insertstatement = "";
    String server, user, password, dbname, filepath;

    String Filedata = "";

    String cwd = System.getProperty("user.dir");

    if (args.length == 0) {
      server = "localhost";
      user = "******";
      password = "******";
      dbname = "sbmldb2";

      /**
       * Path to extract the SBML files from database, where cwd is
       * "github\db2sbml\dbtosbml_standalone_Project\dbtosbml" so add a folder in this directory and
       * mention folder name instead of extractedbm folder
       */
      filepath = cwd + "\\extractedbm\\";
    } else {
      server = args[0];
      user = args[1];
      password = args[2];
      dbname = args[3];
      filepath = args[4];
    }

    try {
      Filedata = readFileAsString(cwd + "\\sbmldbschema.sql");
    } catch (Exception e) {
      e.printStackTrace();
    }

    Mysqlconn sql = new Mysqlconn(server, user, password, dbname);
    // String modelids.getId() = "MorrisonAllegra" ;

    ASTNode math = null;
    int level = 0, version = 0;

    ArrayList<modellist> modelidlist = sql.getmodels();
    insertstatement =
        "LOCK TABLES `model` WRITE,`species` WRITE,`compartment` WRITE,`functiondefinition` WRITE,";
    insertstatement =
        insertstatement
            + "`listofunitdefinitions` WRITE,`listofunits` WRITE,`reaction` WRITE,`simplespeciesreference` WRITE,";
    insertstatement =
        insertstatement
            + "`modifierspeciesreference` WRITE,`kineticlaw` WRITE,`parameter` WRITE,`sbmlconstraint` WRITE,";
    insertstatement =
        insertstatement
            + "`event` WRITE,`sbmltrigger` WRITE,`delay` WRITE,`eventassignment` WRITE,`rules` WRITE"
            + ";";

    for (modellist modelids : modelidlist) {

      ArrayList<modellist> modellevel = sql.getmodeldetails(modelids.getId());

      for (modellist modellv : modellevel) {
        level = modellv.getlevel();
        version = modellv.getversion();
      }

      SBMLDocument doc = new SBMLDocument(level, version);

      ArrayList<modellist> modellists = sql.getmodeldetails(modelids.getId());

      if (!modellists.isEmpty())
        insertmodel =
            insertmodel
                + "\nInsert Into model (id, name,SBML_level,version,notes,annotation) Values";
      for (modellist models : modellists) {
        insertmodel =
            insertmodel
                + "(\'"
                + models.getId()
                + "\',\'"
                + models.getName()
                + "\',"
                + models.getlevel()
                + ","
                + models.getversion()
                + ",\'"
                + models.getnotes()
                + "\',\'"
                + models.getannotation().toString()
                + "\'),";
        model = doc.createModel(models.getId());
        model.setName(models.getName());
        // System.out.println("model : " + models.getId());
        // model.setNotes(models.getnotes());  // there is some null exception is command line run
        // but run perfectly from netbeans so ommented out
        if (!models.getannotation().equals("")) {
          Annotation annot = new Annotation(models.getannotation().toString());
          model.setAnnotation(annot);
        }
        doc.setModel(model);
      }
      if (!modellists.isEmpty()) {
        insertmodel = insertmodel.substring(0, insertmodel.length() - 1);
        insertmodel = insertmodel + ';';
      }
      //   insertmodel = insertmodel + "\nUNLOCK TABLES;";
      //  System.out.println(insertmodel);

      ArrayList<SpeciesList> specieslist = sql.getspecies(modelids.getId());

      if (!specieslist.isEmpty())
        insertspecies =
            insertspecies
                + "\nInsert Into species (id, name, compartment, initialAmount, initialConcentration,substanceUnits,hasOnlySubstanceUnits,boundaryCondition,constant,conversionFactor,model_id,annotation) Values";
      for (SpeciesList species : specieslist) {
        insertspecies =
            insertspecies
                + "(\'"
                + species.getId()
                + "\',\'"
                + species.getName()
                + "\',\'"
                + species.getcompartment()
                + "\',"
                + species.getia()
                + ","
                + species.getic()
                + ",\'"
                + species.getsu()
                + "\',"
                + species.gethosu()
                + ","
                + species.getbc()
                + ","
                + species.getconstant()
                + ","
                + species.getcf()
                + ",\'"
                + modelids.getId()
                + "\',\'"
                + species.getannotation()
                + "\'),";
        Species sp = doc.getModel().createSpecies(species.getId());
        sp.setName(species.getName());
        sp.setCompartment(species.getcompartment());
        sp.setConstant(species.getconstant());
        sp.setInitialAmount(species.getia());
        sp.setInitialConcentration(species.getic());
        sp.setHasOnlySubstanceUnits(species.gethosu());
        if (doc.getModel().getLevel() == 3) sp.setConversionFactor(species.getcf());
        sp.setBoundaryCondition(species.getbc());
        sp.setSubstanceUnits(species.getsu());
        if (!species.getannotation().equals("")) {
          Annotation annot = new Annotation(species.getannotation().toString());
          sp.setAnnotation(annot);
        }
        // doc.getModel().addSpecies(sp) ;
      }
      if (!specieslist.isEmpty()) {
        insertspecies = insertspecies.substring(0, insertspecies.length() - 1);
        insertspecies = insertspecies + ';';
      }

      ArrayList<CompartmentList> complist = sql.getcompartments(modelids.getId());

      if (!complist.isEmpty())
        insertcompartment =
            insertcompartment
                + "\nInsert Into compartment (id, name,constant,model_id,spacialDimensions,size,units) Values";

      for (CompartmentList comp : complist) {
        insertcompartment =
            insertcompartment
                + "(\'"
                + comp.getId()
                + "\',\'"
                + comp.getName()
                + "\',"
                + comp.getconstant()
                + ",\'"
                + modelids.getId()
                + "\',"
                + comp.getspatialdimensions()
                + ","
                + comp.getsize()
                + ","
                + comp.getunits()
                + "\'),";
        Compartment c = doc.getModel().createCompartment(comp.getId());
        c.setName(comp.getName());
        c.setConstant(comp.getconstant());
        c.setSize(comp.getsize());
        c.setSpatialDimensions(comp.getspatialdimensions());
        if (comp.getspatialdimensions() != 0) c.setUnits(comp.getunits());
        // doc.getModel().addSpecies(sp) ;
      }
      if (!complist.isEmpty()) {
        insertcompartment = insertcompartment.substring(0, insertcompartment.length() - 1);
        insertcompartment = insertcompartment + ';';
      }

      ArrayList<functionList> funclist = sql.getfunctions(modelids.getId());

      if (!funclist.isEmpty())
        insertfunction =
            insertfunction + "\nInsert Into functiondefinition (id, xmlns,model_id) Values";

      for (functionList func : funclist) {
        insertfunction =
            insertfunction
                + "(\'"
                + func.getId()
                + "\',\'"
                + func.getxmlns()
                + "\',\'"
                + modelids.getId()
                + "\'),";
        FunctionDefinition fd = doc.getModel().createFunctionDefinition(func.getId());

        try {
          math = ASTNode.parseFormula(func.getxmlns());
          fd.setMath(math);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (!funclist.isEmpty()) {
        insertfunction = insertfunction.substring(0, insertfunction.length() - 1);
        insertfunction = insertfunction + ';';
      }

      ArrayList<unitList> unitlist = sql.getunitlist(modelids.getId());

      if (!unitlist.isEmpty())
        insertunitdef =
            insertunitdef + "\nInsert Into listofunitdefinitions (id,name,model_id) Values";

      for (unitList units : unitlist) {
        insertunitdef =
            insertunitdef
                + "(\'"
                + units.getId()
                + "\',\'"
                + units.getName()
                + "\',\'"
                + modelids.getId()
                + "\'),";

        UnitDefinition ud = doc.getModel().createUnitDefinition(units.getId());
        ud.setName(units.getName());
        ArrayList<unitList> unitdeflist = sql.getunitdef(units.getId());

        if (!unitdeflist.isEmpty())
          insertunits =
              insertunits
                  + "\nInsert Into listofunits (listofunitdefinitions_id,kind, scale,exponent,multiplier) Values";

        for (unitList unitdef : unitdeflist) {
          insertunits =
              insertunits
                  + "(\'"
                  + units.getId()
                  + "\',\'"
                  + unitdef.getkind()
                  + "\',"
                  + unitdef.getscale()
                  + ","
                  + unitdef.getexponent()
                  + ","
                  + unitdef.getmultiplier()
                  + "),";
          Unit u = ud.createUnit(Unit.Kind.valueOf(unitdef.getkind()));
          u.setScale(unitdef.getscale());
          u.setExponent(unitdef.getexponent());
          u.setMultiplier(unitdef.getmultiplier());
        }
        // doc.getModel().addSpecies(sp) ;
        if (!unitdeflist.isEmpty()) {
          insertunits = insertunits.substring(0, insertunits.length() - 1);
          insertunits = insertunits + ';';
        }
      }
      if (!unitlist.isEmpty()) {
        insertunitdef = insertunitdef.substring(0, insertunitdef.length() - 1);
        insertunitdef = insertunitdef + ';';
      }

      ArrayList<reactionList> reactionlist = sql.getreactons(modelids.getId());

      if (!reactionlist.isEmpty())
        insertreaction =
            insertreaction
                + "\nInsert Into reaction (id,name, reversible,fast,model_id,compartment,annotation) Values";

      for (reactionList reaction : reactionlist) {
        insertreaction =
            insertreaction
                + "(\'"
                + reaction.getId()
                + "\',\'"
                + reaction.getName()
                + "\',"
                + reaction.getreversible()
                + ","
                + reaction.getfast()
                + ",\'"
                + modelids.getId()
                + "\',\'"
                + reaction.getcompartment()
                + "\',\'"
                + reaction.getannotation()
                + "\'),";
        Reaction rn = doc.getModel().createReaction(reaction.getId());
        rn.setName(reaction.getName());
        if (doc.getModel().getLevel() == 3) rn.setCompartment(reaction.getcompartment());
        rn.setFast(reaction.getfast());
        rn.setReversible(reaction.getreversible());
        if (!reaction.getannotation().equals("")) {
          Annotation annot = new Annotation(reaction.getannotation().toString());
          rn.setAnnotation(annot);
        }

        ArrayList<reactionList> reactantlist = sql.getreactants(reaction.getId());

        if (!reactantlist.isEmpty())
          insertreactant =
              insertreactant
                  + "\nInsert Into simplespeciesreference (reaction_id,species, sboTerm,stoichiometry,speciestype,constant) Values";
        for (reactionList reactant : reactantlist) {
          insertreactant =
              insertreactant
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + reactant.getspecies()
                  + "\',\'"
                  + reactant.getsboTerm()
                  + "\',"
                  + reactant.getstoichometry()
                  + ","
                  + reactant.getconstant()
                  + ",\'reactants\'),";
          SpeciesReference rt = new SpeciesReference();
          rt.setName(reactant.getspecies());
          rt.setSpecies(reactant.getspecies());
          // rt.setSBOTerm(reactant.getsboTerm());
          rt.setStoichiometry(reactant.getstoichometry());
          //    rt.setConstant(reactant.getconstant());
          rn.addReactant(rt);
        }
        if (!reactantlist.isEmpty()) {
          insertreactant = insertreactant.substring(0, insertreactant.length() - 1);
          insertreactant = insertreactant + ';';
        }

        ArrayList<reactionList> productlist = sql.getproducts(reaction.getId());

        if (!productlist.isEmpty())
          insertproduct =
              insertproduct
                  + "\nInsert Into simplespeciesreference (reaction_id,species, sboTerm,stoichiometry,constant,speciestype) Values";
        for (reactionList product : productlist) {
          insertproduct =
              insertproduct
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + product.getspecies()
                  + "\',\'"
                  + product.getsboTerm()
                  + "\',"
                  + product.getstoichometry()
                  + ","
                  + product.getconstant()
                  + ",\'products\'),";
          SpeciesReference pr = new SpeciesReference();
          pr.setName(product.getspecies());
          pr.setSpecies(product.getspecies());
          //   pr.setSBOTerm(product.getsboTerm());
          pr.setStoichiometry(product.getstoichometry());
          //    pr.setConstant(product.getconstant());
          rn.addProduct(pr);
        }
        if (!productlist.isEmpty()) {
          insertproduct = insertproduct.substring(0, insertproduct.length() - 1);
          insertproduct = insertproduct + ';';
        }

        ArrayList<reactionList> modifierlist = sql.getmodifiers(reaction.getId());

        if (!modifierlist.isEmpty())
          insertmodifier =
              insertmodifier
                  + "\nInsert Into modifierspeciesreference (reaction_id,species, sboTerm,speciestype) Values";
        for (reactionList modifier : modifierlist) {
          insertmodifier =
              insertmodifier
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + modifier.getspecies()
                  + "\',\'"
                  + modifier.getsboTerm()
                  + "\',\'modifiers\'),";
          ModifierSpeciesReference m = new ModifierSpeciesReference();
          m.setName(modifier.getspecies());
          m.setSpecies(modifier.getspecies());
          //    m.setSBOTerm(modifier.getsboTerm());
          rn.addModifier(m);
        }
        if (!modifierlist.isEmpty()) {
          insertmodifier = insertmodifier.substring(0, insertmodifier.length() - 1);
          insertmodifier = insertmodifier + ';';
        }

        ArrayList<reactionList> klawlist = sql.getkineticlaws(reaction.getId());

        if (!klawlist.isEmpty())
          insertklaw =
              insertklaw + "\nInsert Into kineticlaw (reaction_id,kid, math,annotation) Values";
        for (reactionList klaw : klawlist) {
          insertklaw =
              insertklaw
                  + "(\'"
                  + reaction.getId()
                  + "\',\'"
                  + klaw.getId()
                  + "\',\'"
                  + klaw.getmath()
                  + "\',\'"
                  + klaw.getannotation()
                  + "\'),";
          KineticLaw kl = rn.createKineticLaw();
          try {
            math = ASTNode.parseFormula(klaw.getmath());
            kl.setMath(math);
            if (!klaw.getannotation().equals("")) {
              Annotation annot = new Annotation(klaw.getannotation().toString());
              kl.setAnnotation(annot);
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!klawlist.isEmpty()) {
          insertklaw = insertklaw.substring(0, insertklaw.length() - 1);
          insertklaw = insertklaw + ';';
        }
      }
      if (!reactionlist.isEmpty()) {
        insertreaction = insertreaction.substring(0, insertreaction.length() - 1);
        insertreaction = insertreaction + ';';
      }

      ArrayList<parameterList> paralist = sql.getparameters(modelids.getId());

      if (!paralist.isEmpty())
        insertparameter =
            insertparameter
                + "\nInsert Into parameter (id,name,value,units,constant,model_id) Values";

      for (parameterList para : paralist) {
        insertparameter =
            insertparameter
                + "(\'"
                + para.getId()
                + "\',\'"
                + para.getName()
                + "\',"
                + para.getvalue()
                + ","
                + para.getunits()
                + ","
                + para.getconstant()
                + ",\'"
                + modelids.getId()
                + "\'),";
        Parameter par = doc.getModel().createParameter(para.getId());
        par.setName(para.getId());
        par.setConstant(para.getconstant());
        par.setUnits(para.getunits());
        par.setValue(para.getvalue());
      }
      if (!paralist.isEmpty()) {
        insertparameter = insertparameter.substring(0, insertparameter.length() - 1);
        insertparameter = insertparameter + ';';
      }

      ArrayList<constraintList> conslist = sql.getconstraints(modelids.getId());

      if (!conslist.isEmpty())
        insertconstraint =
            insertconstraint + "\nInsert Into sbmlconstraint (math,message,model_id) Values";

      for (constraintList constraint : conslist) {
        insertconstraint =
            insertconstraint
                + "(\'"
                + constraint.getmath()
                + "\',\'"
                + constraint.getmessage()
                + "\',\'"
                + modelids.getId()
                + "\'),";
        Constraint cons = doc.getModel().createConstraint();
        try {
          math = ASTNode.parseFormula(constraint.getmath());
          cons.setMath(math);
          cons.setMessage(constraint.getmessage());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      if (!conslist.isEmpty()) {
        insertconstraint = insertconstraint.substring(0, insertconstraint.length() - 1);
        insertconstraint = insertconstraint + ';';
      }

      ArrayList<eventsList> eventlist = sql.getevents(modelids.getId());

      if (!eventlist.isEmpty())
        insertevent =
            insertevent + "\nInsert Into event (id,name,UseValuesFromTriggerTime,model_id) Values";

      for (eventsList events : eventlist) {
        insertevent =
            insertevent
                + "(\'"
                + events.getId()
                + "\',\'"
                + events.getName()
                + "\',"
                + events.getuservalues()
                + ",\'"
                + modelids.getId()
                + "\'),";
        Event ev = doc.getModel().createEvent(events.getId());
        ev.setName(events.getName());
        // ev.setUseValuesFromTriggerTime(events.getuservalues());

        ArrayList<eventsList> triggerlist = sql.gettriggers(events.getId());

        if (!triggerlist.isEmpty())
          inserttrigger =
              inserttrigger
                  + "\nInsert Into sbmltrigger (event_id,initialvalue,persisent,math) Values";
        for (eventsList triggers : triggerlist) {
          Trigger tr = doc.getModel().createTrigger();
          try {
            math = ASTNode.parseFormula(triggers.getmath());
            tr.setMath(math);
            tr.setInitialValue(triggers.getinitialval());
            tr.setPersistent(triggers.getpersistent());
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!triggerlist.isEmpty()) {
          inserttrigger = inserttrigger.substring(0, insertmodel.length() - 1);
          inserttrigger = inserttrigger + ';';
        }

        ArrayList<eventsList> delaylist = sql.getdelays(events.getId());

        if (!delaylist.isEmpty())
          insertdelay = insertdelay + "\nInsert Into delay (event_id,math) Values";
        for (eventsList delays : delaylist) {
          Delay d = doc.getModel().createDelay();
          try {
            math = ASTNode.parseFormula(delays.getmath());
            d.setMath(math);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!delaylist.isEmpty()) {
          insertdelay = insertdelay.substring(0, insertdelay.length() - 1);
          insertdelay = insertdelay + ';';
        }

        ArrayList<eventsList> evasslist = sql.geteventassignments(events.getId());

        if (!evasslist.isEmpty())
          inserteventassign =
              inserteventassign + "\nInsert Into eventassignment (event_id,variable,math) Values";
        for (eventsList evassign : evasslist) {
          EventAssignment ea = doc.getModel().createEventAssignment();
          try {
            math = ASTNode.parseFormula(evassign.getmath());
            ea.setMath(math);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        if (!evasslist.isEmpty()) {
          inserteventassign = inserteventassign.substring(0, inserteventassign.length() - 1);
          inserteventassign = inserteventassign + ';';
        }
      }
      if (!eventlist.isEmpty()) {
        insertevent = insertevent.substring(0, insertevent.length() - 1);
        insertevent = insertevent + ';';
      }

      ArrayList<ruleslist> rulelist = sql.getrules(modelids.getId());

      if (!rulelist.isEmpty())
        insertrules = insertrules + "\nInsert Into rules (id,math,ruletype,model_id) Values";
      for (ruleslist rules : rulelist) {
        insertrules =
            insertrules
                + "(\'"
                + rules.getId()
                + "\',\'"
                + rules.getmath()
                + "\',\'"
                + rules.getruletype()
                + "\',\'"
                + modelids.getId()
                + "\'),";
        if (rules.getruletype().equals("assignmentrule")) {
          Rule r = doc.getModel().createAssignmentRule();
          r.setMetaId(rules.getId());
          try {
            math = ASTNode.parseFormula(rules.getmath());
            r.setMath(math);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
      if (!rulelist.isEmpty()) {
        insertrules = insertrules.substring(0, insertrules.length() - 1);
        insertrules = insertrules + ';';
      }

      SBMLWriter writer = new SBMLWriter();
      try {
        String Path = filepath + modelids.getId() + ".xml";
        writer.write(doc, Path);

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(Path);
        Element root = document.getDocumentElement();
        Element newdataset = document.createElement("dataset");
        root.appendChild(newdataset);

        ArrayList<dataset> datasetlist = sql.getdataset(modelids.getId());
        for (dataset ds : datasetlist) {
          // System.out.println(ds.getexpcond());

          Element name = document.createElement("experimentalcondition");
          name.setAttribute("bioelement", ds.getbioel());
          name.setAttribute("name", ds.getName());
          name.setAttribute("descr", ds.getdescr());
          name.setAttribute("expcond", ds.getexpcond());
          name.setAttribute("value", String.valueOf(ds.getvalue()));
          name.setAttribute("type", ds.gettype());
          name.setAttribute("uri", ds.geturi());
          newdataset.appendChild(name);
        }

        root.appendChild(newdataset);
        DOMSource source = new DOMSource(document);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        StreamResult result = new StreamResult(filepath + modelids.getId() + "d.xml");
        transformer.transform(source, result);
        System.out.println(
            "Files : "
                + modelids.getId()
                + ".xml and "
                + modelids.getId()
                + "d.xml have been generated successfully !!!");

      } catch (Exception e) {
        e.printStackTrace();
      }

      insertstatement =
          insertstatement
              + "\n\n"
              + insertmodel
              + "\n"
              + insertspecies
              + "\n"
              + insertcompartment
              + "\n"
              + insertfunction;
      insertstatement =
          insertstatement
              + "\n"
              + insertparameter
              + "\n"
              + insertreaction
              + "\n"
              + insertreactant
              + "\n"
              + insertproduct;
      insertstatement =
          insertstatement
              + "\n"
              + insertmodifier
              + "\n"
              + insertklaw
              + "\n"
              + insertunitdef
              + "\n"
              + insertunits;
      insertstatement =
          insertstatement
              + "\n"
              + insertrules
              + "\n"
              + insertconstraint
              + "\n"
              + insertevent
              + "\n"
              + inserttrigger
              + "\n"
              + insertdelay
              + "\n"
              + inserteventassign;

      insertcompartment = "";
      insertmodel = "";
      insertspecies = "";

      // System.out.println("document : " + doc);
    }
    insertstatement = insertstatement + "\nUNLOCK TABLES;";
    Filedata = Filedata + "\n\n\n" + insertstatement;

    try {
      wrtireStringToFile(Filedata, filepath + "sbmldb.sql");
    } catch (IOException e) {
      e.printStackTrace();
    }
    // System.out.println(insertstatement);
  }
Пример #20
0
  public String toXMLString() {
    Document doc;
    try { // Create an Empty Dom
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      doc = builder.newDocument();
    } catch (ParserConfigurationException e) {
      System.err.println("error when create empty Dom: " + e);
      return null;
    }

    if (doc == null) {
      System.err.println("null dom");
      return null;
    }

    try {
      Element root = doc.createElement("PathwayLayout");
      doc.appendChild(root);

      Element nodeslayout = doc.createElement("Nodes");
      root.appendChild(nodeslayout);
      Element edgeslayout = doc.createElement("Edges");
      root.appendChild(edgeslayout);

      for (NodeLayout nl : nodes) {
        Element ne = doc.createElement("NodeLayout");
        ne.setAttribute("ID", nl.nodeID);
        ne.setAttribute("NeighboringProcessId", nl.processID);
        String co = "false";
        if (nl.cofactor.equalsIgnoreCase("true")) {
          co = "true";
        }
        ne.setAttribute("cofactor", co);
        ne.setAttribute("X", Double.toString(nl.x));
        ne.setAttribute("Y", Double.toString(nl.y));
        nodeslayout.appendChild(ne);
      }

      for (EdgeLayout el : edges) {
        Element ee = doc.createElement("EdgeLayout");
        ee.setAttribute("SourceID", el.sourceNode);
        ee.setAttribute("SourceNeighboringProcessId", el.sourcepid);
        String sco = "false";
        if (el.scofactor.equalsIgnoreCase("true")) {
          sco = "true";
        }
        ee.setAttribute("SourceCofactor", sco);

        ee.setAttribute("TargetID", el.targetNode);
        ee.setAttribute("TargetNeighboringProcessId", el.targetpid);
        String tco = "false";
        if (el.tcofactor.equalsIgnoreCase("true")) {
          sco = "true";
        }
        ee.setAttribute("TargetCofactor", tco);

        for (LayoutPoint lp : el.bends) {
          Element lpe = doc.createElement("BendPoint");
          lpe.setAttribute("X", Double.toString(lp.x));
          lpe.setAttribute("Y", Double.toString(lp.y));
          ee.appendChild(lpe);
        }

        edgeslayout.appendChild(ee);
      }

      // Transform Dom to XML String
      Transformer transformer = TransformerFactory.newInstance().newTransformer();

      // additional whitespace when outputting the result tree
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");

      StreamResult result = new StreamResult(new StringWriter());
      DOMSource source = new DOMSource(doc);
      transformer.transform(source, result);

      String xmlString = result.getWriter().toString();
      return xmlString;
    } catch (Exception e) {
      System.err.println("error when fill the Dom: " + e);
      return null;
    }
  }