Ejemplo n.º 1
0
  public static void parse(InputStream is, XmlTagHandler tag, EntityResolver resolver)
      throws XmlParseException {
    SAXBuilder builder;
    Document doc;

    builder = new SAXBuilder();

    if (resolver != null) {
      builder.setEntityResolver(resolver);
    }

    try {
      if (resolver != null) {
        // WTF?  seems relative entity URIs are allowed
        // by certain xerces impls.  but fully qualified
        // file://... URLs trigger a NullPointerException
        // in others.  setting base here worksaround
        doc = builder.build(is, "");
      } else {
        doc = builder.build(is);
      }
    } catch (JDOMException exc) {
      XmlParseException toThrow = new XmlParseException(exc.getMessage());
      toThrow.initCause(exc);
      throw toThrow;
    } catch (IOException exc) {
      XmlParseException toThrow = new XmlParseException(exc.getMessage());
      toThrow.initCause(exc);
      throw toThrow;
    }

    generalParse(tag, doc);
  }
Ejemplo n.º 2
0
  public ParseDoc(Object xmlFile, String rootId, TreeMap prevIdMap) {

    SAXBuilder saxBuilder = new SAXBuilder();

    try {
      if (xmlFile instanceof String) {
        document = saxBuilder.build((String) xmlFile);
      } else if (xmlFile instanceof URL) {
        document = saxBuilder.build((URL) xmlFile);
      }
      root = ParseUtils.parseRoot(document, rootId);
      objects = new TreeMap();

      // Build description string (but not for the snippets.xml file)
      if (xmlFile instanceof String) {
        List authorL = root.getChildren("author");
        String author = "<unknown>";
        if (root.getAttributeValue("name") != null) {
          author = root.getAttributeValue("name");
        } else if (authorL.size() > 0) {
          author = ((Element) authorL.get(0)).getValue();
        }
        String description =
            "from file "
                + xmlFile.toString()
                + " (author: "
                + author
                + ") on "
                + new Date().toString();
        HasIdentifiers.addGlobalIdentifier("_description_", description);
      }

      // Get all macro definitions, and remove them from document
      TreeMap macroMap = ParseUtils.getMacroDefs(root);

      // Process all macro expansions; replace macro expansion request with result
      ParseUtils.expandMacros(root, macroMap);

      // Get all elements in document, and assign identifiers to them;
      idMap = ParseUtils.parseId(root, prevIdMap);

      // Rewriting done; output debug XML code
      if (root.getAttributeValue("debug") != null) {
        XMLOutputter outputter = new XMLOutputter();
        FileOutputStream fos = new FileOutputStream(xmlFile + ".debug");
        outputter.output(document, fos);
        fos.close();
      }

    } catch (JDOMException e) { // indicates a well-formedness or other error

      throw new Error("JDOMException: " + e.getMessage());

    } catch (IOException e) { // indicates an IO problem

      throw new Error("IOException: " + e.getMessage());
    }
  }
