示例#1
0
  public String createDrawingXML(String drawing) {
    try {
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

      Document doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("message");

      rootElement.setAttribute("drawing", drawing);
      rootElement.setAttribute("user", user);
      rootElement.setAttribute("cmd", "create");

      doc.appendChild(rootElement);

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      StringWriter writer = new StringWriter();
      transformer.transform(new DOMSource(doc), new StreamResult(writer));
      String xml = writer.getBuffer().toString().replaceAll("\n|\r", "");

      postData(xml);

      return null;
    } catch (ParserConfigurationException ex) {
      Logger.getLogger(XMLManager.class.getName()).log(Level.SEVERE, null, ex);
      return null;
    } catch (TransformerConfigurationException ex) {
      Logger.getLogger(XMLManager.class.getName()).log(Level.SEVERE, null, ex);
      return null;
    } catch (TransformerException ex) {
      Logger.getLogger(XMLManager.class.getName()).log(Level.SEVERE, null, ex);
      return null;
    }
  }
示例#2
0
  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();
    }
  }
示例#3
0
    /** Turns a List<CubicCurve2D.Float> into a SVG Element representing a sketch of that spline. */
    Element splineToSketch(SVGDocument document, List<CubicCurve2D.Float> spline) {
      String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;

      // <g> is an SVG group
      // TODO: add a random(ish) rotation to the group
      Element group = document.createElementNS(svgNS, "g");

      // For each curve in the path, draw along it using a "brush".  In
      // our case the brush is a simple circle, but this could be changed
      // to something more advanced.
      for (CubicCurve2D.Float curve : spline) {
        // TODO: magic number & step in loop guard
        for (double i = 0.0; i <= 1.0; i += 0.01) {
          Point2D result = evalParametric(curve, i);

          // Add random jitter at some random positive or negative
          // distance along the unit normal to the tangent of the
          // curve
          Point2D n = vectorUnitNormal(evalParametricTangent(curve, i));
          float dx = (float) ((Math.random() - 0.5) * n.getX());
          float dy = (float) ((Math.random() - 0.5) * n.getY());

          Element brush = document.createElementNS(svgNS, "circle");
          brush.setAttribute("cx", Double.toString(result.getX() + dx));
          brush.setAttribute("cy", Double.toString(result.getY() + dy));
          // TODO: magic number for circle radius
          brush.setAttribute("r", Double.toString(1.0));
          brush.setAttribute("fill", "green");
          brush.setAttributeNS(null, "z-index", Integer.toString(zOrder.CONTOUR.ordinal()));
          group.appendChild(brush);
        }
      }

      return group;
    }
  private static void exportThisSeries(
      String name,
      String target_sea_state_datum,
      NamedList thisList,
      String[] sea_state_headings,
      Element itt,
      Document doc) {
    // ok, put us into the element
    org.w3c.dom.Element datum = doc.createElement(target_sea_state_datum);

    datum.setAttribute("Type", name);

    // and step through its values
    Collection<Double> indices = thisList.getValues();
    int ctr = 0;
    for (Iterator<Double> iter = indices.iterator(); iter.hasNext(); ) {
      Double val = (Double) iter.next();
      if (val != null) {
        datum.setAttribute(sea_state_headings[ctr], writeThis(val.doubleValue()));
        ctr++;
      } else break;
    }

    itt.appendChild(datum);
  }
示例#5
0
  @Override
  public Element export(ExportSupport support) throws IOException {
    Element layerEl = support.createElement("layer");
    layerEl.setAttribute("type", "osm-data");
    layerEl.setAttribute("version", "0.1");

    Element file = support.createElement("file");
    layerEl.appendChild(file);

    if (requiresZip()) {
      String zipPath = "layers/" + String.format("%02d", support.getLayerIndex()) + "/data.osm";
      file.appendChild(support.createTextNode(zipPath));
      addDataFile(support.getOutputStreamZip(zipPath));
    } else {
      URI uri = layer.getAssociatedFile().toURI();
      URL url = null;
      try {
        url = uri.toURL();
      } catch (MalformedURLException e) {
        throw new IOException(e);
      }
      file.appendChild(support.createTextNode(url.toString()));
    }
    return layerEl;
  }
