Beispiel #1
0
  /**
   * Writes the test results in XML format to the supplied writer.
   *
   * <p>This method does NOT close the writer object.
   *
   * @param allResults The test results.
   * @param writer The writer in which the XML data will be written to.
   */
  public static void writeXmlOutput(List<TestResults> allResults, Writer writer)
      throws IOException {
    try {
      // Build the XML output.
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dbf.newDocumentBuilder();
      Document doc = docBuilder.newDocument();
      // Create the <tests> tag. All test data will be within this tag.
      Element testsEl = doc.createElement("tests");
      doc.appendChild(testsEl);

      for (TestResults results : allResults) {
        for (TestCaseSummary testCase : results.getTestCases()) {
          // Create the <test name="..." status="..." time="..."> tag.
          // This records a single test case result in the test suite.
          Element testEl = doc.createElement("test");
          testEl.setAttribute("name", testCase.getTestCaseName());
          testEl.setAttribute("status", testCase.isSuccess() ? "PASS" : "FAIL");
          testEl.setAttribute("time", Long.toString(testCase.getTotalTime()));
          testsEl.appendChild(testEl);

          // Loop through the test case and add XML data (name, message, and
          // stacktrace) for each individual test, if present.
          addExtraXmlInfo(testCase, testEl);
        }
      }

      // Write XML to the writer.
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      transformer.transform(new DOMSource(doc), new StreamResult(writer));
    } catch (TransformerException | ParserConfigurationException ex) {
      throw new IOException("Unable to build the XML document!");
    }
  }
Beispiel #2
0
  /**
   * Returns a new {@code XMLConfig} with no entries.
   *
   * @return a new {@code XMLConfig} with no entries
   */
  static XMLConfig empty() {
    XMLConfig rv = naked();
    Document xmlDoc;
    try {
      xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException ex) {
      throw new ConfigException(ex);
    }

    Element rootElement = xmlDoc.createElement(ROOT_PREFIX);

    Element numberElements = xmlDoc.createElement(Repository.NUMBER.getName());
    rootElement.appendChild(numberElements);

    Element stringElements = xmlDoc.createElement(Repository.STRING.getName());
    rootElement.appendChild(stringElements);

    Element booleanElements = xmlDoc.createElement(Repository.BOOLEAN.getName());
    rootElement.appendChild(booleanElements);

    xmlDoc.appendChild(rootElement);
    xmlDoc.setXmlStandalone(true);

    rv.stringElements = stringElements;
    rv.numberElements = numberElements;
    rv.booleanElements = booleanElements;
    rv.xmlDoc = xmlDoc;

    return rv;
  }
Beispiel #3
0
  /**
   * This method serialises the state and action labels
   *
   * @param document
   */
  private static void serialiseStateAndActionLabels(final Element tree, final Document document) {
    HashMap<String, ArrayList<String>> retrievedStateLabels =
        QueryManager.getData().getStateLabels();
    HashMap<String, ArrayList<String>> stateLabels = new HashMap<String, ArrayList<String>>();
    ArrayList<String> actionLabels = new ArrayList<String>();

    // only add the state and action labels to the respective array lists
    // that are actually
    // occurring in the macro
    ArrayList<PerformanceTreeNode> nodesArray = MacroWriter.macro.getMacroNodes();
    Iterator<PerformanceTreeNode> ni = nodesArray.iterator();
    while (ni.hasNext()) {
      PerformanceTreeNode node = ni.next();
      if (node instanceof StatesNode) {
        StatesNode statesNode = (StatesNode) node;
        if (statesNode.getNodeLabelObject() != null) {
          String stateLabel = statesNode.getNodeLabel();
          ArrayList<String> states = retrievedStateLabels.get(stateLabel);
          stateLabels.put(stateLabel, states);
        }
      } else if (node instanceof ActionsNode) {
        ActionsNode actionsNode = (ActionsNode) node;
        if (actionsNode.getNodeLabelObject() != null) {
          String actionLabel = actionsNode.getNodeLabel();
          actionLabels.add(actionLabel);
        }
      }
    }

    // serialise state labels
    Element stateLabelsElement = document.createElement("stateLabels");
    tree.appendChild(stateLabelsElement);
    Iterator<String> i = stateLabels.keySet().iterator();
    while (i.hasNext()) {
      Element stateLabelElement = document.createElement("statelabel");
      stateLabelsElement.appendChild(stateLabelElement);
      String stateLabel = i.next();
      ArrayList<String> stateLabelsStates = stateLabels.get(stateLabel);
      stateLabelElement.setAttribute("name", stateLabel);
      Iterator<String> j = stateLabelsStates.iterator();
      while (j.hasNext()) {
        Element stateElement = document.createElement("state");
        stateLabelElement.appendChild(stateElement);
        String stateName = j.next();
        stateElement.setAttribute("name", stateName);
      }
    }

    // serialise action labels
    Element actionLabelsElement = document.createElement("actionLabels");
    tree.appendChild(actionLabelsElement);
    Element actionLabelElement;
    i = actionLabels.iterator();
    while (i.hasNext()) {
      actionLabelElement = document.createElement("actionlabel");
      actionLabelsElement.appendChild(actionLabelElement);
      String actionLabel = i.next();
      actionLabelElement.setAttribute("label", actionLabel);
    }
  }
