示例#1
0
  public static void Clone(Element root, Element src) {
    Document doc = root.getOwnerDocument();
    NodeList nodes = src.getChildNodes();
    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      int nodeType = node.getNodeType();
      switch (nodeType) {
        case Node.TEXT_NODE:
          root.appendChild(doc.createTextNode(node.getNodeValue()));
          break;
        case Node.ELEMENT_NODE:
          Element _element = doc.createElement(node.getNodeName());
          // clone attribute
          NamedNodeMap attrs = node.getAttributes();
          for (int j = 0; j < attrs.getLength(); j++) {
            Node attr = attrs.item(j);
            _element.setAttribute(attr.getNodeName(), attr.getNodeValue());
          }

          // clone children
          Clone(_element, (Element) node);
          root.appendChild(_element);
          break;
      }
    }
  }
 /** get all the categories of all tv programs */
 public static ArrayList<OnlineVideo> getAllCategory(final Context context) {
   ArrayList<OnlineVideo> result = new ArrayList<OnlineVideo>();
   DocumentBuilderFactory docBuilderFactory = null;
   DocumentBuilder docBuilder = null;
   Document doc = null;
   try {
     docBuilderFactory = DocumentBuilderFactory.newInstance();
     docBuilder = docBuilderFactory.newDocumentBuilder();
     // xml file is set in 'assets' folder
     doc = docBuilder.parse(context.getResources().getAssets().open("online.xml"));
     // root element
     Element root = doc.getDocumentElement();
     NodeList nodeList = root.getElementsByTagName("category");
     for (int i = 0; i < nodeList.getLength(); i++) {
       Node node = nodeList.item(i); // category
       OnlineVideo ov = new OnlineVideo();
       NamedNodeMap attr = node.getAttributes();
       ov.title = attr.getNamedItem("name").getNodeValue();
       ov.id = attr.getNamedItem("id").getNodeValue();
       ov.category = 1;
       ov.level = 2;
       ov.is_category = true;
       result.add(ov);
       // Read Node
     }
   } catch (IOException e) {
   } catch (SAXException e) {
   } catch (ParserConfigurationException e) {
   } finally {
     doc = null;
     docBuilder = null;
     docBuilderFactory = null;
   }
   return result;
 }
示例#3
0
  void handleParent(Element e, NameSpaceSymbTable ns) {
    if (!e.hasAttributes()) {
      return;
    }
    xmlattrStack.push(-1);
    NamedNodeMap attrs = e.getAttributes();
    int attrsLength = attrs.getLength();
    for (int i = 0; i < attrsLength; i++) {
      Attr N = (Attr) attrs.item(i);
      if (Constants.NamespaceSpecNS != N.getNamespaceURI()) {
        // Not a namespace definition, ignore.
        if (XML_LANG_URI == N.getNamespaceURI()) {
          xmlattrStack.addXmlnsAttr(N);
        }
        continue;
      }

      String NName = N.getLocalName();
      String NValue = N.getNodeValue();
      if (XML.equals(NName) && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
        continue;
      }
      ns.addMapping(NName, NValue, N);
    }
  }
  /**
   * Show a node as a string
   *
   * @param node
   * @param tabs
   * @return
   */
  String toString(Node node) {
    StringBuilder sb = new StringBuilder();

    // ---
    // Get name & value
    // ---
    String name = node.getNodeName();
    String value = node.getNodeValue();
    if (value != null) value = value.replace('\n', ' ').trim();
    sb.append(name);

    // ---
    // Get attributes
    // ---
    NamedNodeMap map = node.getAttributes();
    if (map != null) {
      sb.append("( ");
      for (int i = 0; i < map.getLength(); i++) {
        Node attr = map.item(i);
        String aname = attr.getNodeName();
        String aval = attr.getNodeValue();

        if (i > 0) sb.append(", ");
        sb.append(aname + "='" + aval + "'");
      }
      sb.append(" )");
    }

    if (value != null) sb.append(" = '" + value + "'\n");

    return sb.toString();
  }
  @Override
  protected void addTagInsertionProposals(
      ContentAssistRequest contentAssistRequest,
      int childPosition,
      CompletionProposalInvocationContext context) {
    int offset = contentAssistRequest.getReplacementBeginPosition();
    int length = contentAssistRequest.getReplacementLength();
    Node node = contentAssistRequest.getNode();
    // Current node can be 'parent' when the cursor is just before the end tag of the parent.
    Node parentNode = node.getNodeType() == Node.ELEMENT_NODE ? node : node.getParentNode();
    if (parentNode.getNodeType() != Node.ELEMENT_NODE) return;

    String tagName = parentNode.getNodeName();
    NamedNodeMap tagAttrs = parentNode.getAttributes();
    // Result mapping proposals.
    if ("resultMap".equals(tagName))
      generateResults(
          contentAssistRequest, offset, length, parentNode, tagAttrs.getNamedItem("type"));
    else if ("collection".equals(tagName))
      generateResults(
          contentAssistRequest, offset, length, parentNode, tagAttrs.getNamedItem("ofType"));
    else if ("association".equals(tagName))
      generateResults(
          contentAssistRequest, offset, length, parentNode, tagAttrs.getNamedItem("javaType"));

    Node statementNode = MybatipseXmlUtil.findEnclosingStatementNode(parentNode);
    if (statementNode == null) return;
    proposeStatementText(contentAssistRequest, statementNode);
  }
