public static Document createItemListDocument(Collection<Item> list) {

    try {

      DocumentBuilder documentBuilder = XmlUtil.getDocumentBuilder();
      Document document = documentBuilder.newDocument();

      Element localeElement = document.createElement(items);

      Element itemElem = document.createElement(item_node);
      Element itemLabelElem = document.createElement(item_node_label);
      Element itemValueElem = document.createElement(item_value_label);

      Node itemNode;

      for (Item item : list) {

        itemLabelElem.setTextContent(item.getItemLabel());
        itemValueElem.setTextContent(item.getItemValue());

        itemElem.appendChild(itemLabelElem);
        itemElem.appendChild(itemValueElem);

        itemNode = localeElement.getOwnerDocument().importNode(itemElem, true);
        localeElement.appendChild(itemNode);
      }
      document.appendChild(localeElement);

      return document;

    } catch (ParserConfigurationException e) {
      // TODO: handle exception
    }
    return null;
  }
Example #2
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);
  }
  public void saveProp(String file) throws Exception {
    File outputfile = new File(file);
    DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dbuilder = dbfactory.newDocumentBuilder();
    Document doc = dbuilder.newDocument();
    Element e = doc.createElement("properties");
    doc.appendChild(e);

    Element e2 = doc.createElement("threadcount");
    e2.setTextContent(threadcount + "");
    e.appendChild(e2);

    Element e3 = doc.createElement("workspace");
    e3.setTextContent(workspace);
    e.appendChild(e3);

    Element e4 = doc.createElement("display");
    e4.setTextContent(display + "");
    e.appendChild(e4);

    TransformerFactory ts = TransformerFactory.newInstance();
    Transformer transformer = ts.newTransformer();
    DOMSource dm = new DOMSource(doc);
    transformer.transform(dm, new StreamResult(outputfile));
  }
Example #4
0
  /**
   * @param filePath
   * @param output
   * @throws InvalidFormatException
   * @throws IOException
   * @throws ParserConfigurationException
   * @throws TransformerException
   */
  public static void convert(String filePath, String output)
      throws InvalidFormatException, IOException, ParserConfigurationException,
          TransformerException {
    XlsxConverter converter = new XlsxConverter(filePath, output);

    Integer sheetNum = converter.x.getNumberOfSheets();
    for (int i = 0; i < sheetNum; i++) {
      XSSFSheet sheet = converter.x.getSheet(converter.x.getSheetName(i));
      String sheetName = converter.x.getSheetName(i);
      System.out.println("----starting process sheet : " + sheetName);
      // add sheet title
      {
        Element title = converter.htmlDocumentFacade.createHeader2();
        title.setTextContent(sheetName);
        converter.page.appendChild(title);
      }

      converter.processSheet(converter.page, sheet);
    }

    converter.htmlDocumentFacade.updateStylesheet();

    Element style =
        (Element) converter.htmlDocumentFacade.getDocument().getElementsByTagName("style").item(0);

    style.setTextContent(converter.css.append(style.getTextContent()).toString());

    converter.saveAsHtml(output, converter.htmlDocumentFacade.getDocument());
  }
Example #5
0
  @Override
  public void write(Document document) {
    Element root = document.createElement(WXXmlElementName.ROOT);
    head.write(root, document);

    Element musicElement = document.createElement(WXXmlElementName.MUSIC);

    Element titleElement = document.createElement(WXXmlElementName.TITLE);
    titleElement.setTextContent(this.title);
    Element descriptionElement = document.createElement(WXXmlElementName.DESCRITION);
    descriptionElement.setTextContent(this.description);
    Element musicUrlElement = document.createElement(WXXmlElementName.MUSIC_URL);
    musicUrlElement.setTextContent(this.musicUrl);
    Element hQMusicUrlElement = document.createElement(WXXmlElementName.HQ_MUSIC_URL);
    hQMusicUrlElement.setTextContent(this.hQMusicUrl);

    musicElement.appendChild(titleElement);
    musicElement.appendChild(descriptionElement);
    musicElement.appendChild(musicUrlElement);
    musicElement.appendChild(hQMusicUrlElement);
    root.appendChild(musicElement);

    Element funcFlagElement = document.createElement(WXXmlElementName.FUNC_FLAG);
    funcFlagElement.setTextContent(this.funcFlag);
    root.appendChild(funcFlagElement);

    document.appendChild(root);
  }