Ejemplo n.º 3
0
  public void testPie1() {
    try {

      String url = baseURL + "/rest/Pie/search;id=*/utensilCollection";

      WebClient client = WebClient.create(url);
      client.type("application/xml").accept("application/xml");
      Response response = client.get();

      if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) {
        InputStream is = (InputStream) response.getEntity();
        org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
        org.jdom.Document jDoc = builder.build(is);
        assertEquals(jDoc.getRootElement().getName(), "response");
      } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
        InputStream is = (InputStream) response.getEntity();
        org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
        org.jdom.Document jDoc = builder.build(is);
        assertEquals(jDoc.getRootElement().getName(), "response");
      } else if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
      }

      File myFile = new File("Pie_Search" + "XML.xml");
      System.out.println("writing data to file " + myFile.getAbsolutePath());
      FileWriter myWriter = new FileWriter(myFile);

      BufferedReader br =
          new BufferedReader(new InputStreamReader(((InputStream) response.getEntity())));

      String output;
      System.out.println("Output from Server .... \n");
      while ((output = br.readLine()) != null) {
        myWriter.write(output);
        System.out.println(output);
      }

      myWriter.flush();
      myWriter.close();

    } catch (Exception e) {
      e.printStackTrace();
      ResponseBuilder builder = Response.status(Status.INTERNAL_SERVER_ERROR);
      builder.type("application/xml");
      StringBuffer buffer = new StringBuffer();
      buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
      buffer.append("<response>");
      buffer.append("<type>ERROR</type>");
      buffer.append("<code>INTERNAL_ERROR_4</code>");
      buffer.append("<message>Failed to Query due to: " + e.getMessage() + "</message>");
      buffer.append("</response>");
      builder.entity(buffer.toString());
      throw new WebApplicationException(builder.build());
    }
  }
  public void loadTestProfiles() throws IOException, JDOMException {
    SAXBuilder parser = new SAXBuilder();

    // load constraint profile.
    Document doc1 = parser.build(new File(traceDir + "SigConstProfile.xml"));
    for (Object o : doc1.getContent()) {
      Element root = (Element) o;
      if (!root.getName().equals("SigConstProfile")) continue;
      for (Object s : root.getContent()) { // for each SQL signature.
        if (!(s instanceof Element)) continue;
        Element sigConstElement = (Element) s;
        if (!sigConstElement.getName().equals("Signature")) continue;
        String sig = sigConstElement.getAttributeValue("Sig");
        SigProfile profile = new SigProfile(sig);
        profile.procXMLSigConstProfileElement(sigConstElement);
        testProfiles.put(sig, profile);
      }
    }
    // load trace summary.
    Document doc2 = parser.build(new File(traceDir + "TraceSummary.xml"));
    for (Object o : doc2.getContent()) {
      Element root = (Element) o;
      if (!root.getName().equals("TraceSummary")) continue;
      for (Object s : root.getContent()) { // for each SQL signature.
        if (!(s instanceof Element)) continue;
        Element summary = (Element) s;
        if (!summary.getName().equals("Signature")) continue;
        String sig = summary.getAttributeValue("Sig");
        SigProfile profile = testProfiles.get(sig);
        profile.procXMLTraceSumElement(summary);
      }
    }
    // prepare sessionVars set.
    for (String sig : testProfiles.keySet()) {
      for (String entry : testProfiles.get(sig).getEntries().keySet()) {
        // System.out.println(sig + " " + entry);
        Vector<RequestMessage> messageList = testProfiles.get(sig).getMessagesByEntry(entry);
        // System.out.println(messageList.size());
        for (RequestMessage message : messageList) {
          String stateSig = _stateConstructor.genStateSig(message.getSessionVars());
          if (!sessionVarsSet.containsKey(stateSig)) {
            if (!_stateConstructor.getStateSet().contains(stateSig)) {
              continue;
            }
            System.out.println("Loading state: " + stateSig);
            sessionVarsSet.put(stateSig, new HashSet<String>());
          }
          sessionVarsSet.get(stateSig).add(message.getSessionVars());
        }
      }
    }
  }
Ejemplo n.º 5
0
  private boolean deploy(File f) {
    try {
      if (log != null) log.info("deploy:" + f.getCanonicalPath());
      QEntry qentry = (QEntry) dirMap.get(f);
      SAXBuilder builder = createSAXBuilder();
      Document doc;
      if (decorator != null && !f.getName().equals(LOGGER_CONFIG)) {
        doc = decrypt(builder.build(new StringReader(decorator.decorateFile(f))));
      } else {
        doc = decrypt(builder.build(f));
      }

      Element rootElement = doc.getRootElement();
      String iuuid = rootElement.getAttributeValue("instance");
      if (iuuid != null) {
        UUID uuid = UUID.fromString(iuuid);
        if (!uuid.equals(getInstanceId())) {
          deleteFile(f, iuuid);
          return false;
        }
      }
      Object obj = factory.instantiate(this, rootElement);
      qentry.setObject(obj);

      ObjectInstance instance = factory.createQBean(this, doc.getRootElement(), obj);
      qentry.setInstance(instance);
    } catch (InstanceAlreadyExistsException e) {
      /*
       * Ok, the file we tried to deploy, holds an object
       *  that already has been deployed.
       *
       * Rename it out of the way.
       *
       */
      tidyFileAway(f, DUPLICATE_EXTENSION);
      getLog().warn("deploy", e);
      return false;
    } catch (Exception e) {
      getLog().warn("deploy", e);
      tidyFileAway(f, ERROR_EXTENSION);
      // This will also save deploy error repeats...
      return false;
    } catch (Error e) {
      getLog().warn("deploy", e);
      tidyFileAway(f, ENV_EXTENSION);
      // This will also save deploy error repeats...
      return false;
    }
    return true;
  }
