public IXArchElement cloneElement(int depth) {
    synchronized (DOMUtils.getDOMLock(elt)) {
      Document doc = elt.getOwnerDocument();
      if (depth == 0) {
        Element cloneElt = (Element) elt.cloneNode(false);
        cloneElt = (Element) doc.importNode(cloneElt, true);
        AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt);
        cloneImpl.setXArch(getXArch());
        return cloneImpl;
      } else if (depth == 1) {
        Element cloneElt = (Element) elt.cloneNode(false);
        cloneElt = (Element) doc.importNode(cloneElt, true);
        AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt);
        cloneImpl.setXArch(getXArch());

        NodeList nl = elt.getChildNodes();
        int size = nl.getLength();
        for (int i = 0; i < size; i++) {
          Node n = nl.item(i);
          Node cloneNode = (Node) n.cloneNode(false);
          cloneNode = doc.importNode(cloneNode, true);
          cloneElt.appendChild(cloneNode);
        }
        return cloneImpl;
      } else /* depth = infinity */ {
        Element cloneElt = (Element) elt.cloneNode(true);
        cloneElt = (Element) doc.importNode(cloneElt, true);
        AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt);
        cloneImpl.setXArch(getXArch());
        return cloneImpl;
      }
    }
  }
  /**
   * Set a property of a resource to a value.
   *
   * @param name the property name
   * @param value the property value
   * @exception com.ibm.webdav.WebDAVException
   */
  public void setProperty(String name, Element value) throws WebDAVException {
    // load the properties
    Document propertiesDocument = resource.loadProperties();
    Element properties = propertiesDocument.getDocumentElement();
    String ns = value.getNamespaceURI();

    Element property = null;
    if (ns == null) {
      property = (Element) ((Element) properties).getElementsByTagName(value.getTagName()).item(0);
    } else {
      property = (Element) properties.getElementsByTagNameNS(ns, value.getLocalName()).item(0);
    }

    if (property != null) {
      try {
        properties.removeChild(property);
      } catch (DOMException exc) {
      }
    }

    properties.appendChild(propertiesDocument.importNode(value, true));

    // write out the properties
    resource.saveProperties(propertiesDocument);
  }
Beispiel #3
0
 /** @param eNewParent */
 public static void debugOutput(Element eNewParent) {
   try {
     Document d = XML.newDocument("test");
     d.getDocumentElement().appendChild(d.importNode(eNewParent, true));
     System.err.println(XML.saveString(d).replaceAll("(^(.|[\\n\\r])*<test>)|(</test>$)", ""));
   } catch (Exception e) {
   }
 }
Beispiel #4
0
 protected Element importElement(Element element) {
   Document document = getOwnerDocument();
   Document oldDocument = element.getOwnerDocument();
   if (!oldDocument.equals(document)) {
     return (Element) document.importNode(element, true);
   } else {
     return element;
   }
 }
 public Track add(Track track) {
   synchronized (this) {
     Track copy;
     if ((copy = getTrack(track)) == null) {
       copy = new Track((Element) doc.importNode(track.getElement(), false));
       docElt.appendChild(copy.getElement());
       tracks.add(copy);
       hash.put(copy.getKey(), copy);
     }
     return copy;
   }
 }
Beispiel #6
0
  /**
   * Processes curr node. Copies node to the target document if its is not a text node of index
   * entry element. Otherwise it process it and creates nodes with "prefix" in given "namespace_url"
   * from the parsed index entry text.
   *
   * @param theNode node to process
   * @param theTargetDocument target document used to import and create nodes
   * @param theIndexEntryFoundListener listener to notify that new index entry was found
   * @return the array of nodes after processing input node
   */
  private Node[] processCurrNode(
      final Node theNode,
      final Document theTargetDocument,
      final IndexEntryFoundListener theIndexEntryFoundListener) {
    final NodeList childNodes = theNode.getChildNodes();

    if (checkElementName(theNode)) {
      return processIndexNode(theNode, theTargetDocument, theIndexEntryFoundListener);
    } else {
      final Node result = theTargetDocument.importNode(theNode, false);
      for (int i = 0; i < childNodes.getLength(); i++) {
        final Node[] processedNodes =
            processCurrNode(childNodes.item(i), theTargetDocument, theIndexEntryFoundListener);
        for (final Node node : processedNodes) {
          result.appendChild(node);
        }
      }
      return new Node[] {result};
    }
  }
