Example #1
0
  protected static Document rootResourceXml(final String url) throws ParserConfigurationException {
    /*
     * <?xml version="1.0" encoding="UTF-8" ?> <Services> <TileMapService
     * title="MrGeo Tile Map Service" version="1.0.0"
     * href="http://localhost:8080/mrgeo-services/api/tms/1.0.0" /> </Services>
     */

    final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    final Document doc = docBuilder.newDocument();
    final Element rootElement = doc.createElement("Services");
    doc.appendChild(rootElement);
    final Element tms = doc.createElement("TileMapService");
    rootElement.appendChild(tms);
    final Attr title = doc.createAttribute("title");
    title.setValue("MrGeo Tile Map Service");
    tms.setAttributeNode(title);
    final Attr v = doc.createAttribute("version");
    v.setValue(VERSION);
    tms.setAttributeNode(v);
    final Attr href = doc.createAttribute("href");
    href.setValue(normalizeUrl(url) + "/" + VERSION);
    tms.setAttributeNode(href);

    return doc;
  }
  protected void transferAttributes(
      Element source, Element result, java.util.List nonTransferList) {
    boolean debug = false;
    NamedNodeMap sourceAttrNodeMap = source.getAttributes();
    if (sourceAttrNodeMap == null) return;

    NamedNodeMap resultAttrNodeMap = result.getAttributes();

    for (int index = 0; index < sourceAttrNodeMap.getLength(); index++) {
      Node sourceAttrNode = sourceAttrNodeMap.item(index);
      if (!this.canTransferAttribute(sourceAttrNode.getNodeName(), nonTransferList)) continue;
      if (!isValidAttributeToTransfer(
          sourceAttrNode.getNodeName(), getAttributeListForElement(result.getTagName()))) continue;
      if (resultAttrNodeMap == null) {
        Attr addAttr = result.getOwnerDocument().createAttribute(sourceAttrNode.getNodeName());
        addAttr.setValue(sourceAttrNode.getNodeValue());
        result.setAttributeNode(addAttr);
      } else {
        Node resultAttrNode = resultAttrNodeMap.getNamedItem(sourceAttrNode.getNodeName());
        if (resultAttrNode != null) {
          resultAttrNode.setNodeValue(sourceAttrNode.getNodeValue());
          // result.setAttributeNode((Attr)resultAttrNode);
        } else {
          Attr addAttr = result.getOwnerDocument().createAttribute(sourceAttrNode.getNodeName());
          addAttr.setValue(sourceAttrNode.getNodeValue());
          result.setAttributeNode(addAttr);
        }
      }
    }
  }
Example #3
0
 public static void updateGmlIDs(final Node node, final String gmlID, String oldGmlID) {
   // check this node's attributes
   if (node != null) {
     final String nodeNamespace = node.getNamespaceURI();
     final NamedNodeMap attributes = node.getAttributes();
     if (attributes != null) {
       for (int i = 0, len = attributes.getLength(); i < len; i++) {
         final Attr attr = (Attr) attributes.item(i);
         if (attr.getLocalName().equals(GmlConstants.AN_ID)) {
           if (checkAttributeForGmlId(attr, nodeNamespace)) {
             if (oldGmlID == null) {
               oldGmlID = attr.getValue();
               attr.setValue((gmlID));
             } else {
               String helperString = attr.getValue();
               helperString = helperString.replace(oldGmlID, gmlID);
               attr.setValue(helperString);
             }
           }
         }
       }
       // recurse this node's children
       final NodeList children = node.getChildNodes();
       if (children != null) {
         for (int i = 0, len = children.getLength(); i < len; i++) {
           updateGmlIDs(children.item(i), gmlID, oldGmlID);
         }
       }
     }
   }
 }
 /**
  * UserVectorのXML文書を追加します
  *
  * @param sID 送る側のID文字列
  * @param rID 受ける側のID文字列
  * @param serverRandom 16進表記の文字列
  * @return 追加されたDocumentクラスを返す
  * @author hiroki
  */
 private Document setPreSharedValues(String sID, String rID, String serverRandom) {
   try {
     // ルート要素からShareKeyのノードリストを取得
     NodeList uveclist = this.root.getElementsByTagName("userVector");
     Element uVector = (Element) uveclist.item(0);
     if (uVector == null) {
       // userVectorタグ作成
       uVector = this.document.createElement("userVector");
       // 属性ノードの作成
       Attr sIDtag = this.document.createAttribute("xmlns:SenderID");
       // 属性ノードの値
       sIDtag.setValue(sID);
       // 属性ノードを要素に追加
       uVector.setAttributeNode(sIDtag);
     }
     // 新規要素、PreSharedValueタグの作成
     Element user = this.document.createElement("PreSharedValue");
     // 属性ノードの作成
     Attr rIDtag = this.document.createAttribute("xmlns:RecieverID");
     // 属性ノードの値
     rIDtag.setValue(rID);
     // 属性ノードを要素に追加
     user.setAttributeNode(rIDtag);
     // PreSharedValueの計算
     user.appendChild(this.document.createTextNode(this.getHash(sID, rID, serverRandom)));
     // 親要素にPreSharedValueを追加
     uVector.appendChild(user);
     // XMLのルート要素に追加
     this.root.appendChild(uVector);
   } catch (Exception e) {
     e.printStackTrace();
   }
   return (this.document);
 }