示例#6
0
  // Walk the tree from a specified element,
  // inserting data from a DicomObject where required.
  private static String getElementText(Element element, DicomObject dicomObject) {

    if (dicomTag(element)) return getDicomElementText(element, dicomObject);

    if (element.getTagName().equals("block")) return getBlockText(element, dicomObject);

    StringBuffer sb = new StringBuffer();
    sb.append("<" + element.getTagName());
    NamedNodeMap attributes = element.getAttributes();
    Attr attr;
    for (int i = 0; i < attributes.getLength(); i++) {
      attr = (Attr) attributes.item(i);
      String attrValue = attr.getValue().trim();
      if (dicomTag(attrValue)) {
        attrValue = getDicomElementText(attrValue, dicomObject);
      }
      sb.append(" " + attr.getName() + "=\"" + attrValue + "\"");
    }
    sb.append(">");
    if (element.getTagName().equals("table")) sb.append(getTableText(element, dicomObject));
    else if (element.getTagName().equals("publication-date")) sb.append(StringUtil.getDate());
    else sb.append(getChildrenText(element, dicomObject));
    sb.append("</" + element.getTagName() + ">");
    return sb.toString();
  }
示例#7
0
 @Override
 public void init(Element element) {
   final Element settingsElement = (Element) element.getElementsByTagName("settings").item(0);
   final NamedNodeMap attributes = settingsElement.getAttributes();
   for (int i = 0; i < attributes.getLength(); i++) {
     final Node node = attributes.item(i);
     if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
       final Attr attr = (Attr) node;
       this.params.put(attr.getName(), Float.parseFloat(attr.getValue()));
     }
   }
   final float top = this.params.get("top");
   final float left = this.params.get("left");
   final float bottom = this.params.get("bottom");
   final float right = this.params.get("right");
   final float bWidth = this.params.get("blockWidth");
   final float bHeight = this.params.get("blockHeight");
   final List<XYZItem> truc = new LinkedList<XYZItem>();
   for (float x = left; x < right; x += bWidth) {
     for (float y = bottom; y < top; y += bHeight) {
       truc.add(new XYZItem(x, y, getZValue(x, y)));
     }
   }
   this.map = new double[3][truc.size()];
   int i = 0;
   for (XYZItem item : truc) {
     this.map[0][i] = item.getXValue();
     this.map[1][i] = item.getYValue();
     this.map[2][i] = item.getZValue();
     i++;
   }
 }
  // factory
  private static GenerationTarget createTarget(File templateFile, File root) {
    GenerationTarget target;

    // read XML document
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
      Document doc = docBuilder.parse(templateFile);

      // get name
      NodeList nodes = doc.getElementsByTagName("templates");
      Node node = nodes.item(0);
      NamedNodeMap attrs = node.getAttributes();
      Node attr = attrs.getNamedItem("name");
      String templateName = attr.getNodeValue();
      target = new GenerationTarget(templateFile, root, templateName);

      // get class directives
      nodes = doc.getElementsByTagName("project");
      int nb = nodes.getLength();
      for (int i = 0; i < nb; i++) {
        node = nodes.item(i);
        createProjectDirective(target, node);
      }

    } catch (ParserConfigurationException ex) {
      target = null;
    } catch (IOException ex) {
      target = null;
    } catch (SAXException ex) {
      target = null;
    } // end try

    return target;
  }
  /**
   * @see
   *     org.teiid.designer.core.types.DatatypeManager#getEnterpriseExtensionsMap(org.eclipse.emf.ecore.EObject)
   */
  @Override
  public Map getEnterpriseExtensionsMap(EObject type) {
    Map result = Collections.EMPTY_MAP;
    if (type instanceof XSDSimpleTypeDefinition) {
      // Get the annotation for the type
      XSDAnnotation annotation = ((XSDSimpleTypeDefinition) type).getAnnotation();
      if (annotation == null) {
        return null;
      }

      // Iterator over the appInfos and add any attributes to the result collection
      result = new HashMap();
      final Iterator appInfos = annotation.getApplicationInformation().iterator();
      while (appInfos.hasNext()) {
        final Element appInfo = (Element) appInfos.next();
        if (appInfo.getAttributes() != null && appInfo.getAttributes().getLength() > 0) {
          final int length = appInfo.getAttributes().getLength();
          final NamedNodeMap map = appInfo.getAttributes();
          for (int i = 0; i < length; i++) {
            final Node mapNode = map.item(i);
            if (mapNode != null) {
              result.put(mapNode.getNodeName(), mapNode.getNodeValue());
            }
          }
        }
      }
    }

    return result;
  }