Ejemplo n.º 6
0
  /**
   * Processes the messages from the server
   *
   * @param message
   */
  private synchronized void processServerMessage(String message) {
    SAXBuilder builder = new SAXBuilder();
    String what = new String();
    Document doc = null;

    try {
      doc = builder.build(new StringReader(message));
      Element root = doc.getRootElement();
      List childs = root.getChildren();
      Iterator i = childs.iterator();
      what = ((Element) i.next()).getName();
    } catch (Exception e) {
    }

    if (what.equalsIgnoreCase("LOGIN") == true) _login(doc);
    else if (what.equalsIgnoreCase("LOGOUT") == true) _logout(doc);
    else if (what.equalsIgnoreCase("MESSAGE") == true) _message(doc);
    else if (what.equalsIgnoreCase("WALL") == true) _wall(doc);
    else if (what.equalsIgnoreCase("CREATEGROUP") == true) _creategroup(doc);
    else if (what.equalsIgnoreCase("JOINGROUP") == true) _joingroup(doc);
    else if (what.equalsIgnoreCase("PARTGROUP") == true) _partgroup(doc);
    else if (what.equalsIgnoreCase("GROUPMESSAGE") == true) _groupmessage(doc);
    else if (what.equalsIgnoreCase("KICK") == true) _kick(doc);
    else if (what.equalsIgnoreCase("LISTUSER") == true) _listuser(doc);
    else if (what.equalsIgnoreCase("LISTGROUP") == true) _listgroup(doc);
  }
Ejemplo n.º 7
0
 @SuppressWarnings("unchecked")
 @Override
 public String inportFlowbase(String flowBaseXml) {
   ByteArrayInputStream bais;
   try {
     bais = new ByteArrayInputStream(flowBaseXml.getBytes("UTF-8"));
     SAXBuilder saxBuilder = new SAXBuilder();
     Document doc = saxBuilder.build(bais);
     Element root = doc.getRootElement();
     Flowbase flowbase = XmlUtil.getBeanByElement(root, Flowbase.class);
     flowbase.setFlowName(flowbase.getFlowName() + "-副本");
     this.flowbaseDao.save(flowbase);
     List<Element> nodeList = root.getChildren("flownode");
     this.flownodeService.importFlowNode(flowbase.getId(), nodeList);
     // TODO 未完成
     return flowbase.getId();
   } catch (UnsupportedEncodingException e) {
     log.error(
         this.getClass().getSimpleName() + " e==> inportFlowbase,UnsupportedEncodingException", e);
     throw new BpmException("bpm003", "导入流程失败");
   } catch (JDOMException e) {
     log.error(this.getClass().getSimpleName() + " e==> inportFlowbase,JDOMException", e);
     throw new BpmException("bpm003", "导入流程失败");
   } catch (IOException e) {
     log.error(this.getClass().getSimpleName() + " e==> inportFlowbase,IOException", e);
     throw new BpmException("bpm003", "导入流程失败");
   }
 }
Ejemplo n.º 8
0
  public UserEntrySet(InputStream stream, String urlPrefix)
      throws JDOMException, IOException, UnexpectedRootElementException {
    SAXBuilder sb = new SAXBuilder();
    Document d = sb.build(stream);

    populate(d, urlPrefix);
  }
Ejemplo n.º 9
0
  private SBOLRootObject createDnaComponent(String xml, SBOLDocument document) {
    SAXBuilder builder = new SAXBuilder();
    DnaComponent dnaComponent = SBOLFactory.createDnaComponent();
    try {
      Document doc = builder.build(new File(xml));
      Element rootEl = doc.getRootElement();

      Element list = rootEl.getChild("part_list").getChild("part");
      partId = Integer.parseInt(list.getChildText("part_id"));
      dnaComponent.setURI(URI.create(list.getChildText("part_url")));
      dnaComponent.setDisplayId(list.getChildText("part_name"));
      dnaComponent.setName(list.getChildText("part_short_name"));
      dnaComponent.setDescription(list.getChildText("part_short_desc"));
      Element seq = rootEl.getChild("part_list").getChild("part").getChild("sequences");

      dnaComponent.setDnaSequence(this.createDnaSequence(seq.getChildText("seq_data")));
      List<SequenceAnnotation> seqs = createAllDnaSubComponent(xml);
      System.out.println(seqs.size());
      for (int i = 0; i < seqs.size(); i++) dnaComponent.addAnnotation(seqs.get(i));

    } catch (JDOMException e) {
      //            e.printStackTrace();

    } catch (IOException e) {
      //            e.printStackTrace();
    }
    return dnaComponent;
  }
  private void parseConfigFile(File configFile) throws IOException, JDOMException {
    /* check for valid xml */
    if (XMLValidityChecker.validateXML(configFile.getAbsolutePath())) {

      SAXBuilder saxBuilder = new SAXBuilder();
      Document document = saxBuilder.build(configFile);
      Element rootElement = document.getRootElement();

      hasGoldGroup = false;

      Iterator childrenIterator = rootElement.getChildren().iterator();

      while (childrenIterator.hasNext()) {
        Element childElement = (Element) childrenIterator.next();
        if (childElement.getName().equals(ANNOTATION_GROUP_TAG)) {
          processAnnotationGroupElement(childElement);
        } else if (childElement.getName().equals(COMPARISON_GROUP_TAG)) {
          processComparisonGroupElement(childElement);
        } else {
          logger.warn(
              "Unexpected element encountered while parsing the comparison configuration file: "
                  + childElement.getName());
        }
      }

    } else {
      logger.error(
          "Comparison configuration file is not well-formed XML. Please fix and try again.");
    }
  }