Example #6
0
 private void addLatLonParameters(Element parent, LatLonRect bbox) {
   // lat
   Element lat = getDocument().createElement("ows:Parameter");
   lat.setAttribute("name", "lat");
   lat.setAttribute("use", "required");
   Element latAllowedValues = getDocument().createElement("ows:AllowedValues");
   // min
   Element latMin = getDocument().createElement("ows:MinimumValue");
   latMin.setTextContent(bbox.getLowerLeftPoint().getLatitude() + "");
   latAllowedValues.appendChild(latMin);
   // max
   Element latMax = getDocument().createElement("ows:MaximumValue");
   latMax.setTextContent(bbox.getUpperRightPoint().getLatitude() + "");
   latAllowedValues.appendChild(latMax);
   lat.appendChild(latAllowedValues);
   parent.appendChild(lat);
   // lon
   Element lon = getDocument().createElement("ows:Parameter");
   lon.setAttribute("name", "lon");
   lon.setAttribute("use", "required");
   Element lonAllowedValues = getDocument().createElement("ows:AllowedValues");
   // min
   Element lonMin = getDocument().createElement("ows:MinimumValue");
   lonMin.setTextContent(bbox.getLowerLeftPoint().getLongitude() + "");
   lonAllowedValues.appendChild(lonMin);
   // max
   Element lonMax = getDocument().createElement("ows:MaximumValue");
   lonMax.setTextContent(bbox.getUpperRightPoint().getLongitude() + "");
   lonAllowedValues.appendChild(lonMax);
   lon.appendChild(lonAllowedValues);
   parent.appendChild(lon);
 }
Example #7
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;
  }
  @Override
  protected void changeItem(UntypedItemXml item) {
    Element element = getElement(item, property);
    if (element == null) {
      throw new CliException("Cannot find element: " + property);
    }

    String namespaceURI = element.getNamespaceURI();
    String localName = element.getLocalName();

    Node parentNode = element.getParentNode();
    String parentNamespaceUri = parentNode.getNamespaceURI();
    String parentTag = parentNode.getLocalName();

    String pathKey = parentNamespaceUri + ":" + parentTag + ":" + namespaceURI + ":" + localName;

    if ("http://platformlayer.org/service/platformlayer/v1.0:platformLayerService:http://platformlayer.org/service/platformlayer/v1.0:config"
        .equals(pathKey)) {
      Element newNode = element.getOwnerDocument().createElementNS(NAMESPACE_URI_CORE, "property");
      Element keyNode = element.getOwnerDocument().createElementNS(NAMESPACE_URI_CORE, "key");
      keyNode.setTextContent(key);
      Element valueNode = element.getOwnerDocument().createElementNS(NAMESPACE_URI_CORE, "value");
      valueNode.setTextContent(value);
      newNode.appendChild(keyNode);
      newNode.appendChild(valueNode);

      element.appendChild(newNode);
    } else {
      throw new UnsupportedOperationException();
    }
  }
 private Element createSnippetNode(final Snippet inSnippet) throws IOException {
   Element snippetNode = _document.createElement("snippet");
   snippetNode.setAttribute("sid", String.valueOf(inSnippet.sid));
   for (List<SnippetToken> sentence : inSnippet.sentences) {
     for (SnippetToken token : sentence) {
       if (!token.punctuationBefore.isEmpty()) {
         Element beforePunctNode = _document.createElement("text");
         beforePunctNode.setTextContent(token.punctuationBefore);
         snippetNode.appendChild(beforePunctNode);
       }
       Element wordNode = _document.createElement("word");
       wordNode.setAttribute("text", token.text);
       wordNode.setAttribute("source", token.source);
       wordNode.setAttribute("code", Integer.toString(-1));
       if (token.target) {
         wordNode.setAttribute("target", "1");
         wordNode.setAttribute("queryPosition", String.valueOf(token.queryPosition));
       }
       snippetNode.appendChild(wordNode);
       if (!token.punctuationAfter.isEmpty()) {
         Element afterPunctNode = _document.createElement("text");
         afterPunctNode.setTextContent(token.punctuationAfter);
         snippetNode.appendChild(afterPunctNode);
       }
     }
   }
   return snippetNode;
 }