示例#10
0
  /**
   * Convert a <table> node from the xml into an HTableDescriptor (with its column families)
   */
  private HTableDescriptor getTable(Node tableNode) {
    NamedNodeMap tableAttributes = tableNode.getAttributes();
    String tableName = tableAttributes.getNamedItem(TABLE_NAME_ATTRIBUTE).getNodeValue();
    HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
    for (int x = 0; x < tableAttributes.getLength(); x++) {
      Node attr = tableAttributes.item(x);
      if (!attr.getNodeName().equalsIgnoreCase(TABLE_NAME_ATTRIBUTE)) { // skip name, already got it
        setAttributeValue(tableDescriptor, attr.getNodeName(), attr.getNodeValue());
      }
    }

    applyMissingTableDefaults(tableDescriptor);

    // parse the column families
    NodeList tableChildren = tableNode.getChildNodes();
    for (int x = 0; x < tableChildren.getLength(); x++) {
      Node tableChild = tableChildren.item(x);
      if (tableChild.getNodeName().equals(COLUMN_FAMILIES_ELEMENT)) {
        for (HColumnDescriptor family : getColumnFamilies(tableChild)) {
          tableDescriptor.addFamily(family);
        }
      }
    }

    // push this entire subtree of the xml file into the table metadata as the table's schema
    tableDescriptor.setValue(FULL_SCHEMA_PROPERTY, getFullXML(tableNode));

    validateTableDefinition(tableDescriptor);

    return tableDescriptor;
  }
示例#11
0
  /** Convert a <columnFamilies> node to a set of HColumnDescriptors */
  private Set<HColumnDescriptor> getColumnFamilies(Node columnFamiliesNode) {
    final Set<HColumnDescriptor> result = new HashSet<HColumnDescriptor>();

    NodeList columnFamilies = columnFamiliesNode.getChildNodes();
    for (int x = 0; x < columnFamilies.getLength(); x++) {
      Node columnFamily = columnFamilies.item(x);
      if (columnFamily.getNodeName().equals(COLUMN_FAMILY_ELEMENT)) {
        NamedNodeMap columnFamilyAttributes = columnFamily.getAttributes();
        String familyName =
            columnFamilyAttributes.getNamedItem(COLUMN_FAMILY_NAME_ATTRIBUTE).getNodeValue();
        HColumnDescriptor cf = new HColumnDescriptor(familyName);
        for (int y = 0; y < columnFamilyAttributes.getLength(); y++) {
          Node attr = columnFamilyAttributes.item(y);
          if (!attr.getNodeName()
              .equalsIgnoreCase(COLUMN_FAMILY_NAME_ATTRIBUTE)) { // skip name, already got it
            setAttributeValue(cf, attr.getNodeName(), attr.getNodeValue());
          }
        }
        applyMissingColumnFamilyDefaults(cf);
        validateColumnFamily(cf);
        result.add(cf);
      }
    }
    return result;
  }