Ejemplo n.º 11
0
  @Parameters
  public static Collection<FitsOutput[]> data() throws Exception {
    Fits fits = new Fits("");
    SAXBuilder builder = new SAXBuilder();
    //		List<FitsOutput[]> inputs = new ArrayList<String[][]>();
    List<FitsOutput[]> inputs = new ArrayList<FitsOutput[]>();

    File inputDir = new File("tests/input");
    File outputDir = new File("tests/output");

    for (File input : inputDir.listFiles()) {
      // skip directories
      if (input.isDirectory()) {
        continue;
      }
      FitsOutput fitsOut = fits.examine(input);

      File outputFile = new File(outputDir + File.separator + input.getName() + ".xml");
      if (!outputFile.exists()) {
        System.err.println("Not Found: " + outputFile.getPath());
        continue;
      }
      Document expectedXml = builder.build(new FileInputStream(outputFile));
      FitsOutput expectedFits = new FitsOutput(expectedXml);

      FitsOutput[][] tmp = new FitsOutput[][] {{expectedFits, fitsOut}};
      inputs.add(tmp[0]);
    }
    return inputs;
  }
Ejemplo n.º 12
0
  public String SqlExcute(String xmlStr) {
    String outstr = "false";
    Document doc;
    Element rootNode;
    String intStr = Basic.decode(xmlStr);

    try {
      Reader reader = new StringReader(intStr);
      SAXBuilder ss = new SAXBuilder();
      doc = ss.build(reader);

      rootNode = doc.getRootElement();

      List list = rootNode.getChildren();

      DBTable datatable = new DBTable();

      for (int i = 0; i < list.size(); i++) {
        Element childRoot = (Element) list.get(i);
        // System.out.print(childRoot.getText());
        outstr = String.valueOf(datatable.SaveDateStr(childRoot.getText()));
      }

    } catch (JDOMException ex) {
      System.out.print(ex.getMessage());
    }
    return outstr;
  }
Ejemplo n.º 13
0
 @Override
 public void processExistingResource(
     HttpManager manager, Request request, Response response, Resource resource)
     throws NotAuthorizedException, BadRequestException, ConflictException {
   try {
     org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder();
     // Prevent possibily of malicious clients using remote the parser to load remote resources
     builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
     org.jdom.Document doc = builder.build(request.getInputStream());
     String reportName = doc.getRootElement().getName();
     Report r = reports.get(reportName);
     if (r == null) {
       log.error("report not known: " + reportName);
       throw new BadRequestException(resource);
     } else {
       log.info("process report: " + reportName + " with : " + r.getClass());
       String xml = r.process(request.getHostHeader(), request.getAbsolutePath(), resource, doc);
       if (log.isTraceEnabled()) {
         log.trace("Report XML:\n" + xml);
       }
       response.setStatus(Response.Status.SC_MULTI_STATUS);
       response.setContentTypeHeader("text/xml");
       response.setEntity(new ByteArrayEntity(xml.getBytes("UTF-8")));
     }
   } catch (JDOMException ex) {
     java.util.logging.Logger.getLogger(ReportHandler.class.getName()).log(Level.SEVERE, null, ex);
   } catch (ReadingException ex) {
     throw new RuntimeException(ex);
   } catch (WritingException ex) {
     throw new RuntimeException(ex);
   } catch (IOException ex) {
     throw new RuntimeException(ex);
   }
 }