Beispiel #4
0
 private Element getOptions(Object service, String project, Document doc) {
   List options;
   if (service instanceof ISource) {
     options = ((ISource) service).listOptions(project);
   } else if (service instanceof IBuilder) {
     options = ((IBuilder) service).getOptions();
   } else if (service instanceof IDeployer) {
     options = Collections.EMPTY_LIST;
   } else {
     return null;
   }
   Element optionsElement = doc.createElement("options");
   for (Iterator i = options.iterator(); i.hasNext(); ) {
     Option o = (Option) i.next();
     Element option = doc.createElement("option");
     ;
     if (o instanceof BooleanOption) {
       option.setAttribute("type", "boolean");
     } else if (o instanceof ListOption) {
       option.setAttribute("type", "list");
       for (Iterator j = ((ListOption) o).getChoices().iterator(); j.hasNext(); ) {
         Element choice = doc.createElement("choice");
         choice.setAttribute("value", (String) j.next());
         option.appendChild(choice);
       }
     }
     option.setAttribute("name", o.getName());
     option.setAttribute("label", o.getLabel());
     optionsElement.appendChild(option);
   }
   return optionsElement;
 }
  protected void encodeObject(
      org.w3c.dom.Document document,
      org.w3c.dom.Element node,
      edu.cmu.cs.stage3.io.DirectoryTreeStorer storer,
      edu.cmu.cs.stage3.alice.core.ReferenceGenerator referenceGenerator)
      throws java.io.IOException {
    java.util.Dictionary dict = getDictionaryValue();
    if (dict != null) {
      java.util.Enumeration enum0 = dict.keys();
      while (enum0.hasMoreElements()) {
        Object key = enum0.nextElement();
        Object value = dict.get(key);

        org.w3c.dom.Element entryNode = document.createElement("entry");

        org.w3c.dom.Element keyNode = document.createElement("key");
        keyNode.setAttribute("class", key.getClass().getName());
        keyNode.appendChild(createNodeForString(document, key.toString()));

        org.w3c.dom.Element valueNode = document.createElement("value");
        valueNode.setAttribute("class", value.getClass().getName());
        valueNode.appendChild(createNodeForString(document, value.toString()));

        entryNode.appendChild(keyNode);
        entryNode.appendChild(valueNode);
        node.appendChild(entryNode);
      }
    }
  }
Beispiel #6
0
  /**
   * This method exports the single pattern decision instance to the XML. It MUST be called by an
   * XML exporter, as this will not have a complete header.
   *
   * @param ratDoc The ratDoc generated by the XML exporter
   * @return the SAX representation of the object.
   */
  public Element toXML(Document ratDoc) {
    Element decisionE;
    RationaleDB db = RationaleDB.getHandle();

    // Now, add pattern to doc
    String entryID = db.getRef(this);
    if (entryID == null) {
      entryID = db.addPatternDecisionRef(this);
    }

    decisionE = ratDoc.createElement("DR:patternDecision");
    decisionE.setAttribute("rid", entryID);
    decisionE.setAttribute("name", name);
    decisionE.setAttribute("type", type.toString());
    decisionE.setAttribute("phase", devPhase.toString());
    decisionE.setAttribute("status", status.toString());
    // decisionE.setAttribute("artifact", artifact);

    Element descE = ratDoc.createElement("description");
    Text descText = ratDoc.createTextNode(description);
    descE.appendChild(descText);
    decisionE.appendChild(descE);

    // Add child pattern references...
    Iterator<Pattern> cpi = candidatePatterns.iterator();
    while (cpi.hasNext()) {
      Pattern cur = cpi.next();
      Element curE = ratDoc.createElement("refChildPattern");
      Text curText = ratDoc.createTextNode("p" + new Integer(cur.getID()).toString());
      curE.appendChild(curText);
      decisionE.appendChild(curE);
    }

    return decisionE;
  }