示例#12
0
  @Override
  public void relink_namespace(ThreadContext context) {
    Element e = (Element) node;

    e.getOwnerDocument().renameNode(e, e.lookupNamespaceURI(e.getPrefix()), e.getNodeName());

    if (e.hasAttributes()) {
      NamedNodeMap attrs = e.getAttributes();

      for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr = (Attr) attrs.item(i);
        String nsUri = "";
        String prefix = attr.getPrefix();
        String nodeName = attr.getNodeName();
        if ("xml".equals(prefix)) {
          nsUri = "http://www.w3.org/XML/1998/namespace";
        } else if ("xmlns".equals(prefix) || nodeName.equals("xmlns")) {
          nsUri = "http://www.w3.org/2000/xmlns/";
        } else {
          nsUri = attr.lookupNamespaceURI(nodeName);
        }

        e.getOwnerDocument().renameNode(attr, nsUri, nodeName);
      }
    }

    if (e.hasChildNodes()) {
      ((XmlNodeSet) children(context)).relink_namespace(context);
    }
  }
示例#13
0
  /**
   * Copy in-scope namespace declarations of the decl node to the decl node itself so that this move
   * won't change the in-scope namespace bindings.
   */
  private void copyInscopeNSAttributes(Element e) {
    Element p = e;
    Set<String> inscopes = new HashSet<String>();
    while (true) {
      NamedNodeMap atts = p.getAttributes();
      for (int i = 0; i < atts.getLength(); i++) {
        Attr a = (Attr) atts.item(i);
        if (Constants.NS_XMLNS.equals(a.getNamespaceURI())) {
          String prefix;
          if (a.getName().indexOf(':') == -1) prefix = "";
          else prefix = a.getLocalName();

          if (inscopes.add(prefix) && p != e) {
            // if this is the first time we see this namespace bindings,
            // copy the declaration.
            // if p==decl, there's no need to. Note that
            // we want to add prefix to inscopes even if p==Decl

            e.setAttributeNodeNS((Attr) a.cloneNode(true));
          }
        }
      }

      if (p.getParentNode() instanceof Document) break;

      p = (Element) p.getParentNode();
    }

    if (!inscopes.contains("")) {
      // if the default namespace was undeclared in the context of decl,
      // it must be explicitly set to "" since the new environment might
      // have a different default namespace URI.
      e.setAttributeNS(Constants.NS_XMLNS, "xmlns", "");
    }
  }
示例#14
0
 private void prepareByFile(final File file) throws Exception {
   NodeList sourceDocChildNodes = getDocumentBuilder(file);
   for (int i = 0; i < sourceDocChildNodes.getLength(); i++) {
     NodeList childNodes2 = sourceDocChildNodes.item(i).getChildNodes();
     for (int j = 0; j < childNodes2.getLength(); j++) {
       NamedNodeMap attributes = childNodes2.item(j).getAttributes();
       if (attributes != null && attributes.getNamedItem("name") != null) {
         Node node = childNodes2.item(j).getAttributes().getNamedItem("name");
         Node clone = childNodes2.item(j).cloneNode(true);
         String keyMatch = getKeyMatchingNode(node, config.getKeys());
         String keyException = getKeysByValue(config.getExceptions(), node.getNodeValue());
         String addKey = MergeConfig.COMMON_XSD;
         if (isMatchingNodeBase(node, config.getBase())) {
           addKey = MergeConfig.DATATYPE_XSD;
         } else if (isMatchingDateTime(node)) {
           addKey = MergeConfig.DATETIME_XSD;
         } else if (StringUtils.isNotBlank(keyException)) {
           addKey = keyException;
         } else if (isMatchingCode(node)) {
           addKey = MergeConfig.CODETYPE_XSD;
         } else if (isMatchingAdress(node)) {
           addKey = MergeConfig.ADDRTYPE_XSD;
         } else if (keyMatch != null) {
           addKey = keyMatch;
         }
         mapNodes.get(addKey).addNode(node.getNodeValue(), clone, null);
         mapNodesKey.put(node.getNodeValue(), getPrefixByKey(addKey));
       }
     }
   }
 }