示例#6
0
 public Element toXML() {
   Element e = super.toXML();
   if (value != null) e.setAttribute("value", value.toString());
   if (defaultValue != null) e.setAttribute("defaultValue", defaultValue.toString());
   e.setAttribute("className", "org.rosuda.deducer.widgets.param.ParamNumeric");
   return e;
 }
示例#7
0
  void _serializeString(String key, String value) {
    NodeList elements = stringElements.getElementsByTagName(ENTRY_FLAG);

    final int size = elements.getLength();

    for (int i = 0; i < size; ++i) {
      Element e = (Element) elements.item(i);
      Attr nameAttr = e.getAttributeNode(KEY_FLAG);
      if (nameAttr == null) {
        throw newMalformedKeyAttrException(Repository.STRING);
      }
      if (key.equals(nameAttr.getValue())) {
        Attr valueAttr = e.getAttributeNode(VALUE_FLAG);
        if (valueAttr == null) {
          throw newMalformedValueAttrException(key, Repository.STRING);
        }
        valueAttr.setValue(value);
        return;
      }
    }

    // no existing element found
    Element element = xmlDoc.createElement(ENTRY_FLAG);
    element.setAttribute(KEY_FLAG, key);
    element.setAttribute(VALUE_FLAG, value);
    stringElements.appendChild(element);
  }
  private void processPlugin(final Element root, final ArtifactInformation a) {
    if (!Helper.isBundle(a.getMetaData())) {
      return;
    }

    final String id =
        a.getMetaData().get(new MetaKey(OsgiExtractor.NAMESPACE, OsgiExtractor.KEY_NAME));
    final String version =
        a.getMetaData().get(new MetaKey(OsgiExtractor.NAMESPACE, OsgiExtractor.KEY_VERSION));
    if (id == null || version == null) {
      return;
    }

    boolean unpack = false;

    try {
      final String biString =
          a.getMetaData()
              .get(new MetaKey(OsgiExtractor.NAMESPACE, OsgiExtractor.KEY_BUNDLE_INFORMATION));
      final BundleInformation bi = BundleInformation.fromJson(biString);
      unpack = "dir".equals(bi.getEclipseBundleShape());
    } catch (final Exception e) {
    }

    final Element p = root.getOwnerDocument().createElement("plugin");
    root.appendChild(p);

    p.setAttribute("id", id);
    p.setAttribute("version", version);
    p.setAttribute("unpack", "" + unpack);
  }
示例#9
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);
    }
  }
示例#10
0
 @Override
 public final Element put(final Element parentElement, final Object value) {
   Element newElement = document.createElementNS(XMLNS_ITEM, parentElement.getLocalName());
   if (value == null) {
     newElement.setAttribute("isNull", "yes");
     return newElement;
   }
   Map<String, Object> attributes = XmlHelper.extractAttributes(value);
   for (String key : attributes.keySet()) {
     try {
       newElement.setAttribute(key, attributes.get(key).toString());
     } catch (Exception e) {
       // XXX: ignore exceptions silenty
     }
   }
   Map<String, Collection<?>> collections = XmlHelper.extractCollections(value);
   for (String key : collections.keySet()) {
     try {
       Element container = document.createElementNS(XMLNS_DATA, key);
       newElement.appendChild(container);
       for (Object item : collections.get(key)) {
         put(container, item);
       }
     } catch (Exception e) {
       // XXX: ignore exceptions silenty
     }
   }
   newElement.appendChild(document.createTextNode(value.toString()));
   parentElement.appendChild(newElement);
   return newElement;
 }
示例#11
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;
  }