Beispiel #7
0
  /** @see com.levelonelabs.aim.XMLizable#writeState(Element) */
  public void writeState(Element emptyStateElement) {
    Document doc = emptyStateElement.getOwnerDocument();
    emptyStateElement.setAttribute("name", this.getName());
    emptyStateElement.setAttribute("group", this.getGroup());
    emptyStateElement.setAttribute("isBanned", Boolean.toString(this.isBanned()));

    Iterator roleit = roles.keySet().iterator();
    while (roleit.hasNext()) {
      String role = (String) roleit.next();
      Element roleElem = doc.createElement("role");
      roleElem.setAttribute("name", role);
      emptyStateElement.appendChild(roleElem);
    }

    Iterator prefs = preferences.keySet().iterator();
    while (prefs.hasNext()) {
      String pref = (String) prefs.next();
      Element prefElem = doc.createElement("preference");
      prefElem.setAttribute("name", pref);
      prefElem.setAttribute("value", (String) preferences.get(pref));
      emptyStateElement.appendChild(prefElem);
    }

    for (int i = 0; i < messages.size(); i++) {
      String message = (String) messages.get(i);
      Element messElem = doc.createElement("message");
      CDATASection data = doc.createCDATASection(message);
      messElem.appendChild(data);
      emptyStateElement.appendChild(messElem);
    }
  }