Ejemplo n.º 14
0
  void loadTemplates(InputStream inputStream, final String templateName) {
    final SAXBuilder parser = new SAXBuilder();
    try {

      TemplateSettings templateSettings = TemplateSettings.getInstance();
      Document doc = parser.build(inputStream);
      Element root = doc.getRootElement();
      for (Object element : root.getChildren()) {
        if (element instanceof Element) {
          final Template template = readExternal((Element) element, templateName);
          final String key = template.getKey();
          if (key != null) {
            TemplateImpl existingTemplate = templateSettings.getTemplate(key, TemplateGroupName);
            if (existingTemplate == null) {
              templateSettings.addTemplate(template);
            } else if (TemplateGroupName.equals(existingTemplate.getGroupName())) {
              // Update only add if template is in the AribaWeb group
              templateSettings.removeTemplate(existingTemplate);
              templateSettings.addTemplate(template);
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 15
0
  private void readFile(String fileName) throws JDOMException, IOException {
    String absolutePath = getAbsolutePath(fileName);
    File xmlFile = new File(absolutePath);

    SAXBuilder builder = new SAXBuilder();
    this.doc = builder.build(xmlFile);
  }
  /**
   * Shortcut for reading an Xml document
   *
   * @param path
   * @return the document, or null if the file doesn't exist yet
   * @throws org.jdom.JDOMException
   * @throws java.io.IOException
   */
  public static Document readDocument(String path) throws JDOMException, IOException {

    File f = new File(path);
    SAXBuilder sxb = new SAXBuilder();
    Document jDomDocument = sxb.build(f);
    return jDomDocument;
  }
Ejemplo n.º 17
0
  /**
   * Loads an xml file from a URL after posting content to the URL.
   *
   * @param url
   * @param xmlQuery
   * @return
   * @throws IOException
   * @throws JDOMException
   */
  public static Element loadFile(URL url, Element xmlQuery) throws IOException, JDOMException {
    Element result = null;
    try {
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", "application/xml");
      connection.setRequestProperty(
          "Content-Length",
          "" + Integer.toString(getString(xmlQuery).getBytes(Jeeves.ENCODING).length));
      connection.setRequestProperty("Content-Language", "en-US");
      connection.setDoOutput(true);
      PrintStream out = new PrintStream(connection.getOutputStream(), true, Jeeves.ENCODING);
      out.print(getString(xmlQuery));
      out.close();

      SAXBuilder builder = getSAXBuilderWithoutXMLResolver(false); // new SAXBuilder();
      Document jdoc = builder.build(connection.getInputStream());

      result = (Element) jdoc.getRootElement().detach();
    } catch (Exception e) {
      Log.error(Log.ENGINE, "Error loading URL " + url.getPath() + " .Threw exception " + e);
      e.printStackTrace();
    }
    return result;
  }
Ejemplo n.º 18
0
  static {
    SAXBuilder builder = new SAXBuilder();
    languageCode = prefs.get("uiLanguage", "deu");

    java.net.URL lfURL = new ResourceHandler().languageFileURL();

    try {
      Document doc = builder.build(lfURL);
      Element root = doc.getRootElement();
      List allElements = root.getChild("uiItems").getChildren();
      Iterator iterator = allElements.iterator();
      while (iterator.hasNext()) {
        Element myElement = (Element) iterator.next();
        if (myElement.getName() == "uiItem"
            && myElement.getAttributeValue("name") != null
            && myElement.getAttributeValue("value") != null
            && myElement.getAttributeValue("lang").equals(languageCode)) {
          UiElements.put(myElement.getAttributeValue("name"), myElement.getAttributeValue("value"));
        } else {
          //					System.err.println("uiElement in Languagefile invalid!");
        }
      }

    } catch (JDOMException e) {
      System.err.println("Languagefile invalid!");
      e.printStackTrace();
    } catch (IOException e) {
      System.err.println("Languagefile missing!");
    }
  }
Ejemplo n.º 19
0
  public void cargarConfiguracion() throws ConfiguracionException {

    try {
      SAXBuilder builder = new SAXBuilder();
      File xmlFile = new File(this.getPathConfig());
      Document document = (Document) builder.build(xmlFile);
      Element rootNode = document.getRootElement();
      this.setHoraUnificador(Integer.valueOf(rootNode.getChildText("horaUnificador")));
      this.setMinutoUnificador(Integer.valueOf(rootNode.getChildText("minutoUnificador")));
      this.setManianaOTardeUnificador(rootNode.getChildText("manianaOTardeUnificador"));

      this.setSmtp(rootNode.getChildText("smtp"));
      this.setPuerto(rootNode.getChildText("puerto"));
      this.setDesdeMail(rootNode.getChildText("desde"));
      this.setTLS(Boolean.valueOf(rootNode.getChildText("tls")));
      this.setAuth(Boolean.valueOf(rootNode.getChildText("auth")));
      this.setUser(rootNode.getChildText("user"));
      this.setPassword(rootNode.getChildText("password"));

      this.setIpBD(rootNode.getChildText("ipBD"));
      this.setPortBD(rootNode.getChildText("portBD"));

      this.setPathTempImages(rootNode.getChildText("pathTempImages"));
      this.setPathExportDesign(rootNode.getChildText("pathExportDesign"));
      this.setPathConfig(rootNode.getChildText("pathConfig"));
      this.setPathDownloadApp(rootNode.getChildText("pathDownloadApp"));
      this.setKeyGoogleMap(rootNode.getChildText("keyGoogleMap"));

    } catch (Exception e) {
      LogFwk.getInstance(Configuracion.class)
          .error("Error al leer el archivo de configuracion. Detalle: " + e.getMessage());
      throw new ConfiguracionException(
          "Error al leer el archivo de configuracion. Detalle: " + e.getMessage());
    }
  }
Ejemplo n.º 20
0
  private void loadData(File path) {
    if (path.isDirectory()) {
      File[] dataFiles = path.listFiles(new XMLFilter());
      SAXBuilder builder = new SAXBuilder();
      GeneratorDtdResolver resolver = new GeneratorDtdResolver(path);
      builder.setEntityResolver(resolver);

      for (int i = 0; i < dataFiles.length; i++) {
        try {
          URL url = dataFiles[i].toURI().toURL();
          Document nameSet = builder.build(url);
          DocType dt = nameSet.getDocType();

          if (dt.getElementName().equals("GENERATOR")) {
            loadFromDocument(nameSet);
          }

          nameSet = null;
          dt = null;
        } catch (Exception e) {
          Logging.errorPrint(e.getMessage(), e);
          JOptionPane.showMessageDialog(this, "XML Error with file " + dataFiles[i].getName());
        }
      }

      loadDropdowns();
    } else {
      JOptionPane.showMessageDialog(this, "No data files in directory " + path.getPath());
    }
  }
Ejemplo n.º 21
0
  public DataSource createDataSource() {

    SAXBuilder sb = new SAXBuilder();
    DataSource dataSource = null;
    try {
      Document xmlDoc = sb.build("config/data.xml");
      Element root = xmlDoc.getRootElement();
      Element url = root.getChild("url");

      dataSource = new DataSource();
      dataSource.setHost(url.getText());
      dataSource.setDbName(root.getChild("database").getText());
      dataSource.setDriverClass(root.getChildText("driver-class"));
      dataSource.setPort(root.getChildText("port"));
      dataSource.setUserLogin(root.getChildText("login"));
      dataSource.setUserPwd(root.getChildText("password"));

    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return dataSource;
  }
Ejemplo n.º 22
0
  public XMIVersionExtractor(File xmlFile) {
    try {
      SAXBuilder builder = new SAXBuilder();
      Document doc = builder.build(xmlFile);

      Element root = doc.getRootElement();
      if (root.getName().equals("XMI")) {
        String version = null;
        version = root.getAttributeValue("xmi.version");
        if (version != null) {
          this.version = version;
        } else {
          version = root.getAttributeValue("version", root.getNamespace());
          if (version != null) this.version = version;
        }
      } else {
        Element xmiRoot = root.getChild("XMI");
        if (xmiRoot != null) {
          String version = null;
          version = xmiRoot.getAttributeValue("xmi.version");
          if (version != null) {
            this.version = version;
          } else {
            version = xmiRoot.getAttributeValue("version", xmiRoot.getNamespace());
            if (version != null) this.version = version;
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JDOMException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 23
0
 public void createMessageFiles(String modelFileName) {
   try {
     System.out.println(modelFileName);
     msgs = new HashMap<String, MessageObject>();
     fields = new HashMap<String, List<FieldObject>>();
     String configFilePath = GeneratorHelper.getBuildPath(MODEL_DIC + modelFileName);
     SAXBuilder builder = new SAXBuilder();
     Document doc = builder.build(configFilePath);
     Element root = doc.getRootElement();
     String module = root.getAttributeValue("module"); // 所属模块
     List messages = root.getChildren("message", NAME_SPACE); // 消息体定义
     List constants = null;
     Element constantsElement = root.getChild("constants", NAME_SPACE);
     if (constantsElement != null) {
       constants = root.getChild("constants", NAME_SPACE).getChildren(); // 常量定义
     } else {
       constants = new ArrayList();
     }
     this.replaceMacros(messages);
     createServerFiles(messages, module);
     createClientFile(messages, module, constants);
     createServerMappingFile(messages, module);
     createRobotServerMappingFile(messages, module);
   } catch (Exception e) {
     logger.error("", e);
   }
 }
Ejemplo n.º 24
0
  public static void main(String[] args) {

    if (args.length == 0) {
      System.out.println("Usage: java JDOMValidator URL");
      return;
    }

    SAXBuilder builder = new SAXBuilder(true);
    //  ^^^^
    // Turn on validation

    // command line should offer URIs or file names
    try {
      builder.build(args[0]);
      // If there are no well-formedness or validity errors,
      // then no exception is thrown.
      System.out.println(args[0] + " is valid.");
    }
    // indicates a well-formedness or validity error
    catch (JDOMException e) {
      System.out.println(args[0] + " is not valid.");
      System.out.println(e.getMessage());
    } catch (IOException e) {
      System.out.println("Could not check " + args[0]);
      System.out.println(" because " + e.getMessage());
    }
  }
Ejemplo n.º 25
0
  @SuppressWarnings("unchecked")
  private List<JarConfig> loadConfig() {
    List<JarConfig> list_pair = new ArrayList<JarConfig>();
    SAXBuilder builder = new SAXBuilder();

    try {
      Document document = builder.build(this.config);
      Element root = document.getRootElement();
      Element ele = (Element) XPath.selectSingleNode(root, path.JAR.toString());
      List<Element> list = ele.getChildren();
      for (Element element : list) {
        JarConfig config =
            new JarConfig(
                classPath + element.getAttributeValue("jar").trim(),
                element.getAttributeValue("name").trim(),
                element.getAttributeValue("class").trim());

        list_pair.add(config);
      }
    } catch (JDOMException e) {
      WriteToLog.error("XML FORMAT ERROR!" + "\n" + e.getMessage());

    } catch (IOException e) {
      WriteToLog.error("XML FORMAT ERROR!" + "\n" + e.getMessage());
    } catch (Exception e) {
      e.printStackTrace();
      WriteToLog.error("XML ERROR!" + "\n" + e.getMessage());
    }
    return list_pair;
  }
  private void loadTerminologyFromXML(String filename) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    InputStream input = this.getClass().getResourceAsStream(filename);
    try {
      Document doc = builder.build(input);
      Element root = doc.getRootElement();
      List codesets = root.getChildren("codeset");
      codeSetList.clear();
      groupList.clear();

      for (Iterator it = codesets.iterator(); it.hasNext(); ) {
        Element element = (Element) it.next();
        codeSetList.add(loadCodeSet(element));
      }

      List groups = root.getChildren("group");
      for (Iterator it = groups.iterator(); it.hasNext(); ) {
        Element element = (Element) it.next();
        groupList.add(loadGroup(element));
      }
    } finally {
      if (input != null) {
        input.close();
      }
    }
  }
Ejemplo n.º 27
0
  /**
   * Read the description of the Folder from the specified URL.
   *
   * @param url the URL of a web service providing the description of the Folder
   * @param treenode the JTree node that represents this Folder
   */
  private void readFolderFromURL(String url, DefaultMutableTreeNode treenode) {
    ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();

    // add the LoadDescription action
    list.add(new NameValuePair("Action", "LoadDescription")); // $NON-NLS-1$ //$NON-NLS-2$

    try {
      // get an input stream from the URL
      InputStream fin = getInputStream(url, list);

      // build the XML document
      SAXBuilder builder = new SAXBuilder();

      Document doc = builder.build(fin);

      // get the root Element in the document
      Element root = doc.getRootElement();

      readFolder(treenode, root);

    } catch (MalformedURLException ex) {
      errorMessage(Messages.getString(BUNDLE_NAME, "Folder.12") + url); // $NON-NLS-1$
      LOG.error(Messages.getString(BUNDLE_NAME, "Folder.13") + url, ex); // $NON-NLS-1$
    } catch (JDOMException ex) {
      // indicates a well-formedness error
      errorMessage(Messages.getString(BUNDLE_NAME, "Folder.14") + url); // $NON-NLS-1$
      LOG.error(Messages.getString(BUNDLE_NAME, "Folder.15") + url, ex); // $NON-NLS-1$
    } catch (IOException ex) {
      errorMessage(Messages.getString(BUNDLE_NAME, "Folder.16") + url); // $NON-NLS-1$
      LOG.error(Messages.getString(BUNDLE_NAME, "Folder.17") + url, ex); // $NON-NLS-1$
    } catch (Exception ex) {
      errorMessage(Messages.getString(BUNDLE_NAME, "Folder.18") + url); // $NON-NLS-1$
      LOG.error(Messages.getString(BUNDLE_NAME, "Folder.19") + url, ex); // $NON-NLS-1$
    }
  }
  /* (non-Javadoc)
   * @see org.hibernate.UserType#nullSafeGet(java.sql.ResultSet, java.lang.String[], java.lang.Object)
   */
  public Object nullSafeGet(ResultSet rs, String[] names, Object owner)
      throws HibernateException, SQLException {
    byte[] bytes = rs.getBytes(names[0]);
    if (rs.wasNull()) {
      return null;
    }

    // TODO figure out how to inject this
    HomeFactory homeFactory = (HomeFactory) ComponentManager.getInstance().get("xmlHomeFactory");
    WritableObjectHome home = (WritableObjectHome) homeFactory.getHome("agent");

    StructuredArtifact artifact = (StructuredArtifact) home.createInstance();
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    SAXBuilder saxBuilder = new SAXBuilder();
    saxBuilder.setFeature(
        "http://apache.org/xml/features/disallow-doctype-decl", true); // SAK-23245
    try {
      Document doc = saxBuilder.build(in);
      artifact.setBaseElement(doc.getRootElement());
    } catch (JDOMException e) {
      throw new HibernateException(e);
    } catch (IOException e) {
      throw new HibernateException(e);
    }
    return artifact;
  }
  /*
   * Liest die Scenario Informationen in die entsprechenden Objekte
   * und gibt eine Liste davon zurueck. Siehe dazu auch MeteringProcessStorage.java.
   * @param fileName Dateiname der Storagedatei
   * @return Liste mit den Scenario-Objekte.
   */
  public List getList() {
    List scenariosList = new ArrayList();
    try {
      SAXBuilder builder = new SAXBuilder();
      StorageDoc = builder.build(appPath + storageFileName);
      Root = StorageDoc.getRootElement();
      List scenarioChildren = Root.getChildren("scenario", ipfixConfigNS);
      Iterator listIterator = scenarioChildren.iterator();
      Element currentElement;

      while (listIterator.hasNext()) {
        currentElement = (Element) listIterator.next();
        Scenario currentScenario = new Scenario();
        // currentscenario.setId(Integer.valueOf(currentElement.getAttributeValue("id")));
        currentScenario.setName(currentElement.getChildText("name", ipfixConfigNS));
        currentScenario.setDescription(currentElement.getChildText("descript", ipfixConfigNS));
        List deviceList = new ArrayList();
        Element devices = currentElement.getChild("devices", ipfixConfigNS);
        List childList = devices.getChildren("device", ipfixConfigNS);
        Iterator devicesIterator = childList.iterator();
        while (devicesIterator.hasNext()) {
          Element currentDevice = (Element) devicesIterator.next();
          deviceList.add(currentDevice.getText());
        }
        currentScenario.setDeviceList(deviceList);
        scenariosList.add(currentScenario);
      }

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return scenariosList;
  }
Ejemplo n.º 30
0
 /**
  * Initialize all the exporters
  *
  * @param file the {@link File} with the exporters to intialize
  * @throws ExportException when cannot read from the file
  */
 public static void initializeExporters(File file) throws ExportException {
   BufferedReader reader = null;
   try {
     reader = new BufferedReader(new FileReader(file));
     // if(reader==null)
     // {
     // String params[]={file.getAbsolutePath()};
     // throw new
     // ExportException(StringUtilities.getReplacedString(PropertiesHandler.getResourceString("error.algorithm.file"),params));
     // }
     SAXBuilder builder = new SAXBuilder(true);
     builder.setEntityResolver(new NetworkEntityResolver());
     Document doc = builder.build(reader);
     loadFromDocument(doc);
   } catch (FileNotFoundException e) {
     throw new ExportException(e.getMessage());
   } catch (JDOMException e) {
     throw new ExportException(e.getMessage());
   } catch (Exception e) {
     throw new ExportException(e.getMessage());
   } finally {
     if (reader != null) {
       try {
         reader.close();
       } catch (IOException ignore) {
       }
     }
   }
 }