Beispiel #7
0
  /**
   * Constructs an overview-node in the pre-html where all steps are described. Also, information
   * about valid and non-valid form-schema's are placed in the steps-overview.
   *
   * <p>The node looks like this:
   *
   * <pre>
   * &lt;steps-validator valid="false" allowsave="false" allowcancel="true"&gt;
   *      &lt;step form-schema="schema-id" valid="true" /&gt;
   *      &lt;step form-schema="schema-id" valid="false" /&gt;
   * &lt;/steps-validator&gt;
   * </pre>
   *
   * THis method creates a steps-overview which can be used by the html to show what forms are valid
   * and what are not.
   *
   * @param prehtml the prehtml data node
   * @param schema the original wizardschema
   */
  public static void createStepsOverview(Document prehtml, Document schema) {

    // remove a "steps-validator" node if it exists.
    Node overview = Utils.selectSingleNode(prehtml, "/*/steps-overview");
    if (overview != null) prehtml.getDocumentElement().removeChild(overview);

    // create new overview node
    overview = prehtml.createElement("steps-validator");
    Utils.setAttribute(overview, "allowcancel", "true");

    int invalidforms = 0;

    // iterate through all defined steps
    NodeList steps = Utils.selectNodeList(schema, "/*/steps/step");
    for (int i = 0; i < steps.getLength(); i++) {
      Node step = steps.item(i);
      String schemaid = Utils.getAttribute(step, "form-schema", "");
      if (!schemaid.equals("")) {
        // find the referred form and check if the form is valid.
        Node form = Utils.selectSingleNode(prehtml, "/*/form[@id='" + schemaid + "']");
        if (form != null) {
          Node validationerror = Utils.selectSingleNode(form, ".//field/validator[@valid='false']");

          boolean valid = (validationerror == null);
          // copy step information to overview node and store validation results.
          Node newstep = prehtml.importNode(step.cloneNode(true), true);
          overview.appendChild(newstep);
          Utils.setAttribute(newstep, "valid", valid + "");
          if (!valid) invalidforms++;
        }
      }
    }

    // store global information about validationresults
    Utils.setAttribute(overview, "allowsave", (invalidforms == 0) + "");
    Utils.setAttribute(overview, "valid", (invalidforms == 0) + "");

    // store new overview node in the prehtml.
    prehtml.getDocumentElement().appendChild(overview);
  }
  @Override
  public String executeAlgorithm(
      NetPlan netPlan,
      Map<String, String> algorithmParameters,
      Map<String, String> net2planParameters) {

    List<Integer> parameters = new ArrayList<Integer>();

    final int maxParameters = 5;
    final int traffic[] = {1, 2, 8, 32, 80};

    for (int i = 0; i < maxParameters; i++) {
      String path = algorithmParameters.get("trafficMatrix" + (i + 1));
      File f = new File(path);
      if (f.exists()) parameters.add(i);
    }

    // check parameters.size()> 0
    if (parameters.size() == 0) {
      throw new Net2PlanException("Must have matrices to add");
    }

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
      Document doc1 =
          factory
              .newDocumentBuilder()
              .parse(new File(algorithmParameters.get("trafficMatrix" + (parameters.get(0) + 1))));
      NodeList list = doc1.getElementsByTagName("layer");
      Element element = (Element) list.item(0);
      int max_id = -1;

      NodeList entrylist = doc1.getElementsByTagName("demand");
      for (int i = 0; i < entrylist.getLength(); i++) {
        Node n = entrylist.item(i);
        String id_string = n.getAttributes().getNamedItem("id").getNodeValue();
        int id_int = Integer.parseInt(id_string);
        max_id = Math.max(max_id, id_int);
        String offeredTraffic_string =
            n.getAttributes().getNamedItem("offeredTraffic").getNodeValue();
        double offeredTraffic_int =
            Double.parseDouble(offeredTraffic_string) * traffic[parameters.get(0)];
        ((Element) n).setAttribute("offeredTraffic", ((Double) offeredTraffic_int).toString());
        Element attribute = doc1.createElement("attribute");
        attribute.setAttribute("key", "ODU");
        attribute.setAttribute("value", "" + parameters.get(0));
        n.appendChild(attribute);
      }
      max_id++;

      for (int k = 1; k < parameters.size(); k++) {
        Document doc =
            factory
                .newDocumentBuilder()
                .parse(
                    new File(algorithmParameters.get("trafficMatrix" + (parameters.get(k) + 1))));
        entrylist = doc.getElementsByTagName("demand");

        // Add demands from ODU matrix
        for (int i = 0; i < entrylist.getLength(); i++) {

          Node n = doc1.importNode(entrylist.item(i), false);
          ((Element) n).setAttribute("id", ((Integer) max_id).toString());
          String offeredTraffic_string =
              n.getAttributes().getNamedItem("offeredTraffic").getNodeValue();
          double offeredTraffic_int =
              Double.parseDouble(offeredTraffic_string) * traffic[parameters.get(k)];
          ((Element) n).setAttribute("offeredTraffic", ((Double) offeredTraffic_int).toString());
          Element attribute = doc1.createElement("attribute");
          attribute.setAttribute("key", "ODU");
          attribute.setAttribute("value", "" + parameters.get(k));
          max_id++;
          element.appendChild(n);
          n.appendChild(attribute);
        }
      }

      // Create matrix with demands
      Transformer t = TransformerFactory.newInstance().newTransformer();
      Result ouput = new StreamResult(new File(algorithmParameters.get("trafficMatrix6")));
      t.setOutputProperty(OutputKeys.INDENT, "yes");

      t.transform(new DOMSource(doc1), ouput);

    } catch (Throwable t) {
      t.printStackTrace();
    }

    return "Ok!";
  }