Example #5
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);
  }
Example #6
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);
  }
Example #7
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);
  }
  public Document export(Document doc, Element root, Customer cus, List<CardBean> cards) {
    Element customer = doc.createElement("Kunde");
    root.appendChild(customer);

    Attr cusNum = doc.createAttribute("Kundennummer");
    cusNum.setValue(cus.getCustomernumber());
    customer.setAttributeNode(cusNum);

    Element cusName = doc.createElement("Name");
    cusName.appendChild(doc.createTextNode(cus.getName()));
    customer.appendChild(cusName);

    Iterator<CardBean> it = cards.iterator();
    while (it.hasNext()) {
      CardBean card = it.next();

      Element cusCard = doc.createElement("Karte");
      customer.appendChild(cusCard);

      Attr cardNum = doc.createAttribute("Kartennummer");
      cardNum.setValue(card.getCardNumber());
      cusCard.setAttributeNode(cardNum);

      Element telFirst = doc.createElement("Telefonnummer");
      telFirst.appendChild(doc.createTextNode(card.getPhoneString()));
      cusCard.appendChild(telFirst);
    }

    return doc;
  }
 // DOM output
 public void addPrefixDecl(Element element, String prefix, String uri) {
   if ("".equals(prefix)) {
     Document doc = element.getOwnerDocument();
     Attr attr = doc.createAttributeNS("http://www.w3.org/XML/2000/xmlns/", "xmlns");
     attr.setValue(uri);
     element.setAttributeNode(attr);
   } else {
     Document doc = element.getOwnerDocument();
     Attr attr = doc.createAttributeNS("http://www.w3.org/XML/2000/xmlns/", "xmlns:" + prefix);
     attr.setValue(uri);
     element.setAttributeNode(attr);
   }
 }
  protected void handleParent(Element e, NameSpaceSymbTable ns) {
    if (!e.hasAttributes() && e.getNamespaceURI() == null) {
      return;
    }
    xmlattrStack.push(-1);
    NamedNodeMap attrs = e.getAttributes();
    int attrsLength = attrs.getLength();
    for (int i = 0; i < attrsLength; i++) {
      Attr attribute = (Attr) attrs.item(i);
      String NName = attribute.getLocalName();
      String NValue = attribute.getNodeValue();

      if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
        if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
          ns.addMapping(NName, NValue, attribute);
        }
      } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) {
        xmlattrStack.addXmlnsAttr(attribute);
      }
    }
    if (e.getNamespaceURI() != null) {
      String NName = e.getPrefix();
      String NValue = e.getNamespaceURI();
      String Name;
      if (NName == null || NName.equals("")) {
        NName = "xmlns";
        Name = "xmlns";
      } else {
        Name = "xmlns:" + NName;
      }
      Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
      n.setValue(NValue);
      ns.addMapping(NName, NValue, n);
    }
  }
  /**
   * @param root
   * @param node
   */
  private void writeRecursive(org.w3c.dom.Node target, Node source) {
    Document owned = target.getOwnerDocument();
    if (owned == null) {
      owned = (Document) target;
    }
    org.w3c.dom.Node targetChild = null;
    if (source.text() != null) {
      targetChild = owned.createElement(source.name());
      targetChild.appendChild(owned.createTextNode(source.text()));
    } else {
      targetChild = owned.createElement(source.name());
    }

    target.appendChild(targetChild);

    for (Map.Entry<String, String> attribute : source.attributes().entrySet()) {
      Attr attr = owned.createAttribute(attribute.getKey());
      attr.setValue(attribute.getValue());

      targetChild.getAttributes().setNamedItem(attr);
    }
    for (Node sourceChild : source.children()) {
      writeRecursive(targetChild, sourceChild);
    }
  }
 private void addAttribute(Document doc, Element rootElement, String attrName, String attrValue) {
   if (doc != null && rootElement != null && attrName != null) {
     Attr attr = doc.createAttribute(attrName);
     attr.setValue(attrValue);
     rootElement.setAttributeNode(attr);
   }
 }
  /**
   * Creates 'wsu:Id' attribute for wsu:Timestamp needed for signature.
   *
   * @param message
   * @return
   * @throws ParserException
   */
  private String createTimestampUuid(SoapMessage message) throws ParserException {

    NodeList timestampList =
        message
            .getHeader()
            .getOwnerDocument()
            .getElementsByTagNameNS(WSU_NAMESPACE, WSU_TIMESTAMP_LOCAL_NAME);

    assert timestampList.getLength() <= 1;

    if (timestampList.getLength() == 1) {
      assert timestampList.item(0).getNodeType() == Node.ELEMENT_NODE;

      Element timestamp = (Element) timestampList.item(0);
      String timestampId = Util.randomNCNameUUID();

      Attr wsuId = timestamp.getOwnerDocument().createAttributeNS(WSU_NAMESPACE, WSU_ID_LOCAL_NAME);
      wsuId.setPrefix(timestamp.getPrefix());

      wsuId.setValue(timestampId);
      timestamp.setAttributeNodeNS(wsuId);
      timestamp.setIdAttributeNode(wsuId, true);

      log.trace("Created wsu:Id for wsu:Timestamp: " + timestampId);

      return timestampId;
    }

    log.trace("Timestamp element not found in the message");

    return null;
  }