示例#15
0
  /**
   * Parses the document using the expected RSS format.
   *
   * @return Feed
   */
  @Override
  public Feed parse(Document document) {
    Feed feed = new Feed();

    // Get the root node.
    Node rssElement = document.getFirstChild();

    NamedNodeMap attrMap = rssElement.getAttributes();
    feed.setVersion(attrMap.getNamedItem("version").getNodeValue());

    // Now get channel.
    NodeList childNodes = rssElement.getChildNodes();
    Node channelNode = null;
    for (int index = 0; index < childNodes.getLength(); index++) {
      Node childNode = childNodes.item(index);

      if (!childNode.getNodeName().equalsIgnoreCase("channel")) {
        continue;
      }

      channelNode = childNode;
    }

    if (channelNode == null) {
      throw new ParserException("Parser could not find the channel element in the RSS feed.");
    }

    // We've done enough here...
    return parseChannel(feed, channelNode);
  }
  /**
   * Check if the attribute of a tag is in a list of allowed attribute names.
   *
   * @param element the tag element
   * @param attributeNames the allowed attribute names
   * @throws EoulsanException if an attribute of the tag in not in the allowed attribute list
   */
  private static void checkAllowedAttributes(final Element element, String... attributeNames)
      throws EoulsanException {

    final List<String> attributeList = Arrays.asList(attributeNames);

    final NamedNodeMap nnm = element.getAttributes();

    for (int i = 0; i < nnm.getLength(); i++) {

      final Node n = nnm.item(i);

      if (n.getNodeType() == Node.ATTRIBUTE_NODE) {

        final String attributeName = n.getNodeName();

        if (!attributeList.contains(attributeName)) {
          throw new EoulsanException(
              "the \""
                  + element.getNodeName()
                  + "\" tag contains an unknown attribute: "
                  + attributeName
                  + ".");
        }
      }
    }
  }
示例#17
0
    Shuttle(Shuttle cp, Element e) {
      this.node = e;
      this.g = cp.g;
      this.svgRoot = cp.svgRoot;
      this.shape = cp.shape;
      this.clip = cp.clip;
      this.fontSize = cp.fontSize;
      this.fontFamily = cp.fontFamily;
      this.stroke = cp.stroke;
      this.fill = cp.fill;
      this.strokeWidth = cp.strokeWidth;
      this.transform = new AffineTransform(cp.transform);
      this.opacity = cp.opacity;
      if (e.hasAttributes()) {
        NamedNodeMap atts = e.getAttributes();
        for (int i = 0; i < atts.getLength(); ++i) {

          Attr att = Attr.class.cast(atts.item(i));
          if (att.getNamespaceURI() != null) continue;
          String s = att.getName();
          String value = att.getValue();
          if (s.equals("style")) {
            for (String styles : value.split("[;]+")) {
              int j = styles.indexOf(':');
              if (j != -1) {
                applyStyle(styles.substring(0, j).trim(), styles.substring(j + 1).trim());
              }
            }

          } else {
            applyStyle(s, att.getValue());
          }
        }
      }
    }
示例#18
0
  public static void readXpath()
      throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("D:\\temp\\test_2\\screen_2.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
    // XPath Query for showing all nodes value
    // XPathExpression expr = xpath
    // .compile("//Screens/Screen[@number='1']/Button[@number='1']/Action[@type='onclick']/*");
    String xpathStr = "//Screen[@number='2007']/Button[@number='87'][@h='1']";
    XPathExpression expr = xpath.compile(xpathStr);

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
      NamedNodeMap nodeMap = nodes.item(i).getAttributes();
      String attrName = "";
      for (int j = 0; j < nodeMap.getLength(); j++) {
        attrName = xpathStr.substring(xpathStr.lastIndexOf('@') + 1, xpathStr.lastIndexOf("="));
        if (nodes.item(i).getAttributes().item(j).getNodeName().equals(attrName)) {
          System.out.println(nodes.item(i).getAttributes().item(j).getNodeValue());
        }
      }
    }
  }