Beispiel #9
0
 public XML addChild(XML child) {
   Document document = node.getOwnerDocument();
   Node newChild = document.importNode((Node) child.getNative(), true);
   return appendChild(newChild);
 }
Beispiel #10
0
 private void appendNodes(Document doc, Node target, NodeList nodes) {
   for (int i = 0; i < nodes.getLength(); i++) {
     Node node = nodes.item(i);
     target.appendChild(doc.importNode(node, true));
   }
 }
Beispiel #11
0
  /**
   * Creates nodes from index entries
   *
   * @param theIndexEntries index entries
   * @param theTargetDocument target document
   * @param theIndexEntryComparator comparator to sort the index entries. if it is null the index
   *     entries will be unsorted
   * @return nodes for the target document
   */
  private Node[] transformToNodes(
      final IndexEntry[] theIndexEntries,
      final Document theTargetDocument,
      final Comparator<IndexEntry> theIndexEntryComparator) {
    if (null != theIndexEntryComparator) {
      Arrays.sort(theIndexEntries, theIndexEntryComparator);
    }

    final List<Element> result = new ArrayList<Element>();
    for (final IndexEntry indexEntry : theIndexEntries) {
      final Element indexEntryNode = createElement(theTargetDocument, "index.entry");

      final Element formattedStringElement = createElement(theTargetDocument, "formatted-value");
      if (indexEntry.getContents() != null) {
        for (final Iterator<Node> i = indexEntry.getContents().iterator(); i.hasNext(); ) {
          final Node child = i.next();
          final Node clone = theTargetDocument.importNode(child, true);
          if (!i.hasNext() && clone.getNodeType() == Node.TEXT_NODE) {
            final Text t = (Text) clone;
            t.setData(t.getData().replaceAll("[\\s\\n]+$", ""));
          }
          formattedStringElement.appendChild(clone);
        }
      } else {
        final Text textNode = theTargetDocument.createTextNode(indexEntry.getFormattedString());
        textNode.normalize();
        formattedStringElement.appendChild(textNode);
      }
      indexEntryNode.appendChild(formattedStringElement);

      final String[] refIDs = indexEntry.getRefIDs();
      for (final String refID : refIDs) {
        final Element referenceIDElement = createElement(theTargetDocument, "refID");
        referenceIDElement.setAttribute("value", refID);
        indexEntryNode.appendChild(referenceIDElement);
      }

      final String val = indexEntry.getValue();
      if (null != val) {
        indexEntryNode.setAttribute("value", val);
      }

      final String sort = indexEntry.getSortString();
      if (null != sort) {
        indexEntryNode.setAttribute("sort-string", sort);
      }

      if (indexEntry.isStartingRange()) {
        indexEntryNode.setAttribute("start-range", "true");
      } else if (indexEntry.isEndingRange()) {
        indexEntryNode.setAttribute("end-range", "true");
      }
      if (indexEntry.isSuppressesThePageNumber()) {
        indexEntryNode.setAttribute("no-page", "true");
      } else if (indexEntry.isRestoresPageNumber()) {
        indexEntryNode.setAttribute("single-page", "true");
      }

      final IndexEntry[] childIndexEntries = indexEntry.getChildIndexEntries();

      final Node[] nodes =
          transformToNodes(childIndexEntries, theTargetDocument, theIndexEntryComparator);

      for (final Node node : nodes) {
        indexEntryNode.appendChild(node);
      }

      final IndexEntry[] seeChildIndexEntries = indexEntry.getSeeChildIndexEntries();
      if (seeChildIndexEntries != null) {
        final Element seeElement = createElement(theTargetDocument, "see-childs");
        final Node[] seeNodes =
            transformToNodes(seeChildIndexEntries, theTargetDocument, theIndexEntryComparator);
        for (final Node node : seeNodes) {
          seeElement.appendChild(node);
        }

        indexEntryNode.appendChild(seeElement);
      }

      final IndexEntry[] seeAlsoChildIndexEntries = indexEntry.getSeeAlsoChildIndexEntries();
      if (seeAlsoChildIndexEntries != null) {
        final Element seeAlsoElement = createElement(theTargetDocument, "see-also-childs");
        final Node[] seeAlsoNodes =
            transformToNodes(seeAlsoChildIndexEntries, theTargetDocument, theIndexEntryComparator);
        for (final Node node : seeAlsoNodes) {
          seeAlsoElement.appendChild(node);
        }

        indexEntryNode.appendChild(seeAlsoElement);
      }

      result.add(indexEntryNode);
    }
    return (Node[]) result.toArray(new Node[result.size()]);
  }
  /**
   * Edit the properties of a resource. The updates must refer to a Document containing a WebDAV
   * propertyupdates element as the document root.
   *
   * @param updates an XML Document containing propertyupdate elements
   * @return the result of making the updates describing the edits to be made.
   * @exception com.ibm.webdav.WebDAVException
   */
  public MultiStatus setProperties(Document propertyUpdates) throws WebDAVException {
    // create a MultiStatus to hold the results. It will hold a MethodResponse
    // for each update, and one for the method as a whole
    MultiStatus multiStatus = new MultiStatus();
    boolean errorsOccurred = false;

    // first, load the properties so they can be edited
    Document propertiesDocument = resource.loadProperties();
    Element properties = (Element) propertiesDocument.getDocumentElement();

    // be sure the updates have at least one update
    Element propertyupdate = (Element) propertyUpdates.getDocumentElement();
    String tagName = propertyupdate.getNamespaceURI() + propertyupdate.getLocalName();

    if (!tagName.equals("DAV:propertyupdate")) {
      throw new WebDAVException(
          WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "missing propertyupdate element");
    }

    NodeList updates = propertyupdate.getChildNodes();

    if (updates.getLength() == 0) {
      throw new WebDAVException(WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no updates in request");
    }

    Vector propsGood = new Vector(); // a list of properties that

    // were patched correctly or would have been if another
    // property hadn't gone bad.
    // apply the updates
    Node temp = null;

    for (int i = 0; i < updates.getLength(); i++) {
      temp = updates.item(i);

      // skip any ignorable TXText elements
      if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
        continue;
      }

      Element update = (Element) temp;
      int updateCommand = -1;
      tagName = update.getNamespaceURI() + update.getLocalName();

      if (tagName.equals("DAV:set")) {
        updateCommand = set;
      } else if (tagName.equals("DAV:remove")) {
        updateCommand = remove;
      } else {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY,
            update.getTagName() + " is not a valid property update request");
      }

      // iterate through the props in the set or remove element and update the
      // properties as directed
      Element prop = (Element) update.getElementsByTagNameNS("DAV:", "prop").item(0);

      if (prop == null) {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no propeprties in update request");
      }

      NodeList propsToUpdate = prop.getChildNodes();

      for (int j = 0; j < propsToUpdate.getLength(); j++) {
        temp = propsToUpdate.item(j);

        // skip any TXText elements??
        if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
          continue;
        }

        Element propToUpdate = (Element) temp;

        // find the property in the properties element
        Element property = null;
        PropertyName propertyName = new PropertyName(propToUpdate);

        if (((Element) propToUpdate).getNamespaceURI() != null) {
          property =
              (Element)
                  properties
                      .getElementsByTagNameNS(
                          propToUpdate.getNamespaceURI(), propToUpdate.getLocalName())
                      .item(0);
        } else {
          property = (Element) properties.getElementsByTagName(propToUpdate.getTagName()).item(0);
        }

        boolean liveone = isLive(propertyName.asExpandedString());

        if (liveone) {
          errorsOccurred = true;

          PropertyResponse response = new PropertyResponse(resource.getURL().toString());
          response.addProperty(propertyName, propToUpdate, WebDAVStatus.SC_FORBIDDEN);
          multiStatus.addResponse(response);
        }

        // do the update
        if (updateCommand == set) {
          if (property != null) {
            try {
              properties.removeChild(property);
            } catch (DOMException exc) {
            }
          }

          if (!liveone) {
            // I don't think we're allowed to update live properties
            //    here.  Doing so effects the cache.  A case in
            //    point is the lockdiscoveryproperty.  properties
            //    is actually the properites cache "document" of this
            //    resource.  Even though we don't "save" the request
            //    if it includes live properties, we don't remove
            //    it from the cache after we'd set it here, so it
            //    can affect other queries. (jlc 991002)
            properties.appendChild(propertiesDocument.importNode(propToUpdate, true));

            propsGood.addElement(propToUpdate);
          }
        } else if (updateCommand == remove) {
          try {
            if (property != null) {
              properties.removeChild(property);
              propsGood.addElement(propToUpdate);
            }
          } catch (DOMException exc) {
          }
        }
      }
    }

    {
      Enumeration els = propsGood.elements();

      for (; els.hasMoreElements(); ) {
        Object ob1 = els.nextElement();
        Element elProp = (Element) ob1;
        PropertyName pn = new PropertyName(elProp);
        PropertyResponse response = new PropertyResponse(resource.getURL().toString());
        response.addProperty(
            pn,
            (Element) elProp.cloneNode(false),
            (errorsOccurred ? WebDAVStatus.SC_FAILED_DEPENDENCY : WebDAVStatus.SC_OK));

        // todo: add code for responsedescription
        multiStatus.addResponse(response);
      }
    }

    // write out the properties
    if (!errorsOccurred) {
      resource.saveProperties(propertiesDocument);
    }

    return multiStatus;
  }