示例#12
0
  /**
   * generated <code><col><code> tags.
   * @param sheet
   * @param table container.
   */
  private void generateColumns(XSSFSheet sheet, Element table) {
    List<CTCols> colsList = sheet.getCTWorksheet().getColsList();
    MathContext mc = new MathContext(3);
    for (CTCols cols : colsList) {
      long oldLevel = 1;
      for (CTCol col : cols.getColArray()) {
        while (true) {
          if (oldLevel == col.getMin()) {
            break;
          }
          Element column = htmlDocumentFacade.createTableColumn();
          //					htmlDocumentFacade.addStyleClass(column, "col", "width:2cm;");
          column.setAttribute("style", "width:2cm;");
          table.appendChild(column);
          oldLevel++;
        }
        Element column = htmlDocumentFacade.createTableColumn();
        String width =
            new BigDecimal(sheet.getColumnWidth(Long.bitCount(oldLevel)) / 1440.0, mc).toString();
        column.setAttribute("style", "width:".concat(width).concat("cm;"));
        table.appendChild(column);

        oldLevel++;
      }
    }
  }
示例#13
0
  private void processSheet(Element container, XSSFSheet sheet) {

    Element table = htmlDocumentFacade.createTable();
    int sIndex = sheet.getWorkbook().getSheetIndex(sheet);
    String sId = "sheet_".concat(String.valueOf(sIndex));
    table.setAttribute("id", sId);
    table.setAttribute("border", "1");
    table.setAttribute("cellpadding", "2");
    table.setAttribute("cellspacing", "0");
    table.setAttribute("style", "border-collapse: collapse;");

    css.append("#")
        .append(sId)
        .append(" tr{height:")
        .append(sheet.getDefaultRowHeightInPoints() / 28.34)
        .append("cm}\n");
    css.append("#")
        .append(sId)
        .append(" td{width:")
        .append(sheet.getDefaultColumnWidth() * 0.21)
        .append("cm}\n");

    // cols
    generateColumns(sheet, table);

    // rows
    Iterator<Row> rows = sheet.iterator();
    while (rows.hasNext()) {
      Row row = rows.next();
      if (row instanceof XSSFRow) processRow(table, (XSSFRow) row, sheet);
    }

    container.appendChild(table);
  }
示例#14
0
 /*
  * If the element contains an attribute 'makeOnly' with a value of 'true',
  * create a child element before any existing children which will display a node
  * which will display only the elements records.
  * Compute the query attribute, which is the appended result of all of the children
  * appended to this element name. If noQuery=true. then do not generate a query term
  * for this element.
  */
 String computeQuery(Element e) {
   String query = "";
   if (!(e.getAttribute("noQuery").equalsIgnoreCase("true"))) {
     query = e.getAttribute("name");
   }
   String makeOnly = e.getAttribute("makeOnly");
   boolean madeOnly = false;
   NodeList children = e.getChildNodes();
   for (int i = 0; i < children.getLength(); i++) {
     Node child = children.item(i);
     if (child.getNodeType() == Node.ELEMENT_NODE) {
       if (makeOnly.equalsIgnoreCase("true") && !madeOnly) {
         // need to make an ...-Only node and populate it
         String onlyTagName = e.getTagName() + "-Only";
         Element only = ((Document) dom.getNode()).createElement(onlyTagName);
         only.setAttribute("name", e.getAttribute("name") + "-Only");
         only.setAttribute("query", e.getAttribute("name"));
         e.insertBefore(only, child);
         i++;
         madeOnly = true;
       }
       if (query.length() > 0) {
         query += ",";
       }
       query += computeQuery((Element) child);
     }
   }
   log.info("setting query for " + e.getNodeName() + "   " + query);
   e.setAttribute("query", query);
   return query;
 }
  private void formatError(String type, Test test, Throwable t) {
    if (test != null) {
      endTest(test);
      failedTests.put(test, test);
    }

    Element nested = doc.createElement(type);
    Element currentTest = null;
    if (test != null) {
      currentTest = (Element) testElements.get(test);
    } else {
      currentTest = rootElement;
    }

    currentTest.appendChild(nested);

    String message = t.getMessage();
    if (message != null && message.length() > 0) {
      nested.setAttribute(ATTR_MESSAGE, t.getMessage());
    }
    nested.setAttribute(ATTR_TYPE, t.getClass().getName());

    String strace = JUnitTestRunner.getFilteredTrace(t);
    Text trace = doc.createTextNode(strace);
    nested.appendChild(trace);
  }
示例#16
0
文件: Jelly.java 项目: alwold/jelly
 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;
 }