Beispiel #8
0
  public static void main(String[] args) {

    try {

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document = builder.newDocument();
      Element root = document.createElement("Languages");
      root.setAttribute("cat", "it");

      Element lan1 = document.createElement("lan");
      lan1.setAttribute("id", "1");
      Element name1 = document.createElement("name");
      name1.setTextContent("Java");
      Element ide1 = document.createElement("ide");
      ide1.setTextContent("Eclipse");
      lan1.appendChild(name1);
      lan1.appendChild(ide1);

      Element lan2 = document.createElement("lan");
      lan1.setAttribute("id", "2");
      Element name2 = document.createElement("name");
      name1.setTextContent("Swift");
      Element ide2 = document.createElement("ide");
      ide1.setTextContent("Xcode");
      lan1.appendChild(name2);
      lan1.appendChild(ide2);

      Element lan3 = document.createElement("lan");
      lan1.setAttribute("id", "1");
      Element name3 = document.createElement("name");
      name1.setTextContent("Java");
      Element ide3 = document.createElement("ide");
      ide1.setTextContent("Eclipse");
      lan1.appendChild(name3);
      lan1.appendChild(ide3);

      root.appendChild(lan1);
      root.appendChild(lan2);
      root.appendChild(lan3);
      document.appendChild(root);

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      StringWriter writer = new StringWriter();
      transformer.transform(new DOMSource(document), new StreamResult(writer));
      System.out.println(writer.toString());

      transformer.transform(new DOMSource(document), new StreamResult("newXML.xml"));

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TransformerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
 public static String serialize(Storeable s, List<Class<?>> types) {
   Document document;
   try {
     document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
     Element root = document.createElement("row");
     for (int i = 0; i < types.size(); ++i) {
       Object obj = s.getColumnAt(i);
       Element child;
       if (obj == null) {
         child = document.createElement("null");
       } else {
         child = document.createElement("col");
         child.setTextContent(obj.toString());
       }
       root.appendChild(child);
     }
     document.appendChild(root);
   } catch (IndexOutOfBoundsException | ParserConfigurationException e) {
     throw new ColumnFormatException();
   }
   StringWriter writer;
   try {
     Transformer transformer = TransformerFactory.newInstance().newTransformer();
     transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
     writer = new StringWriter();
     transformer.transform(new DOMSource(document), new StreamResult(writer));
   } catch (TransformerException e) {
     throw new RuntimeException("FATAL: Unable to initialize converter");
   }
   return writer.getBuffer().toString().replaceAll("\n|\r", "");
 }
  private Document getXmlDocument() {
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
      Document doc = docBuilder.newDocument();

      // create the root element and add it to the document
      Element root = doc.createElement("paletteAssociations");
      doc.appendChild(root);

      for (PaletteAssociation element : values()) {
        Element xmlElement = doc.createElement("element");
        xmlElement.setAttribute("name", element.name);
        xmlElement.setAttribute("displayString", element.displayString);
        xmlElement.setAttribute("url", element.url);
        xmlElement.setAttribute("description", element.description);
        xmlElement.setAttribute("initWidth", Integer.toString(element.initWidth));
        xmlElement.setAttribute("initHeight", Integer.toString(element.initHeight));

        root.appendChild(xmlElement);
      }

      return doc;

    } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return null;
  }
  public boolean addSubscriber(String virtualUser, String subscriberEmail) {
    Element watchedInvitation = getInvitationElementByVirtualUser(virtualUser);
    if (watchedInvitation == null) {
      return false;
    }

    Element subscriberListElem = XmlUtil.getChildByTagName(watchedInvitation, "subscriberList");
    if (subscriberListElem == null) {
      subscriberListElem = doc.createElement("subscriberList");
      watchedInvitation.appendChild(subscriberListElem);
    }

    NodeList subscriberList = subscriberListElem.getElementsByTagName("subscriber");

    if (subscriberList != null) {
      int listLength = subscriberList.getLength();
      for (int i = 0; i < listLength; i++) {
        Element subscriberElement = (Element) subscriberList.item(i);
        if (XmlUtil.getChildText(subscriberElement, "email").equals(subscriberEmail)) {
          return false;
        }
      }
    }

    Element subscriberElem = doc.createElement("subscriber");
    XmlUtil.setChildText(subscriberElem, "email", subscriberEmail);
    XmlUtil.setChildText(subscriberElem, "code", generateAccessCode());
    subscriberListElem.appendChild(subscriberElem);
    changed = true;
    return true;
  }
Beispiel #12
0
  private void store_data(Location loc) {

    Element trkpt = gpx_document.createElement("trkpt");

    Attr longitude = gpx_document.createAttribute("lon");
    Attr latitude = gpx_document.createAttribute("lat");
    longitude.setValue(Double.toString(currentLongitude));
    latitude.setValue(Double.toString(currentLatitude));

    trkpt.setAttributeNode(longitude);
    trkpt.setAttributeNode(latitude);

    Element elevation = gpx_document.createElement("ele");
    String altitude = Double.toString(loc.getAltitude());
    elevation.appendChild(gpx_document.createTextNode(altitude));
    trkpt.appendChild(elevation);

    Element timestamp = gpx_document.createElement("time");
    String time = Long.toString(loc.getTime());
    timestamp.appendChild(gpx_document.createTextNode(time));
    trkpt.appendChild(timestamp);

    Element type = gpx_document.createElement("type");
    String difficulty = currentDifficulty.getDifficulty();
    type.appendChild(gpx_document.createTextNode(difficulty));
    trkpt.appendChild(type);

    trackSegment.appendChild(trkpt);

    update_screen_info(altitude, difficulty);
  }
Beispiel #13
0
  public void start_GPS_Capture()
      throws ParserConfigurationException, TransformerConfigurationException {

    gpx_document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

    rootElement = gpx_document.createElement("gpx");
    Attr xmlns = gpx_document.createAttribute("xmlns");
    Attr version = gpx_document.createAttribute("version");
    Attr creator = gpx_document.createAttribute("creator");

    xmlns.setValue("http://www.topografix.com/GPX/1/1");
    version.setValue("1.1");
    creator.setValue("http://offtrek.com");

    rootElement.setAttributeNode(xmlns);
    rootElement.setAttributeNode(version);
    rootElement.setAttributeNode(creator);

    track = gpx_document.createElement("trk");
    trackSegment = gpx_document.createElement("trkseg");

    track.appendChild(trackSegment);
    rootElement.appendChild(track);
    gpx_document.appendChild(rootElement);

    Chronometer chrono = (Chronometer) findViewById(R.id.chronometer);
    chrono.setBase(chronoBase);
    chrono.start();
    GPS_captureStarted = true;
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
  }
Beispiel #14
0
  /**
   * A helper method that adds extra XML.
   *
   * <p>This includes a test name, time (in ms), message, and stack trace, when present. Example:
   *
   * <pre>
   * &lt;testresult name="failed_test" time="200">
   *   &lt;message>Reason for test failure&lt;/message>
   *   &lt;stacktrace>Stacktrace here&lt;/stacktrace>
   * &lt;/testresult>
   * </pre>
   *
   * @param testCase The test case summary containing one or more tests.
   * @param testEl The XML element object for the <test> tag, in which extra information tags will
   *     be added.
   */
  @VisibleForTesting
  static void addExtraXmlInfo(TestCaseSummary testCase, Element testEl) {
    Document doc = testEl.getOwnerDocument();
    // Loop through the test case and extract test data.
    for (TestResultSummary testResult : testCase.getTestResults()) {
      // Extract the test name and time.
      String name = Strings.nullToEmpty(testResult.getTestName());
      String time = Long.toString(testResult.getTime());

      // Create the tag: <testresult name="..." time="...">
      Element testResultEl = doc.createElement("testresult");
      testResultEl.setAttribute("name", name);
      testResultEl.setAttribute("time", time);
      testEl.appendChild(testResultEl);

      // Create the tag: <message>(Error message here)</message>
      Element messageEl = doc.createElement("message");
      String message = Strings.nullToEmpty(testResult.getMessage());
      messageEl.appendChild(doc.createTextNode(message));
      testResultEl.appendChild(messageEl);

      // Create the tag: <stacktrace>(Stacktrace here)</stacktrace>
      Element stacktraceEl = doc.createElement("stacktrace");
      String stacktrace = Strings.nullToEmpty(testResult.getStacktrace());
      stacktraceEl.appendChild(doc.createTextNode(stacktrace));
      testResultEl.appendChild(stacktraceEl);
    }
  }
  /**
   * Add attachement element for the javadoc artifact if present.
   *
   * <pre>
   *  &lt;attach file="${basedir}/target/my-project-1.0-javadoc.jar"
   *             type="jar"
   *             classifier="javadoc"/&gt;
   * </pre>
   *
   * @param el element to add the attachment to.
   * @param ba The bundle archive to add a source artifact for.
   * @param prefix Whitespace to add before the new element.
   */
  private void addJavadocAttachment(final Element el, final BundleArchive ba, final String prefix) {
    String javadocPath = ba.file.getAbsolutePath();
    // Remove ".jar" suffix.
    javadocPath = javadocPath.substring(0, javadocPath.length() - 4);
    javadocPath = javadocPath + "-javadoc.jar";

    final File javadocFile = new File(javadocPath);
    if (javadocFile.exists()) {
      final Document doc = el.getOwnerDocument();
      final String prefix1 = prefix + "  ";
      final String prefix2 = prefix1 + "  ";
      final Element javadocAttachment = doc.createElement("javadoc-attachment");

      el.appendChild(doc.createTextNode("\n" + prefix1));
      el.appendChild(javadocAttachment);
      el.appendChild(doc.createTextNode("\n" + prefix));

      final Element attach = doc.createElement("attach");
      javadocAttachment.appendChild(doc.createTextNode("\n" + prefix2));
      javadocAttachment.appendChild(attach);
      javadocAttachment.appendChild(doc.createTextNode("\n" + prefix1));

      attach.setAttribute("file", javadocPath);
      attach.setAttribute("type", "jar");
      attach.setAttribute("classifier", "javadoc");
    }
  }
Beispiel #16
0
  private void xmlWrite(String name, String score) {
    try {
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      docFactory.setValidating(true);
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
      org.w3c.dom.Document doc = docBuilder.parse(xml);

      Node data = doc.getFirstChild();

      org.w3c.dom.Element root = doc.createElement("ranking");
      org.w3c.dom.Element player = doc.createElement("player");
      org.w3c.dom.Element _name = doc.createElement("name");
      _name.setTextContent(name);
      org.w3c.dom.Element _score = doc.createElement("score");
      _score.setTextContent(score);

      player.appendChild(_name);
      player.appendChild(_score);
      root.appendChild(player);

      data.appendChild(player);

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(xml);
      transformer.transform(source, result);

    } catch (Exception ex) {
    }
  }
  @Test
  public void testGetRecursiveChildIter() {
    final Document doc = XMLFactory.newDocument();

    // No children present
    assertFalse(new ChildElementIterator(doc).hasNext());

    // 1 child
    final Element eRoot = (Element) doc.appendChild(doc.createElement("root"));
    assertEquals(1, ContainerHelper.newList(new ChildElementIterator(doc)).size());

    // 2 children
    eRoot.appendChild(doc.createElement("Hallo"));
    eRoot.appendChild(doc.createTextNode(" - "));
    eRoot.appendChild(doc.createElement("Welt"));
    assertEquals(2, ContainerHelper.newList(new ChildElementIterator(eRoot)).size());
    assertEquals(
        1,
        ContainerHelper.newList(
                new ChildElementIterator(eRoot, new FilterElementWithTagName("Hallo")))
            .size());

    try {
      new ChildElementIterator(doc).remove();
      fail();
    } catch (final UnsupportedOperationException ex) {
    }
    try {
      new ChildElementIterator(null);
      fail();
    } catch (final NullPointerException ex) {
    }
  }
Beispiel #18
0
  public void logQuery(
      final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo) {
    final Element updateElement = createOrGetUpdateElement(update);

    final Element queryElement = doc.createElement("query");
    updateElement.appendChild(queryElement);

    queryElement.appendChild(keyValue("sql", statementInfo.getSql()));
    final Element paramsElement = doc.createElement("params");
    queryElement.appendChild(paramsElement);
    for (final Map.Entry<Integer, Object> entry : statementInfo.getParameters().entrySet()) {
      final Element param = keyValue("param", entry.getValue());
      param.setAttribute("idx", String.valueOf(entry.getKey()));
      paramsElement.appendChild(param);
    }

    final Element resultsElement = doc.createElement("results");
    queryElement.appendChild(resultsElement);

    int rowNum = 1;
    for (final List<String> row : resultInfo.getRows()) {
      final Element rowElement = doc.createElement("row");
      rowElement.setAttribute("idx", String.valueOf(rowNum++));
      resultsElement.appendChild(rowElement);

      int colNum = 0;
      for (final String column : row) {
        final Element columnElement = keyValue("column", column);
        columnElement.setAttribute("idx", String.valueOf(colNum++));
        rowElement.appendChild(columnElement);
      }
    }
  }
Beispiel #19
0
  /**
   * Similar to the XMLRepresentation interface, this method will append an XML representation of
   * some preferences to an existing node.
   *
   * @param prefs the preferences node to write out.
   * @param deep - true to include a subtree with all child preferences nodes.
   * @param domDoc the document in which the node will reside.
   * @param node the node to which a child is applied.
   */
  public static void toXML(
      Preferences prefs, boolean deep, org.w3c.dom.Document domDoc, Element node, Map options)
      throws IOException {
    String[] keys;
    String[] children;
    Element childElement, entry;
    String value;
    int i;

    // System.err.println( "node = "+prefs.name() );
    try {
      keys = prefs.keys();
      childElement = (Element) node.appendChild(domDoc.createElement("map"));
      for (i = 0; i < keys.length; i++) {
        value = prefs.get(keys[i], null);
        // System.err.println( "  key = "+keys[i]+"; value = "+value );
        if (value == null) continue;
        entry = (Element) childElement.appendChild(domDoc.createElement("entry"));
        entry.setAttribute("key", keys[i]);
        entry.setAttribute("value", value);
      }
      if (deep) {
        children = prefs.childrenNames();
        for (i = 0; i < children.length; i++) {
          childElement = (Element) node.appendChild(domDoc.createElement("node"));
          childElement.setAttribute("name", children[i]);
          toXML(prefs.node(children[i]), deep, domDoc, childElement, options);
        }
      }
    } catch (DOMException e1) {
      throw IOUtil.map(e1);
    } catch (BackingStoreException e2) {
      throw IOUtil.map(e2);
    }
  }
Beispiel #20
0
  @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */)
  public void log(final Message message, @Nullable final Throwable t) {
    final Element typeElement = doc.createElement(message.getType().toString());

    final Element messageElement = doc.createElement("message");
    messageElement.setTextContent(message.toString());
    typeElement.appendChild(messageElement);

    if (t != null) {
      final Element throwableElement = doc.createElement("throwable");

      final Element throwableMessageElement = doc.createElement("message");
      throwableMessageElement.setTextContent(t.getMessage());
      throwableElement.appendChild(throwableMessageElement);

      final StringWriter stringWriter = new StringWriter();
      final PrintWriter printWriter = new PrintWriter(stringWriter);

      t.printStackTrace(printWriter);
      printWriter.flush();

      final Element stacktraceElement = doc.createElement("stacktrace");
      stacktraceElement.setTextContent(stringWriter.toString());
      throwableElement.appendChild(stacktraceElement);

      typeElement.appendChild(throwableElement);
    }

    messages.appendChild(typeElement);
  }