示例#19
0
  /**
   * Returns a sorted list of attributes.
   *
   * @param attrs Description of the Parameter
   * @return Description of the Return Value
   */
  protected Attr[] sortAttributes(NamedNodeMap attrs) {

    int len = (attrs != null) ? attrs.getLength() : 0;
    Attr array[] = new Attr[len];
    for (int i = 0; i < len; i++) {
      array[i] = (Attr) attrs.item(i);
    }

    for (int i = 0; i < len - 1; i++) {
      String name = array[i].getNodeName();
      int index = i;
      for (int j = i + 1; j < len; j++) {
        String curName = array[j].getNodeName();
        if (curName.compareTo(name) < 0) {
          name = curName;
          index = j;
        }
      }
      if (index != i) {
        Attr temp = array[i];
        array[i] = array[index];
        array[index] = temp;
      }
    }

    return array;
  }
 /*
  * @see com.sun.org.apache.xml.internal.utils.PrefixResolverDefault
  */
 protected String inferNamespaceURI(String prefix) {
   Node parent = namespaceContext;
   String namespace = null;
   int type;
   while ((null != parent)
       && (null == namespace)
       && (((type = parent.getNodeType()) == Node.ELEMENT_NODE)
           || (type == Node.ENTITY_REFERENCE_NODE))) {
     if (type == Node.ELEMENT_NODE) {
       if (parent.getNodeName().indexOf(prefix + ":") == 0) {
         return parent.getNamespaceURI();
       }
       NamedNodeMap nnm = parent.getAttributes();
       for (int i = 0; i < nnm.getLength(); i++) {
         Node attr = nnm.item(i);
         String aname = attr.getNodeName();
         boolean isPrefix = aname.startsWith("xmlns:");
         if (isPrefix || aname.equals("xmlns")) {
           int index = aname.indexOf(':');
           String p = isPrefix ? aname.substring(index + 1) : "";
           if (p.equals(prefix)) {
             namespace = attr.getNodeValue();
             break;
           }
         }
       }
     }
     parent = parent.getParentNode();
   }
   return namespace;
 }
示例#21
0
  public void createOrUpdateProject(NamedNodeMap nodeMap, ProjectDAO dao) {
    Project project = new Project(); // проект из БД

    // поля синхронизации
    String name = nodeMap.getNamedItem("name").getNodeValue().trim(); // название проекта
    String idProject = nodeMap.getNamedItem("id").getNodeValue(); // id проекта
    String status = nodeMap.getNamedItem("status").getNodeValue(); // статус проекта
    String pmLdap = nodeMap.getNamedItem("pm").getNodeValue(); // руководитель проекта
    String hcLdap = nodeMap.getNamedItem("hc").getNodeValue(); // hc

    // ищем в БД запись о проекте
    Project findingProject = dao.findByProjectId(idProject);
    if (findingProject == null) { // если проекта еще нет в БД
      project.setActive(newStatus.contains(status)); // установим ему новый статус
    } else {
      // если проект уже существовал - статус менять не будем
      // см. //APLANATS-408
      project.setActive(findingProject.isActive());
    }

    project.setName(name);
    project.setProjectId(idProject);

    if (project.isActive()) {
      if (!setPM(project, pmLdap)) {
        return; // если не указан РП или его нет в БД, то проект не сохраняем, переходим к
                // следующему
      }
      setDivision(project, hcLdap); // установим подразделение пользователя
    }
    dao.store(project); // запишем в БД
  }
 /**
  * Internal method used to copy from manifest Application to PhoneLabApplication class instance
  *
  * @param app
  * @param element
  */
 private void copyApp(PhoneLabApplication app, Element element) {
   NamedNodeMap map = element.getAttributes();
   for (int i = 0; i < map.getLength(); i++) {
     Node attr = map.item(i);
     if (attr.getNodeName().equals("intent_name")) {
       app.setIntentName(attr.getNodeValue());
     } else if (attr.getNodeName().equals("package_name")) {
       app.setPackageName(attr.getNodeValue());
     } else if (attr.getNodeName().equals("name")) {
       app.setName(attr.getNodeValue());
     } else if (attr.getNodeName().equals("description")) {
       app.setDescription(attr.getNodeValue());
     } else if (attr.getNodeName().equals("type")) {
       app.setType(attr.getNodeValue());
     } else if (attr.getNodeName().equals("participantinitiated")) {
       if (attr.getNodeValue().equals("yes")) app.setParticipantInitiated(true);
       else app.setParticipantInitiated(false);
     } else if (attr.getNodeName().equals("download")) {
       app.setDownload(attr.getNodeValue());
     } else if (attr.getNodeName().equals("version")) {
       app.setVersion(attr.getNodeValue());
     } else if (attr.getNodeName().equals("action")) {
       app.setAction(attr.getNodeValue());
     }
   }
 }
  public List<String> getNodeDetails(NamespaceContext nsc, String exprString, String filePath)
      throws XPathExpressionException {

    List<String> list = new ArrayList<String>();
    XPathFactory factory = XPathFactory.newInstance();

    // 2. Use the XPathFactory to create a new XPath object
    XPath xpath = factory.newXPath();

    xpath.setNamespaceContext(nsc);

    // 3. Compile an XPath string into an XPathExpression
    XPathExpression expression = xpath.compile(exprString);

    // 4. Evaluate the XPath expression on an input document
    Node result =
        (Node) expression.evaluate(new org.xml.sax.InputSource(filePath), XPathConstants.NODE);

    String svcName = null;
    NamedNodeMap attMap = result.getAttributes();
    Node att = attMap.getNamedItem("group");
    if (att != null) svcName = att.getNodeValue();
    if (result != null) {
      list.add(result.getNodeName());
      list.add(result.getTextContent());
      list.add(svcName);
    }
    factory = null;
    xpath = null;
    expression = null;
    result = null;
    attMap = null;
    att = null;
    return list;
  }