示例#17
0
  public Node convertToXML(Document parent) {
    Element targetNode = parent.createElement(ELEMENT_NAME);
    if (ident != null) targetNode.setAttribute(ATTRIBUTE_IDENT, ident);
    if (decoy != null) targetNode.setAttribute(ATTRIBUTE_DECOY, decoy);
    if (networkInterface != null) targetNode.setAttribute(ATTRIBUTE_INTERFACE, networkInterface);

    if (node != null) {
      Node nodeNode = node.convertToXML(parent);
      targetNode.appendChild(nodeNode);
    }
    if (user != null) {
      Node userNode = user.convertToXML(parent);
      targetNode.appendChild(userNode);
    }
    if (process != null) {
      Node processNode = process.convertToXML(parent);
      targetNode.appendChild(processNode);
    }
    if (service != null) {
      Node serviceNode = service.convertToXML(parent);
      targetNode.appendChild(serviceNode);
    }
    if (fileList != null) {
      targetNode.appendChild(fileList.convertToXML(parent));
    }

    return targetNode;
  }
示例#18
0
 /**
  * Convert an item in the Segment relation into XML, inserting it at the specified location in the
  * XML tree.
  *
  * @param deep whether to create a deep structure of <syllable> and <ph> elements or not.
  */
 protected String insertSegment(Item segmentItem, Element syllable, boolean deep) {
   // allow for syllable == null if not deep:
   if (segmentItem == null || deep && syllable == null) {
     throw new NullPointerException("Null arguments to insertSegment()");
   }
   if (deep && !syllable.getTagName().equals(MaryXML.SYLLABLE)) {
     throw new IllegalArgumentException("Segments can only be inserted in <syllable> elements");
   }
   String segmentString = segmentItem.toString();
   Voice maryVoice = FreeTTSVoices.getMaryVoice(segmentItem.getUtterance().getVoice());
   if (deep) {
     Document doc = syllable.getOwnerDocument();
     Element segment = MaryXML.createElement(doc, MaryXML.PHONE);
     syllable.appendChild(segment);
     segment.setAttribute("p", segmentString);
     if (segmentItem.getFeatures().isPresent("end")) {
       float endInSeconds = segmentItem.getFeatures().getFloat("end");
       int endInMillis = (int) (1000 * endInSeconds);
       segment.setAttribute("end", String.valueOf(endInMillis));
     }
     if (segmentItem.getFeatures().isPresent("mbr_dur")) {
       int mbrDur = segmentItem.getFeatures().getInt("mbr_dur");
       segment.setAttribute("d", String.valueOf(mbrDur));
     }
     if (segmentItem.getFeatures().isPresent("mbr_targets")) {
       String mbrTargets = segmentItem.getFeatures().getString("mbr_targets");
       if (!mbrTargets.equals("")) {
         segment.setAttribute("f0", mbrTargets);
       }
     }
   }
   return segmentString;
 }
示例#19
0
  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);
  }
示例#20
0
  /**
   * Creates a SignatureRequest document element.
   *
   * @param document
   * @param details
   * @return
   */
  private Element createSignatureRequestElement(
      Document document, ObjectAndSignatureRequestDetails details) {
    SignatureRequest request = details.signatureRequest;

    Element requestElem = document.createElement("SignatureRequest");
    requestElem.setAttribute("type", request.getSignatureType());
    requestElem.setAttribute("signed", String.valueOf(request.isSigned()));
    requestElem.appendChild(
        createObjectElement(
            document, details.key, details.bucketName, details.metadata, "RequestObject"));

    if (request.isSigned()) {
      requestElem.appendChild(
          createObjectElement(
              document,
              request.getObjectKey(),
              request.getBucketName(),
              request.getObjectMetadata(),
              "SignedObject"));
      requestElem.appendChild(
          createPropertyElement(document, null, request.getSignedUrl(), "SignedURL"));
    } else if (request.getDeclineReason() != null) {
      requestElem.appendChild(
          createPropertyElement(document, null, request.getDeclineReason(), "DeclineReason"));
    }
    return requestElem;
  }