Example #14
0
    void define(Node self, Document doc) throws ThinklabException {

      if (attrs != null)
        for (Pair<String, String> a : attrs) {
          Attr attr = doc.createAttribute(a.getFirst());
          attr.setValue(a.getSecond());
          ((Element) self).setAttributeNode(attr);
        }

      for (Object o : contents) {

        if (o instanceof String) {
          String text = (String) o;
          XMLDocument.setTextContent(doc, self, text);
        } else if (o instanceof Collection<?>) {
          for (Iterator<?> it = ((Collection<?>) o).iterator(); it.hasNext(); ) {
            Object no = it.next();
            if (no instanceof XmlNode) {
              self.appendChild(((XmlNode) no).create(self, doc));
            } else if (no instanceof Polylist) {
              self.appendChild(((Polylist) no).createXmlNode().create(self, doc));
            } else {
              throw new ThinklabValidationException(
                  "XML.node: collections must be of XmlNode or Polylist");
            }
          }
        } else if (o instanceof XmlNode) {
          self.appendChild(((XmlNode) o).create(self, doc));
        } else if (o instanceof Polylist) {
          self.appendChild(((Polylist) o).createXmlNode().create(self, doc));
        }
      }
    }
Example #15
0
    Node create(Node parent, Document doc) throws ThinklabException {

      Node ret = doc.createElement(tag);

      if (attrs != null)
        for (Pair<String, String> a : attrs) {
          Attr attr = doc.createAttribute(a.getFirst());
          attr.setValue(a.getSecond());
          ((Element) ret).setAttributeNode(attr);
        }

      for (Object o : contents) {

        if (o instanceof String) {
          String text = (String) o;
          XMLDocument.setTextContent(doc, ret, text);
        } else if (o instanceof Collection<?>) {
          for (Iterator<?> it = ((Collection<?>) o).iterator(); it.hasNext(); ) {
            Object no = it.next();
            if (!(no instanceof XmlNode)) {
              throw new ThinklabValidationException("XML.node: collections must be of XmlNode");
            }
            ret.appendChild(((XmlNode) no).create(ret, doc));
          }
        } else if (o instanceof XmlNode) {
          ret.appendChild(((XmlNode) o).create(ret, doc));
        }
      }

      return ret;
    }
Example #16
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);
  }