Example #10
0
  public int ajouterAlbum(String titreAlbum, String nomArtiste, int anneeAlbum) {

    if (!existeAlbum(titreAlbum, nomArtiste, anneeAlbum)) {
      ID++;
      Element id = document.createElement("id");
      id.setTextContent(Integer.toString(ID));
      Element titre = document.createElement("titre");
      titre.setTextContent(titreAlbum);
      Element artiste = document.createElement("artiste");
      artiste.setTextContent(nomArtiste);
      Element annee = document.createElement("annee");
      annee.setTextContent(Integer.toString(anneeAlbum));
      Element qte = document.createElement("qte");
      qte.setTextContent(Integer.toString(0));
      Element album = document.createElement("album");
      album.appendChild(id);
      album.appendChild(titre);
      album.appendChild(artiste);
      album.appendChild(annee);
      album.appendChild(qte);
      Element stock = (Element) document.getElementsByTagName("stock").item(0);
      stock.appendChild(album);
      try {
        save(encryptDocument(document), path);
      } catch (Exception ex) {
        Logger.getLogger(Inventaire.class.getName()).log(Level.SEVERE, null, ex);
      }
      return ID;
    }
    return -1;
  }
Example #11
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) {
    }
  }
  private Element makeTerm(Document doc, TablesRevisionProblem problem, Field field)
      throws RenderException {
    assert field != null;

    Element element = doc.createElement("term");

    if (field.equals(problem.getFraction())) {
      Element child = doc.createElement("numerator");
      child.setTextContent("1");
      element.appendChild(child);

      child = doc.createElement("denominator");
      child.setTextContent(String.valueOf(problem.getValue(field)));
      if (field.equals(problem.getBlank())) {
        setBlank(element);
      }
      element.appendChild(child);

    } else {
      if (field.equals(problem.getBlank())) {
        setBlank(element);
      }

      element.setTextContent(String.valueOf(problem.getValue(field)));
    }

    return element;
  }
  public Element createEdgeElement(
      Document evtDom, Collaboration collaboration, int src, int tar, int index) {

    Element edge = evtDom.createElement("edge");
    edge.setAttribute("id", "e" + Integer.toString(index));
    edge.setAttribute("source", Integer.toString(src));
    edge.setAttribute("target", Integer.toString(tar));

    for (int row = 0; row < edgeAttr.length; row++) {
      Element data = evtDom.createElement("data");
      data.setAttribute("key", edgeAttr[row][0]);

      if (edgeAttr[row][0].equalsIgnoreCase("SourceContributorID"))
        data.setTextContent(Integer.toString(src));
      else if (edgeAttr[row][0].equalsIgnoreCase("TargetContributorID"))
        data.setTextContent(Integer.toString(tar));
      else if (edgeAttr[row][0].equalsIgnoreCase("NumOfCollaboration"))
        data.setTextContent(Integer.toString(collaboration.getCollaborationCount()));
      else if (edgeAttr[row][0].equalsIgnoreCase("FirstDate"))
        data.setTextContent(collaboration.getFirstDate());
      else if (edgeAttr[row][0].equalsIgnoreCase("LastDate"))
        data.setTextContent(collaboration.getLastDate());

      edge.appendChild(data);
    }
    return edge;
  }
Example #14
0
 /**
  * @param threddsURI
  * @param stationNames
  * @param sensorNames
  */
 public void setOperationDescSen(
     String threddsURI, String[] stationNames, List<String> sensorNames) {
   // set url info
   setOperationMethods((Element) descSen.getElementsByTagName("ows:HTTP").item(0), threddsURI);
   // set procedure allowed values of each station and sensor for the dataset
   Element procedure = null;
   NodeList nodes = descSen.getElementsByTagName("ows:Parameter");
   for (int i = 0; i < nodes.getLength(); i++) {
     Element elem = (Element) nodes.item(i);
     if (elem.getAttribute("name").equalsIgnoreCase("procedure")) {
       procedure = elem;
       break;
     }
   }
   if (procedure != null && stationNames != null) {
     // add allowed values node
     Element allowedValues = getDocument().createElement("ows:AllowedValues");
     procedure.appendChild(allowedValues);
     // add network-all value
     Element na = getDocument().createElement("ows:Value");
     na.setTextContent("urn:ioos:network:" + SOSBaseRequestHandler.getNamingAuthority() + ":all");
     allowedValues.appendChild(na);
     for (String stationName : stationNames) {
       Element elem = getDocument().createElement("ows:Value");
       elem.setTextContent(SOSBaseRequestHandler.getGMLName(stationName));
       allowedValues.appendChild(elem);
       for (String senName : sensorNames) {
         Element sElem = getDocument().createElement("ows:Value");
         sElem.setTextContent(SOSBaseRequestHandler.getSensorGMLName(stationName, senName));
         allowedValues.appendChild(sElem);
       }
     }
   }
 }
 public void addAppletElement(String appletAID, String className) {
   Element servlet = doc.createElement(XmlTagNames.XML_APPLET_TAG);
   Element sName = doc.createElement(XmlTagNames.XML_APPLET_AID_TAG);
   sName.setTextContent(appletAID);
   Element sClass = doc.createElement(XmlTagNames.XML_APPLET_CLASS_TAG);
   sClass.setTextContent(className);
   servlet.appendChild(sClass);
   servlet.appendChild(sName);
   getAppletAppNode().appendChild(servlet);
 }