示例#21
0
  void _serializeNumber(String key, Number value) {
    NodeList elements = numberElements.getElementsByTagName(ENTRY_FLAG);

    final int size = elements.getLength();

    for (int i = 0; i < size; ++i) {
      Element e = (Element) elements.item(i);
      Attr nameAttr = e.getAttributeNode(KEY_FLAG);
      if (nameAttr == null) {
        throw newMalformedKeyAttrException(Repository.NUMBER);
      }
      if (key.equals(nameAttr.getValue())) {
        Attr valueAttr = e.getAttributeNode(VALUE_FLAG);
        if (valueAttr == null) {
          throw newMalformedValueAttrException(key, Repository.NUMBER);
        }
        Attr typeAttr = e.getAttributeNode(TYPE_FLAG);
        if (typeAttr == null) {
          throw newMalformedTypeAttrException(key, Repository.NUMBER);
        }
        typeAttr.setValue(Configs.resolveNumberType(value).name());
        valueAttr.setValue(value.toString());
        return;
      }
    }
    // no existing element found
    Element element = xmlDoc.createElement(ENTRY_FLAG);
    element.setAttribute(KEY_FLAG, key);
    element.setAttribute(VALUE_FLAG, value.toString());
    element.setAttribute(TYPE_FLAG, Configs.resolveNumberType(value).name());
    numberElements.appendChild(element);
  }
示例#22
0
  /**
   * Creates and element to contain information about an object.
   *
   * @param document
   * @param key
   * @param bucketName
   * @param metadata
   * @param elementName
   * @return
   */
  private Element createObjectElement(
      Document document, String key, String bucketName, Map metadata, String elementName) {
    if (key == null) {
      key = "";
    }
    if (bucketName == null) {
      bucketName = "";
    }

    Element objectElement = document.createElement(elementName);
    objectElement.setAttribute("key", key);
    objectElement.setAttribute("bucketName", bucketName);
    Iterator iter = metadata.entrySet().iterator();
    while (iter.hasNext()) {
      Map.Entry entry = (Map.Entry) iter.next();
      String metadataName = (String) entry.getKey();
      String metadataValue = (String) entry.getValue();

      if (metadataValue == null) {
        metadataValue = "";
      }
      objectElement.appendChild(
          createPropertyElement(document, metadataName, metadataValue, "Metadata"));
    }
    return objectElement;
  }