Example #17
0
  /**
   * Recurse through a node and its children and make all gml:ids unique
   *
   * @param node The node to examine
   */
  public static void makeGmlIdsUnique(final Node node, final Map<String, Integer> foundIds) {
    // check this node's attributes
    final NamedNodeMap attributes = node.getAttributes();
    final String nodeNamespace = node.getNamespaceURI();
    if (attributes != null) {
      for (int i = 0, len = attributes.getLength(); i < len; i++) {
        final Attr attr = (Attr) attributes.item(i);
        if (attr.getLocalName().equals(GmlConstants.AN_ID)) {
          if (checkAttributeForGmlId(attr, nodeNamespace)) {
            final String gmlId = attr.getValue();
            if (foundIds.containsKey(gmlId)) {
              /*
               * id has already been found, suffix this one with
               * the found count for this id
               */
              attr.setValue(gmlId + foundIds.get(gmlId));
              // increment the found count for this id
              foundIds.put(gmlId, foundIds.get(gmlId) + 1);
            } else {
              // id is new, add it to the foundIds map
              foundIds.put(gmlId, 1);
            }
          }
        }
      }
    }

    // recurse this node's children
    final NodeList children = node.getChildNodes();
    if (children != null) {
      for (int i = 0, len = children.getLength(); i < len; i++) {
        makeGmlIdsUnique(children.item(i), foundIds);
      }
    }
  }
  public void setName(String name) throws Exception {
    Attr attrNode =
        (Attr)
            this.getTemplateAttributes()
                .getNamedItem(TransformInfoObjectConfigData.getInstance().NAME);

    attrNode.setValue(name);
  }
Example #19
0
 public void setAttribute(String name, String value) throws DOMException {
   Attr attr = (Attr) attrs.getNamedItem(name);
   if (attr != null) {
     attr.setValue(value);
   } else {
     attrs.list.add(new IIOMetadataAttr(name, value, this));
   }
 }
Example #20
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {

      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

      // Создание корневого элемента
      Document doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("company");
      doc.appendChild(rootElement);

      // дочерние элементы
      Element staff = doc.createElement("Staff");
      rootElement.appendChild(staff);

      // добавление аттрибутов
      Attr attr = doc.createAttribute("id");
      attr.setValue("1");
      staff.setAttributeNode(attr);

      // другой способ
      // staff.setAttribute("id", "1");

      Element firstname = doc.createElement("firstname");
      firstname.appendChild(doc.createTextNode("yong"));
      staff.appendChild(firstname);

      Element lastname = doc.createElement("lastname");
      lastname.appendChild(doc.createTextNode("mook kim"));
      staff.appendChild(lastname);

      Element nickname = doc.createElement("nickname");
      nickname.appendChild(doc.createTextNode("mkyong"));
      staff.appendChild(nickname);

      Element salary = doc.createElement("salary");
      salary.appendChild(doc.createTextNode("100000"));
      staff.appendChild(salary);

      // Запись контента в xml file
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(new File("Export.xml"));

      transformer.transform(source, result);
      System.out.println("File saved!");

    } catch (ParserConfigurationException pce) {
      pce.printStackTrace();
    } catch (TransformerException tfe) {
      tfe.printStackTrace();
    }

    ModifyXMLFile mxf = new ModifyXMLFile();
    mxf.ModifyFile();
  }
  public static void main(String argv[]) {
    try {
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
      // root elements
      Document doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("company");
      doc.appendChild(rootElement);
      // staff elements
      Element staff = doc.createElement("Staff");
      rootElement.appendChild(staff);

      // set attribute to staff element

      Attr attr = doc.createAttribute("id");
      attr.setValue("1");
      staff.setAttributeNode(attr);

      // shorten way
      // staff.setAttribute("id", "1");
      // firstname elements

      Element firstname = doc.createElement("firstname");
      firstname.appendChild(doc.createTextNode("yong"));
      staff.appendChild(firstname);

      // lastname elements
      Element lastname = doc.createElement("lastname");
      lastname.appendChild(doc.createTextNode("mook kim"));
      staff.appendChild(lastname);

      // nickname elements
      Element nickname = doc.createElement("nickname");
      nickname.appendChild(doc.createTextNode("mkyong"));
      staff.appendChild(nickname);

      // salary elements
      Element salary = doc.createElement("salary");
      salary.appendChild(doc.createTextNode("100000"));
      staff.appendChild(salary);

      // write the content into xml file
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(new File(".\\file.xml"));

      // Output to console for testing
      // StreamResult result = new StreamResult(System.out);
      transformer.transform(source, result);
      System.out.println("File saved!");
    } catch (ParserConfigurationException pce) {
      pce.printStackTrace();
    } catch (TransformerException tfe) {
      tfe.printStackTrace();
    }
  }