示例#24
0
  TableMeta(Node tableNode) {
    NamedNodeMap attribs = tableNode.getAttributes();

    name = attribs.getNamedItem("name").getNodeValue();

    Node commentNode = attribs.getNamedItem("comments");
    if (commentNode != null) {
      String tmp = commentNode.getNodeValue().trim();
      comments = tmp.length() == 0 ? null : tmp;
    } else {
      comments = null;
    }

    Node remoteSchemaNode = attribs.getNamedItem("remoteSchema");
    if (remoteSchemaNode != null) {
      remoteSchema = remoteSchemaNode.getNodeValue().trim();
    } else {
      remoteSchema = null;
    }

    logger.fine(
        "Found XML table metadata for "
            + name
            + " remoteSchema: "
            + remoteSchema
            + " comments: "
            + comments);

    NodeList columnNodes = ((Element) tableNode.getChildNodes()).getElementsByTagName("column");

    for (int i = 0; i < columnNodes.getLength(); ++i) {
      Node colNode = columnNodes.item(i);
      columns.add(new TableColumnMeta(colNode));
    }
  }
  @Override
  protected void setBandsElement(SpatioTemporalImageReader reader) {
    GRIB1SpatioTemporalImageReader grib1Reader = ((GRIB1SpatioTemporalImageReader) reader);
    final int imageIndex = getImageIndex();
    Band band = addBand();

    try {
      IIOMetadata metadata = grib1Reader.getImageMetadata(imageIndex);
      if (metadata instanceof BaseImageMetadata) {
        final BaseImageMetadata commonMetadata = (BaseImageMetadata) metadata;
        setBandFromCommonMetadata(band, commonMetadata);
        Node node = commonMetadata.getAsTree(GRIB1ImageMetadata.nativeMetadataFormatName);
        node = node.getFirstChild();
        if (node != null) {
          node = node.getNextSibling();
          if (node != null) {
            final NamedNodeMap attributesMap = node.getAttributes();
            if (attributesMap != null) {
              Node units = attributesMap.getNamedItem(GRIB1ImageMetadata.PROD_PARAMETER_UNIT);
              if (units != null) {
                String unit = units.getNodeValue();
                if (unit != null) {
                  band.setUoM(unit);
                }
              }
            }
          }
        }
      }

    } catch (IOException e) {
      if (LOGGER.isLoggable(Level.WARNING)) LOGGER.warning("Unable to set band metadata");
    }
  }
示例#26
0
 /**
  * Check SOS response for xsi:schemaLocation, remove attribute and add attribute to SOAP message
  *
  * @param xmlObject
  * @param soapResponseMessage SOAP response message
  * @throws SOAPException If an error occurs
  */
 private void addAndRemoveSchemaLocationForSOAP(
     XmlObject xmlObject, SOAPMessage soapResponseMessage) throws SOAPException {
   String value = null;
   Node nodeToRemove = null;
   NamedNodeMap attributeMap = xmlObject.getDomNode().getFirstChild().getAttributes();
   for (int i = 0; i < attributeMap.getLength(); i++) {
     Node node = attributeMap.item(i);
     if (node.getLocalName().equals(W3CConstants.AN_SCHEMA_LOCATION)) {
       value = node.getNodeValue();
       nodeToRemove = node;
     }
   }
   if (nodeToRemove != null) {
     attributeMap.removeNamedItem(nodeToRemove.getNodeName());
   }
   SOAPEnvelope envelope = soapResponseMessage.getSOAPPart().getEnvelope();
   StringBuilder string = new StringBuilder();
   string.append(envelope.getNamespaceURI());
   string.append(BLANK_CHAR);
   string.append(envelope.getNamespaceURI());
   if (value != null && !value.isEmpty()) {
     string.append(BLANK_CHAR);
     string.append(value);
   }
   envelope.addAttribute(N52XmlHelper.getSchemaLocationQNameWithPrefix(), string.toString());
 }