Beispiel #21
0
 /* (non-Javadoc)
  * @see parser.CBMSElement#DoExportCustom(org.w3c.dom.Document)
  */
 protected Element DoExportCustom(Document root) {
   Element eF = root.createElement("Field");
   eF.setAttribute("PosLine", String.valueOf(m_PosLine));
   eF.setAttribute("PosCol", String.valueOf(m_PosCol));
   eF.setAttribute("Length", String.valueOf(m_Length));
   if (m_Color != null) {
     eF.setAttribute("Color", m_Color.m_Name);
   }
   if (m_HighLight != null) {
     eF.setAttribute("HighLight", m_HighLight.m_Name);
   }
   eF.setAttribute("Value", m_Value);
   for (int i = 0; i < m_arrATTRB.size(); i++) {
     String val = m_arrATTRB.elementAt(i);
     Element e = root.createElement("ATTRB");
     e.setAttribute("Value", val);
     eF.appendChild(e);
   }
   for (int i = 0; i < m_arrJustify.size(); i++) {
     String val = m_arrJustify.elementAt(i);
     Element e = root.createElement("JUSTIFY");
     e.setAttribute("Value", val);
     eF.appendChild(e);
   }
   return eF;
 }
Beispiel #22
0
  public static void updateUser(User userToUpdate) throws Exception {
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(Constants.USER_DATA_FILE_PATH);

    NodeList nodeList = document.getElementsByTagName("user");
    for (int i = 0; i < nodeList.getLength(); i++) {
      Node user = nodeList.item(i);
      if (user.getNodeType() == Node.ELEMENT_NODE) {
        Element userElement = (Element) user;
        String userName = userElement.getElementsByTagName("username").item(0).getTextContent();
        if (userName.equalsIgnoreCase(userToUpdate.getUserName())) {
          Node oldAccessibleSheetsNode =
              userElement.getElementsByTagName("accessibleSheets").item(0);
          userElement.removeChild(oldAccessibleSheetsNode);

          // Add new accessibleSheetsNode
          Element newAccessibleSheets = document.createElement("accessibleSheets");
          for (String sheet : userToUpdate.getAccessibleSheets()) {
            Element sheet1 = document.createElement("sheet");
            sheet1.setAttribute("filename", sheet);
            newAccessibleSheets.appendChild(sheet1);
          }
          userElement.appendChild(newAccessibleSheets);
          transformDocumentToXml(document, Constants.USER_DATA_FILE_PATH);
          System.out.println("updated user");
          return;
        }
      }
    }
  }
  //
  // Marshaller's private methods
  //
  private Element marshallConfiguration(ComponentConfigurationImpl config) throws Exception {
    // get ComponentConfigurationImpl Object data
    String configPid = config.getPid();
    Map<String, Object> configProperty = config.getConfigurationProperties();
    Tocd configOCD = config.getDefinition();

    // create configuration element
    Element configurationElement =
        mashallDoc.createElement(ESF_NAMESPACE + ":" + CONFIGURATIONS_CONFIGURATION);
    Attr propertiesAttribute = mashallDoc.createAttribute(CONFIGURATION_PID);
    propertiesAttribute.setNodeValue(configPid);
    configurationElement.setAttributeNode(propertiesAttribute);

    // Add OCD node and marshall definitions
    if (configOCD != null) {
      Element ocd = new XmlJavaMetadataMapper().marshal(mashallDoc, configOCD);
      configurationElement.appendChild(ocd);
    }

    // Add properties Node and marshall properties
    if (configProperty != null) {
      Element properties = mashallDoc.createElement(ESF_NAMESPACE + ":" + PROPERTIES);
      marshallProperties(configProperty, properties);
      configurationElement.appendChild(properties);
    }

    return configurationElement;
  }
  public static Element serializeCaseComponent(
      CaseComponent casecomponent, String name, Document doc) {
    try {
      Element root = doc.createElement("CaseComponent");
      root.setAttribute("Name", name);
      root.setAttribute("Class", casecomponent.getClass().getCanonicalName());
      root.setAttribute("IdAttribute", casecomponent.getIdAttribute().getName());

      for (Attribute at : AttributeUtils.getAttributes(casecomponent)) {
        if (CaseComponent.class.isAssignableFrom(at.getType()))
          root.appendChild(
              serializeCaseComponent(
                  (CaseComponent) at.getValue(casecomponent), at.getName(), doc));
        else {
          Element child = doc.createElement(at.getName());
          Object value = at.getValue(casecomponent);
          if (value != null) child.appendChild(doc.createTextNode(value.toString()));
          root.appendChild(child);
        }
      }

      return root;
    } catch (Exception e) {
      org.apache.commons.logging.LogFactory.getLog(CaseComponentSerializer.class).error(e);
    }
    return null;
  }
  protected void getAlbumsElements(Document doc, GalleryAlbums gallery) {
    Element galleryNameElement = doc.createElement("galleryName");
    galleryNameElement.appendChild(doc.createTextNode(gallery.getGalleryName()));

    Element homePageElement = doc.createElement("homePage");
    homePageElement.appendChild(doc.createTextNode(gallery.getGalleryHomePage()));

    Element root = doc.getDocumentElement();

    root.appendChild(galleryNameElement);
    root.appendChild(homePageElement);

    Element albumsElement = doc.createElement("albums");

    AlbumBean[] albums = gallery.getAllAlbums();
    for (AlbumBean album : albums) {

      Element albumElement = doc.createElement("album");

      albumElement.setAttribute("img", album.getImgThumbnail());
      albumElement.setAttribute("folderName", album.getFolderName());
      albumElement.setAttribute("name", album.getName());
      albumElement.setAttribute("tags", album.getTagsInOneLine());

      albumsElement.appendChild(albumElement);
    }
    root.appendChild(albumsElement);
  }
  @Get("xml")
  public Representation toXml() {
    try {
      DomRepresentation representation = new DomRepresentation(MediaType.TEXT_XML);
      // Generate a DOM document representing the item.
      Document d = representation.getDocument();

      Element eltItem = d.createElement("item");
      d.appendChild(eltItem);
      Element eltName = d.createElement("name");
      eltName.appendChild(d.createTextNode(item.getName()));
      eltItem.appendChild(eltName);

      Element eltDescription = d.createElement("description");
      eltDescription.appendChild(d.createTextNode(item.getDescription()));
      eltItem.appendChild(eltDescription);

      d.normalizeDocument();

      // Returns the XML representation of this document.
      return representation;
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
 @Override
 public Element toXML(Document doc) {
   Element e = doc.createElement("Event");
   e.appendChild(doc.createElement("Type")).appendChild(doc.createTextNode("UserUnAwayEvent"));
   e.appendChild(doc.createElement("User")).appendChild(getUser().toXML(doc));
   return e;
 }
  /**
   * Add attachement element for the source artifact if present.
   *
   * <pre>
   * &lt;attach file="${basedir}/target/my-project-1.0-sources.jar"
   *            type="jar"
   *            classifier="sources"&gt;
   * </pre>
   *
   * @param el element to add the attachment to.
   * @param ba The bundle archive to add a source artifact for.
   * @param prefix Whitespace to add before the new element.
   */
  private void addSourceAttachment(final Element el, final BundleArchive ba, final String prefix) {
    String sourcePath = ba.file.getAbsolutePath();
    // Remove ".jar" suffix.
    sourcePath = sourcePath.substring(0, sourcePath.length() - 4);
    sourcePath = sourcePath + "-source.jar";
    final File sourceFile = new File(sourcePath);

    if (sourceFile.exists()) {
      final Document doc = el.getOwnerDocument();
      final String prefix1 = prefix + "  ";
      final String prefix2 = prefix1 + "  ";
      final Element sourceAttachment = doc.createElement("source-attachment");

      el.appendChild(doc.createTextNode("\n" + prefix1));
      el.appendChild(sourceAttachment);
      el.appendChild(doc.createTextNode("\n" + prefix));

      final Element attach = doc.createElement("attach");
      sourceAttachment.appendChild(doc.createTextNode("\n" + prefix2));
      sourceAttachment.appendChild(attach);
      sourceAttachment.appendChild(doc.createTextNode("\n" + prefix1));

      attach.setAttribute("file", sourcePath);
      attach.setAttribute("type", "jar");
      attach.setAttribute("classifier", "sources");
    }
  }
  public static void main(String[] args) {

    String outputDir = "./";

    for (int i = 0; i < args.length; i++) {
      String arg = args[i];
      if ("-o".equals(arg)) {
        outputDir = args[++i];
        continue;
      } else {
        System.out.println("XMLSchemaGenerator -o <path to newly created xsd schema file>");
        return;
      }
    }

    File f = new File(outputDir, "JGroups-" + Version.major + "." + Version.minor + ".xsd");
    try {
      FileWriter fw = new FileWriter(f, false);
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      DOMImplementation impl = builder.getDOMImplementation();
      Document xmldoc = impl.createDocument("http://www.w3.org/2001/XMLSchema", "xs:schema", null);
      xmldoc.getDocumentElement().setAttribute("targetNamespace", "urn:org:jgroups");
      xmldoc.getDocumentElement().setAttribute("elementFormDefault", "qualified");

      Element xsElement = xmldoc.createElement("xs:element");
      xsElement.setAttribute("name", "config");
      xmldoc.getDocumentElement().appendChild(xsElement);

      Element complexType = xmldoc.createElement("xs:complexType");
      xsElement.appendChild(complexType);

      Element allType = xmldoc.createElement("xs:choice");
      allType.setAttribute("maxOccurs", "unbounded");
      complexType.appendChild(allType);

      Set<Class<?>> classes = getClasses("bboss.org.jgroups.protocols", Protocol.class);
      for (Class<?> clazz : classes) {
        classToXML(xmldoc, allType, clazz, "");
      }
      classes = getClasses("bboss.org.jgroups.protocols.pbcast", Protocol.class);
      for (Class<?> clazz : classes) {
        classToXML(xmldoc, allType, clazz, "pbcast.");
      }

      DOMSource domSource = new DOMSource(xmldoc);
      StreamResult streamResult = new StreamResult(fw);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer serializer = tf.newTransformer();
      serializer.setOutputProperty(OutputKeys.METHOD, "xml");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
      serializer.transform(domSource, streamResult);

      fw.flush();
      fw.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Get
  public Representation toXml() throws IOException {
    // Create a new DOM representation
    DomRepresentation result = new DomRepresentation();

    // Ensure pretty printing
    result.setIndenting(true);

    // Retrieve the DOM document to populate
    Document doc = result.getDocument();

    // Append the root node
    Node mailElt = doc.createElement("mail");
    doc.appendChild(mailElt);

    // Append the child nodes and set their text content
    Node statusElt = doc.createElement("status");
    statusElt.setTextContent("received");
    mailElt.appendChild(statusElt);

    Node subjectElt = doc.createElement("subject");
    subjectElt.setTextContent("Message to self");
    mailElt.appendChild(subjectElt);

    Node contentElt = doc.createElement("content");
    contentElt.setTextContent("Doh!");
    mailElt.appendChild(contentElt);

    Node accountRefElt = doc.createElement("accountRef");
    accountRefElt.setTextContent(new Reference(getReference(), "..").getTargetRef().toString());
    mailElt.appendChild(accountRefElt);
    return result;
  }