Example #22
0
  public static File getXMLFile(
      ByteArrayOutputStream bos,
      String appName,
      String objectType,
      Date createDate,
      String fileName)
      throws Exception {
    byte[] byteData = bos.toByteArray();

    DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputStream is = new ByteArrayInputStream(byteData);
    Document document = docBuilder.parse(is);

    org.w3c.dom.Attr namespace = document.createAttribute("xmlns:exoks");
    namespace.setValue("http://www.exoplatform.com/exoks/2.0");
    document.getFirstChild().getAttributes().setNamedItem(namespace);

    org.w3c.dom.Attr attName = document.createAttribute("exoks:applicationName");
    attName.setValue(appName);
    document.getFirstChild().getAttributes().setNamedItem(attName);

    org.w3c.dom.Attr dataType = document.createAttribute("exoks:objectType");
    dataType.setValue(objectType);
    document.getFirstChild().getAttributes().setNamedItem(dataType);

    org.w3c.dom.Attr exportDate = document.createAttribute("exoks:exportDate");
    exportDate.setValue(createDate.toString());
    document.getFirstChild().getAttributes().setNamedItem(exportDate);

    org.w3c.dom.Attr checkSum = document.createAttribute("exoks:checkSum");
    checkSum.setValue(generateCheckSum(byteData));
    document.getFirstChild().getAttributes().setNamedItem(checkSum);

    DOMSource source = new DOMSource(document.getFirstChild());

    File file = new File(fileName + ".xml");
    file.deleteOnExit();
    file.createNewFile();
    StreamResult result = new StreamResult(file);
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.transform(source, result);
    return file;
  }
  private static Element persistParam(Document doc, String name, String textContent) {
    Element param = doc.createElement("param");

    Attr attr = doc.createAttribute("name");
    attr.setValue(name);
    param.setAttributeNode(attr);

    param.setTextContent(textContent);
    return param;
  }
Example #24
0
 private static void renameNodeReference(
     List<Element> elements, String attributeName, String oldNodeName, String newNodeName) {
   for (Element c : elements) {
     Attr nodeRef = c.getAttributeNode(attributeName);
     String nodeName = nodeRef.getValue();
     if (oldNodeName.equals(nodeName)) {
       nodeRef.setValue(newNodeName);
     }
   }
 }
Example #25
0
 public static void putAt(Element self, String property, Object value) {
   if (property.startsWith("@")) {
     String attributeName = property.substring(1);
     Document doc = self.getOwnerDocument();
     Attr newAttr = doc.createAttribute(attributeName);
     newAttr.setValue(value.toString());
     self.setAttributeNode(newAttr);
     return;
   }
   InvokerHelper.setProperty(self, property, value);
 }
 /**
  * Create a new node (element or attribute) to be inserted into the target node as a child or
  * attribute.
  *
  * @param doc DOM document
  * @param target the target ode
  * @param value the value for creating the new node.
  */
 public void createNewNode(Document doc, Node target, Value value) {
   if (value.getLocation().startsWith("@")) {
     Attr newAttribute = doc.createAttribute(value.getLocation().substring(1));
     newAttribute.setValue(value.getValue());
     target.getAttributes().setNamedItem(newAttribute);
   } else {
     Element newElement = doc.createElement(value.getLocation());
     newElement.setTextContent(value.getValue());
     target.appendChild(newElement);
   }
 }
Example #27
0
 private static void renameRenderedChildReference(
     Element element, String oldNodeName, String newNodeName) {
   Attr renderedChildReference = element.getAttributeNode("renderedChild");
   if (renderedChildReference == null) return;
   String oldRenderedChild = renderedChildReference.getValue();
   if (oldRenderedChild.equals(oldNodeName)) {
     if (newNodeName == null || newNodeName.length() == 0)
       element.removeAttributeNode(renderedChildReference);
     else renderedChildReference.setValue(newNodeName);
   }
 }