示例#23
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);
    }
  }
  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);
      }
    }
  }
  /**
   * @param monitor
   * @throws Exception
   */
  private void addServletToGwtXml(IProgressMonitor monitor) throws Exception {

    monitor = Util.getNonNullMonitor(monitor);

    try {

      monitor.beginTask("", 1);

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

      DocumentBuilder builder = factory.newDocumentBuilder();

      File moduleFile = getModuleFile();

      Document document = builder.parse(moduleFile);
      Node module = document.getDocumentElement();

      Element newServlet = document.createElement("servlet");
      newServlet.setAttribute("path", "/" + serviceUri); // $NON-NLS-2$
      newServlet.setAttribute(
          "class",
          getPackageFragment().getElementName() + '.' + getTypeName() + "Impl"); // $NON-NLS-2$

      module.appendChild(newServlet);

      Transformer writer = TransformerFactory.newInstance().newTransformer();

      writer.transform(new DOMSource(document), new StreamResult(moduleFile));

    } finally {
      monitor.done();
    }
  }
 /** The whole testsuite ended. */
 public void endTestSuite(JUnitTest suite) throws BuildException {
   rootElement.setAttribute(ATTR_TESTS, "" + suite.runCount());
   rootElement.setAttribute(ATTR_FAILURES, "" + suite.failureCount());
   rootElement.setAttribute(ATTR_ERRORS, "" + suite.errorCount());
   rootElement.setAttribute(ATTR_TIME, "" + (suite.getRunTime() / 1000.0));
   if (out != null) {
     Writer wri = null;
     try {
       wri = new BufferedWriter(new OutputStreamWriter(out, "UTF8"));
       wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
       (new DOMElementWriter()).write(rootElement, wri, 0, "  ");
       wri.flush();
     } catch (IOException exc) {
       throw new BuildException("Unable to write log file", exc);
     } finally {
       if (out != System.out && out != System.err) {
         if (wri != null) {
           try {
             wri.close();
           } catch (IOException e) {
             // ignore
           }
         }
       }
     }
   }
 }
  /**
   * Test adding a second md-record to ContentRelation. One md-record already exists.
   *
   * @throws Exception Thrown if adding one md-record failed.
   */
  @Test
  public void testAddMdRecord() throws Exception {

    // add one more md-record
    Document relationCreated = getDocument(relationXml);
    NodeList mdRecordsCreated =
        selectNodeList(relationCreated, "/content-relation/md-records/md-record");
    int numberMdRecordsCreated = mdRecordsCreated.getLength();
    Element mdRecord =
        relationCreated.createElementNS(
            "http://www.escidoc.de/schemas/metadatarecords/0.5",
            "escidocMetadataRecords:md-record");
    mdRecord.setAttribute("name", "md2");
    mdRecord.setAttribute("schema", "bla");
    Element mdRecordContent = relationCreated.createElement("md");
    mdRecord.appendChild(mdRecordContent);
    mdRecordContent.setTextContent("bla");
    selectSingleNode(relationCreated, "/content-relation/md-records").appendChild(mdRecord);
    String relationWithNewMdRecord = toString(relationCreated, false);

    String updatedXml = update(this.relationId, relationWithNewMdRecord);

    // check updated
    assertXmlValidContentRelation(updatedXml);
    Document updatedRelationDocument = getDocument(updatedXml);
    NodeList mdRecordsUpdated =
        selectNodeList(updatedRelationDocument, "/content-relation/md-records/md-record");
    int numberMdRecordsUpdated = mdRecordsUpdated.getLength();
    assertEquals(
        "the content relation should have one additional" + " md-record after update ",
        numberMdRecordsUpdated,
        numberMdRecordsCreated + 1);
  }
  /**
   * Interface TestListener.
   *
   * <p>A Test is finished.
   */
  public void endTest(Test test) {
    // Fix for bug #5637 - if a junit.extensions.TestSetup is
    // used and throws an exception during setUp then startTest
    // would never have been called
    if (!testStarts.containsKey(test)) {
      startTest(test);
    }

    Element currentTest = null;
    if (!failedTests.containsKey(test)) {
      currentTest = doc.createElement(TESTCASE);
      currentTest.setAttribute(ATTR_NAME, JUnitVersionHelper.getTestCaseName(test));
      // a TestSuite can contain Tests from multiple classes,
      // even tests with the same name - disambiguate them.
      currentTest.setAttribute(ATTR_CLASSNAME, test.getClass().getName());
      rootElement.appendChild(currentTest);
      testElements.put(test, currentTest);
    } else {
      currentTest = (Element) testElements.get(test);
    }

    Long l = (Long) testStarts.get(test);
    currentTest.setAttribute(
        ATTR_TIME, "" + ((System.currentTimeMillis() - l.longValue()) / 1000.0));
  }
示例#29
0
  protected boolean logUserStoreLogin(
      User user,
      AdminService admin,
      String remoteIP,
      String remoteHost,
      UserStoreKey userStoreKey) {

    try {
      Document doc = XMLTool.createDocument("logentry");
      Element rootElement = doc.getDocumentElement();
      // UserStoreKey userStoreKey = user.getUserStoreKey();
      if (userStoreKey != null) {
        rootElement.setAttribute("userstorekey", String.valueOf(userStoreKey));
      }
      rootElement.setAttribute("sitekey", String.valueOf(0));
      rootElement.setAttribute("typekey", String.valueOf(LogType.LOGIN_USERSTORE.asInteger()));
      rootElement.setAttribute("inetaddress", remoteIP);
      XMLTool.createElement(doc, rootElement, "data");

      admin.createLogEntries(user, XMLTool.documentToString(doc));
    } catch (VerticalSecurityException vse) {
      String message = "Failed to create log entry because of security error: %t";
      VerticalAdminLogger.error(this.getClass(), 1, message, vse);
      return false;
    }

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