Example #16
0
  private void processCell(Element tr, XSSFCell cell) {

    int num = cell.getSheet().getNumMergedRegions();

    //		System.out.println(cell.getCTCell());
    for (int i = 0; i < num; i++) {

      CellRangeAddress c = cell.getSheet().getMergedRegion(i);

      System.out.println(c.getFirstColumn());
      ;
      System.out.println(c.getLastColumn());
      System.out.println(c.getFirstRow());
      System.out.println(c.getLastRow());
      System.out.println();
      System.out.println(cell.getRowIndex());
      System.out.println(cell.getColumnIndex());

      System.out.println("\n\n\n");

      //		System.out.println(cra);

    }

    //		System.exit(0);

    Element td = htmlDocumentFacade.createTableCell();
    Object value;
    switch (cell.getCellType()) {
      case Cell.CELL_TYPE_BLANK:
        value = "\u00a0";
        break;
      case Cell.CELL_TYPE_NUMERIC:
        value = cell.getNumericCellValue();
        break;
      case Cell.CELL_TYPE_BOOLEAN:
        value = cell.getBooleanCellValue();
        break;
      case Cell.CELL_TYPE_FORMULA:
        value = cell.getNumericCellValue();
        break;
      default:
        value = cell.getRichStringCellValue();
        break;
    }
    if (value instanceof XSSFRichTextString) {
      processCellStyle(td, cell.getCellStyle(), (XSSFRichTextString) value);
      td.setTextContent(value.toString());
    } else {
      processCellStyle(td, cell.getCellStyle(), null);
      td.setTextContent(value.toString());
    }
    //		System.err.println(value);
    tr.appendChild(td);
  }
 @Override
 public void saveValueToXML(@Nonnull Element xmlElement) {
   if (getValue() == null) return;
   Document parentDocument = xmlElement.getOwnerDocument();
   Element newElement = parentDocument.createElement("absolutetolerance");
   newElement.setTextContent(String.valueOf(getValue().getMzTolerance()));
   xmlElement.appendChild(newElement);
   newElement = parentDocument.createElement("ppmtolerance");
   newElement.setTextContent(String.valueOf(getValue().getPpmTolerance()));
   xmlElement.appendChild(newElement);
 }