Example #28
0
  /**
   * Creates the XML file for the game that should be used to keep track of everything.
   *
   * @throws ParserConfigurationException
   * @throws TransformerException
   * @throws IOException
   * @throws SAXException
   */
  public static void createXML(World world)
      throws ParserConfigurationException, TransformerException, SAXException, IOException {

    Document xml = getDocument(null);
    Element money, gameTime, game;
    Element store, quantity, type, item;

    game = xml.createElement("Game");
    xml.appendChild(game);

    // Money
    money = xml.createElement("money");
    money.setTextContent(String.valueOf(world.getMoney()));
    game.appendChild(money);

    gameTime = xml.createElement("gametime");
    gameTime.setTextContent(String.valueOf(System.currentTimeMillis()));
    game.appendChild(gameTime);

    // You'll need to loop through this eventually
    store = xml.createElement("store");
    game.appendChild(store);
    Attr attr = xml.createAttribute("id");
    attr.setValue("1");
    store.setAttributeNode(attr);

    // Loop through the items
    for (Item i : world.getStore().getItems()) {
      item = xml.createElement("item");
      store.appendChild(item);
      attr = xml.createAttribute("id");
      attr.setValue("" + i.getType());
      item.setAttributeNode(attr);

      quantity = xml.createElement("quantity");
      quantity.setTextContent("" + i.getAmount());
      item.appendChild(quantity);
    }
    // Write the content into xml file
    writeXML(xml, new File(FILE_NAME));
  }
 static {
   try {
     nullNode =
         DocumentBuilderFactory.newInstance()
             .newDocumentBuilder()
             .newDocument()
             .createAttributeNS(Constants.NamespaceSpecNS, XMLNS);
     nullNode.setValue("");
   } catch (Exception e) {
     throw new RuntimeException("Unable to create nullNode" /*,*/ + e);
   }
 }
Example #30
0
  protected static Document mrsPyramidToTileMapServiceXml(
      final String url, final List<String> pyramidNames)
      throws ParserConfigurationException, DOMException, UnsupportedEncodingException {
    /*
     * String tileMapService = "<?xml version='1.0' encoding='UTF-8' ?>" +
     * "<TileMapService version='1.0.0' services='http://localhost/mrgeo-services/api/tms/'>" +
     * "  <Title>Example Tile Map Service</Title>" +
     * "  <Abstract>This is a longer description of the example tiling map service.</Abstract>" +
     * "  <TileMaps>" + "    <TileMap " + "      title='AfPk Elevation V2' " +
     * "      srs='EPSG:4326' " + "      profile='global-geodetic' " +
     * "      href='http:///localhost/mrgeo-services/api/tms/1.0.0/AfPkElevationV2' />" +
     * "  </TileMaps>" + "</TileMapService>";
     */

    final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    final Document doc = docBuilder.newDocument();
    final Element rootElement = doc.createElement("TileMapService");
    doc.appendChild(rootElement);
    final Attr v = doc.createAttribute("version");
    v.setValue(VERSION);
    rootElement.setAttributeNode(v);
    final Attr service = doc.createAttribute("services");
    service.setValue(normalizeUrl(normalizeUrl(url).replace(VERSION, "")));
    rootElement.setAttributeNode(service);

    // child elements
    final Element title = doc.createElement("Title");
    title.setTextContent("Tile Map Service");
    rootElement.appendChild(title);

    final Element abst = doc.createElement("Abstract");
    abst.setTextContent("MrGeo MrsImagePyramid rasters available as TMS");
    rootElement.appendChild(abst);

    final Element tilesets = doc.createElement("TileMaps");
    rootElement.appendChild(tilesets);

    Collections.sort(pyramidNames);
    for (final String p : pyramidNames) {
      final Element tileset = doc.createElement("TileMap");
      tilesets.appendChild(tileset);
      final Attr href = doc.createAttribute("href");
      href.setValue(normalizeUrl(url) + "/" + URLEncoder.encode(p, "UTF-8"));
      tileset.setAttributeNode(href);
      final Attr maptitle = doc.createAttribute("title");
      maptitle.setValue(p);
      tileset.setAttributeNode(maptitle);
      final Attr srs = doc.createAttribute("srs");
      srs.setValue(SRS);
      tileset.setAttributeNode(srs);
      final Attr profile = doc.createAttribute("profile");
      profile.setValue("global-geodetic");
      tileset.setAttributeNode(profile);
    }

    return doc;
  }