示例#27
0
 private String nodeToString(final Element elem) {
   final StringBuffer stringBuffer = new StringBuffer();
   stringBuffer.append(Constants.LESS_THAN).append(elem.getNodeName());
   final NamedNodeMap namedNodeMap = elem.getAttributes();
   for (int i = 0; i < namedNodeMap.getLength(); i++) {
     stringBuffer
         .append(Constants.STRING_BLANK)
         .append(namedNodeMap.item(i).getNodeName())
         .append(Constants.EQUAL)
         .append(Constants.QUOTATION + namedNodeMap.item(i).getNodeValue() + Constants.QUOTATION);
   }
   stringBuffer.append(Constants.GREATER_THAN);
   final NodeList nodeList = elem.getChildNodes();
   for (int i = 0; i < nodeList.getLength(); i++) {
     final Node node = nodeList.item(i);
     if (node.getNodeType() == Node.ELEMENT_NODE) {
       // If the type of current node is ELEMENT_NODE, process it
       stringBuffer.append(nodeToString((Element) node));
     }
     if (node.getNodeType() == Node.TEXT_NODE) {
       stringBuffer.append(node.getNodeValue());
     }
   }
   stringBuffer.append("</").append(elem.getNodeName()).append(Constants.GREATER_THAN);
   return stringBuffer.toString();
 }
示例#28
0
  private void gatherNamespaces(Element element, List<URI> namespaceSources) throws SAXException {
    NamedNodeMap attributes = element.getAttributes();
    int attributeCount = attributes.getLength();

    for (int i = 0; i < attributeCount; i++) {
      Attr attribute = (Attr) attributes.item(i);
      String namespace = attribute.getNamespaceURI();

      if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespace)) {
        try {
          namespaceSources.add(new URI(attribute.getValue()));
        } catch (URISyntaxException e) {
          throw new SAXException(
              "Cannot validate this document with this class.  Namespaces must be valid URIs.  Found Namespace: '"
                  + attribute.getValue()
                  + "'.",
              e);
        }
      }
    }

    NodeList childNodes = element.getChildNodes();
    int childCount = childNodes.getLength();
    for (int i = 0; i < childCount; i++) {
      Node child = childNodes.item(i);

      if (child.getNodeType() == Node.ELEMENT_NODE) {
        gatherNamespaces((Element) child, namespaceSources);
      }
    }
  }
  protected void processDocument(Document document, PrintWriter writer) {
    String type = new StencilSetUtil().getStencilSet(document);
    SyntaxChecker checker = null;
    if (type != null) {
      if (type.equals("bpmn.json") || type.equals("bpmneec.json"))
        checker = getCheckerBPMN(document);
      else if (type.equals("bpmn1.1.json")) checker = getCheckerBPMN11(document);
      else if (type.equals("ibpmn.json")) checker = getCheckerIBPMN(document);
      else if (type.equals("interactionpetrinets.json")) checker = getCheckerIPN(document);
      else if (type.equals("epc.json")) checker = getCheckerEPC(document);
    }

    if (checker == null) { // try eRDF
      try {
        NamedNodeMap map =
            XPathAPI.selectSingleNode(document, "//a[@rel='oryx-stencilset']").getAttributes();
        type = map.getNamedItem("href").getNodeValue();
      } catch (TransformerException e) {
        e.printStackTrace();
      }
      if (type != null && type.endsWith("petrinet.json")) {
        checker = getCheckerPetriNet(document);
      }
    }

    if (checker == null) {
      writer.print("{}");
    } else {
      checker.checkSyntax();
      writer.print(checker.getErrorsAsJson().toString());
    }
  }
示例#30
0
  void displayMetadata(Node node, int level) {
    // print open tag of element
    indent(level);
    System.out.print("<" + node.getNodeName());
    NamedNodeMap map = node.getAttributes();
    if (map != null) {

      // print attribute values
      int length = map.getLength();
      for (int i = 0; i < length; i++) {
        Node attr = map.item(i);
        System.out.print(" " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
      }
    }

    Node child = node.getFirstChild();
    if (child == null) {
      // no children, so close element and return
      System.out.println("/>");
      return;
    }

    // children, so close current tag
    System.out.println(">");
    while (child != null) {
      // print children recursively
      displayMetadata(child, level + 1);
      child = child.getNextSibling();
    }

    // print close tag of element
    indent(level);
    System.out.println("</" + node.getNodeName() + ">");
  }