Example #18
0
  private void resetMeta() {
    Element meta = getElement("meta", doc.getDocumentElement());
    getElement("userEntry", meta);
    Element target = getElement("targetSite", meta);
    Element documentation = getElement("documentation", meta);
    Element pageTitle = getElement("pageTitle", meta);
    Element authorName = getElement("authorName", meta);

    target.setAttribute("uri", getTargetUriPattern());
    documentation.setTextContent(getDocumentation());
    pageTitle.setTextContent(getPageTitle());
    authorName.setTextContent(getAuthorName());
  }
  /**
   * Return a XML with config
   *
   * @param path Path for saving de config
   * @param config GUIConfig
   */
  public static void saveXMLFromGUIConfig(String path, GUIConfig config) {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder;
    Document doc = null;
    try {
      docBuilder = docFactory.newDocumentBuilder();

      // root elements
      doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("gui-configuration");
      doc.appendChild(rootElement);

      Element language = doc.createElement("language");
      language.setTextContent(config.getLanguage());
      rootElement.appendChild(language);

      Element recentConfigFiles = doc.createElement("recentConfigFiles");
      rootElement.appendChild(recentConfigFiles);

      for (String configFilePath : config.getRecentConfigFiles()) {
        Element configFile = doc.createElement("configFile");
        configFile.setTextContent(configFilePath);
        recentConfigFiles.appendChild(configFile);
      }

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

      // At the moment we are not to validate Scheme
      // validateSchema(doc, Constants.configSchemaFilePath);

      // normalize text representation
      doc.getDocumentElement().normalize();

      StreamResult result = new StreamResult(new File(path));

      transformer.transform(source, result);

    } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TransformerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #20
0
  /**
   * Parses the given author string and returns the result as DOM node. The returned XML has the
   * following structure: <authors> <author> <familyname>Buxtehude-Mölln</familyname>
   * <givenname>Heribert</givenname> <prefix>von und zu</prefix> <title>König</title> </author>
   * <author> <familyname>Müller</familyname> <givenname>Peter</givenname> </author> </authors>
   *
   * @param authors
   * @return
   */
  public static Node parseAsNode(String authors) {
    DocumentBuilder documentBuilder;

    try {
      documentBuilder = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    Document document = documentBuilder.newDocument();
    Element element = document.createElement("authors");
    document.appendChild(element);

    try {
      AuthorDecoder authorDecoder = new AuthorDecoder(authors);
      List<Author> authorList = authorDecoder.getBestAuthorList();
      if (authorList != null) {
        for (Author author : authorList) {
          Element authorElement = document.createElement("author");
          element.appendChild(authorElement);

          if (author.getSurname() != null) {
            Element familyNameElement = document.createElement("familyname");
            familyNameElement.setTextContent(author.getSurname());
            authorElement.appendChild(familyNameElement);
          }

          if (author.getGivenName() != null) {
            Element givenNameElement = document.createElement("givenname");
            givenNameElement.setTextContent(author.getGivenName());
            authorElement.appendChild(givenNameElement);
          }

          if (author.getPrefix() != null) {
            Element prefixElement = document.createElement("prefix");
            prefixElement.setTextContent(author.getPrefix());
            authorElement.appendChild(prefixElement);
          }

          if (author.getTitle() != null) {
            Element titleElement = document.createElement("title");
            titleElement.setTextContent(author.getTitle());
            authorElement.appendChild(titleElement);
          }
        }
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return document;
  }
 @Override
 public void handleMessage(SoapMessage message) throws Fault {
   Document doc = DOMUtils.createDocument();
   Element root = doc.createElementNS(namespaceURL, rootName);
   Element elCode = doc.createElement(elCodeName);
   elCode.setTextContent(this.code);
   Element elPasswd = doc.createElement(elPasswdName);
   elPasswd.setTextContent(this.passwd);
   root.appendChild(elCode);
   root.appendChild(elPasswd);
   QName qName = new QName("RequestSOAPHeader");
   Header header = new Header(qName, root);
   message.getHeaders().add(header);
 }
  public void setupControlDocs() throws Exception {

    Document doc = parser.newDocument();
    Element root = doc.createElement("DUMMYROOT");
    doc.appendChild(root);

    Element child1 = doc.createElement("theValue");
    child1.setTextContent("10");
    Element child2 = doc.createElement("theOtherValue");
    child2.setTextContent("20");
    root.appendChild(child1);
    root.appendChild(child2);
    controlDocument = doc;
  }
Example #23
0
 /**
  * Builds the property.
  *
  * @param document the document
  * @param parent the parent
  * @param field the field
  * @param dateVal the dateVal
  * @throws IOException Signals that an I/O exception has occurred.
  */
 private static void buildProperty(Document document, Element parent, Field field, Object value)
     throws IOException {
   Type type = field.getType();
   // no need to qualify each element name as namespace is already added
   String propName = field.getName().getLocalName();
   Element element = document.createElement(propName);
   parent.appendChild(element);
   // extract the element content
   if (type.isSimpleType()) {
     // Avoid returning scientific notation representations of
     // very large or very small decimal values. See CSPACE-4691.
     if (isNuxeoDecimalType(type) && valueMatchesNuxeoType(type, value)) {
       element.setTextContent(nuxeoDecimalValueToDecimalString(value));
       /*
       * We need a way to produce just a Date when the specified data
       * type is an xs:date vs. xs:datetime. Nuxeo maps both to a Calendar. Sigh.
       if(logger.isTraceEnabled() && isDateType(type)) {
           String dateValType = "unknown";
           if (value instanceof java.util.Date) {
               dateValType = "java.util.Date";
           } else if (value instanceof java.util.Calendar) {
               dateValType = "java.util.Calendar";
           }
           logger.trace("building XML for date type: "+type.getName()
                   +" value type: "+dateValType
                   +" encoded: "+encodedVal);
       }
       */
     } else {
       String encodedVal = type.encode(value);
       element.setTextContent(encodedVal);
     }
   } else if (type.isComplexType()) {
     ComplexType ctype = (ComplexType) type;
     if (ctype.getName().equals(TypeConstants.CONTENT)) {
       throw new RuntimeException("Unexpected schema type: BLOB for field: " + propName);
     } else {
       buildComplex(document, element, ctype, (Map) value);
     }
   } else if (type.isListType()) {
     if (value instanceof List) {
       buildList(document, element, (ListType) type, (List) value);
     } else if (value.getClass().getComponentType() != null) {
       buildList(document, element, (ListType) type, PrimitiveArrays.toList(value));
     } else {
       throw new IllegalArgumentException(
           "A value of list type is neither list neither array: " + value);
     }
   }
 }
Example #24
0
 private Element createError(String codeStr, String messageStr)
     throws ParserConfigurationException {
   DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   Document doc = documentBuilder.newDocument();
   Element error = doc.createElement("error");
   Element code = doc.createElement("code");
   code.setTextContent(codeStr);
   Element message = doc.createElement("message");
   message.setTextContent(messageStr);
   error.appendChild(code);
   error.appendChild(message);
   doc.appendChild(error);
   return doc.getDocumentElement();
 }
Example #25
0
 @Override
 protected void addField2Body(Element body, SoapMessageModel soapMessageModel) {
   deviceId.addThisToBody(body, soapMessageModel);
   event.addThisToBody(body, soapMessageModel);
   Element maxnv = soapMessageModel.createElement(MAXENV);
   maxnv.setTextContent(Integer.toString((maxEnvelopes)));
   Element retry = soapMessageModel.createElement(RETRYCOUNT);
   retry.setTextContent(Integer.toString(retryCount));
   Element curren = soapMessageModel.createElement(CURRENTTIME);
   curren.setTextContent(currentTime);
   body.appendChild(maxnv);
   body.appendChild(retry);
   body.appendChild(curren);
   parameterList.addThisToBody(body, soapMessageModel);
 }
Example #26
0
 @Override
 public void saveValueToXML(@Nonnull Element xmlElement) {
   final Document parentDocument = xmlElement.getOwnerDocument();
   String value = getValue();
   if (value != null) {
     Element newElement = parentDocument.createElement(textAreaElement);
     newElement.setTextContent(value);
     xmlElement.appendChild(newElement);
   }
   if (lastOpenPath != null) {
     Element newElement = parentDocument.createElement(lastOpenPathElement);
     newElement.setTextContent(lastOpenPath.getPath());
     xmlElement.appendChild(newElement);
   }
 }
  /**
   * 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);
  }
  @Override
  public void setPropertyValue(Object id, Object value) {
    String str = (String) value;
    if ((id == PROPERTY_COUNT_VALUE) && (nameDescriptor != null)) {
      PropertyLabelProvider propProvider =
          (PropertyLabelProvider) nameDescriptor.getLabelProvider();
      Node changeNode = propProvider.getNode();
      Element name = dom.getElement((Element) changeNode, "swe:value");
      if (str != null && !str.equals("")) {
        if (!dom.existAttribute(name, "rng:value/@selected")) {
          dom.setAttributeValue((Element) name, "rng:data/rng:value/@selected", "true");
        }
        dom.setElementValue((Element) name, "rng:data/rng:value", value.toString());
        ((Element) changeNode).setAttribute("xng:selected", "true");

      } else {

        Element valueNode = dom.getElement((Element) changeNode, "swe:value/rng:data/rng:value");
        ((Element) changeNode).removeAttribute("xng:selected");
        valueNode.setTextContent("");
        valueNode.removeAttribute("selected");
      }
      this.firePropertyChange("INSERT", null, null);
    }
  }
 private static void addAlignment(EXIOptions exiOptions, Document doc, Element startExiElement) {
   Element alignmentElement =
       doc.createElementNS(
           XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0, ALIGNMENT_KEY);
   alignmentElement.setTextContent(exiOptions.getAlignmentType().toString());
   startExiElement.appendChild(alignmentElement);
 }
  public void createLegalEntry(
      final Element root, final String type, final String text, final String url) {
    if (text == null && url == null) {
      return;
    }

    final Element ele = XmlHelper.addElement(root, type);
    if (text != null) {
      ele.setTextContent(text);
    } else {
      ele.setTextContent("");
    }
    if (url != null) {
      ele.setAttribute("url", url);
    }
  }