Example #1
0
  /**
   * The net effect of this method is that (subject to flags), true is returned if 'node' is the
   * descendant (not really a child) of a tag with a local name in the list of 'names'.
   *
   * <p>TODO C.B: I hate method. Need to rename and possibly rewrite
   *
   * @param names -- check this list for valid local names
   * @param node -- the node to check
   * @param ignoreCase -- if true, each node name has toLowerCase applied to it before checking for
   *     it names. NOTE: this assumes that names is already in lowercase. TODO: this is crappy
   *     assumption
   * @param noSame -- if true, then node is skipped and only its parent nodes are checked
   * @return true if the local name of node or one of its parents is in the array of Strings called
   *     names.
   */
  public static boolean isChild(
      final String names[], Node node, boolean ignoreCase, boolean noSame) {
    if (node == null) {
      return false;
    }
    if (noSame) {
      node = node.getParentNode();
    }

    final List namesAsList = Arrays.asList(names);

    while (node != null && !isDocument(node)) {
      String nodeName = node.getLocalName();

      if (nodeName != null) {
        if (ignoreCase) {
          nodeName = nodeName.toLowerCase();
        }

        if (namesAsList.contains(nodeName)) {
          return true;
        }
      }
      Node oldNode = node;
      node = node.getParentNode();
      if (oldNode == node) {
        throw new IllegalStateException("Infinite loop discovered in DOM tree"); // $NON-NLS-1$
      }
    }
    return false;
  }
  /**
   * Handle text node during validation.
   *
   * @param received
   * @param source
   */
  private void doText(Node received, Node source) {
    if (log.isDebugEnabled()) {
      log.debug("Validating node value for element: " + received.getParentNode());
    }

    if (received.getNodeValue() != null) {
      Assert.isTrue(
          source.getNodeValue() != null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              null,
              received.getNodeValue().trim()));

      Assert.isTrue(
          received.getNodeValue().trim().equals(source.getNodeValue().trim()),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              source.getNodeValue().trim(),
              received.getNodeValue().trim()));
    } else {
      Assert.isTrue(
          source.getNodeValue() == null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              source.getNodeValue().trim(),
              null));
    }

    if (log.isDebugEnabled()) {
      log.debug("Node value '" + received.getNodeValue().trim() + "': OK");
    }
  }
Example #3
0
  /**
   * Retrieves the prefix associated with a namespace URI in the given context node.
   *
   * @param namespaceURI the namespace whose prefix is required
   * @param contextNode the node where to search for namespace declarations
   * @return the prefix associated with the namespace URI; the empty string indicates the default
   *     namespace, while <code>null</code> indicates no association
   */
  public static String getPrefix(String namespaceURI, Node contextNode) {
    switch (contextNode.getNodeType()) {
      case Node.ATTRIBUTE_NODE:
        contextNode = ((Attr) contextNode).getOwnerElement();
        break;
      case Node.ELEMENT_NODE:
        break;
      default:
        contextNode = contextNode.getParentNode();
    }

    while (contextNode != null && contextNode.getNodeType() == Node.ELEMENT_NODE) {
      Element contextElem = (Element) contextNode;
      NamedNodeMap attributes = contextElem.getAttributes();

      for (int i = 0, n = attributes.getLength(); i < n; i++) {
        Node attr = attributes.item(i);
        if (namespaceURI.equals(attr.getNodeValue())) {
          String prefix = attr.getPrefix();
          if ("xmlns".equals(prefix)) {
            return attr.getLocalName();
          } else if (prefix == null && "xmlns".equals(attr.getLocalName())) {
            return "";
          }
        }
      }
      contextNode = contextNode.getParentNode();
    }
    return null;
  }
Example #4
0
  protected StructuredSelection getNewSelection(Node node) {
    int type = node.getNodeType();
    if (type == 1) {
      // node type = element
      PictogramElement pe = null;
      Element elem = (Element) node;
      String value = elem.getAttribute("bpmnElement"); // $NON-NLS-1$
      if (value != null) {
        pe = findPictogramElement(value);
      }

      if (pe == null) {
        value = elem.getAttribute("id"); // $NON-NLS-1$
        if (value != null) pe = findPictogramElement(value);
      }

      if (pe != null) {
        return new StructuredSelection(pe);
      }
      return getNewSelection(node.getParentNode());
    } else if (type == 2) {
      // node type = attribute
      // search the attribute's owner
      Attr attr = (Attr) node;
      return getNewSelection(attr.getOwnerElement());
    } else if (type == 3) {
      // node type = text
      return getNewSelection(node.getParentNode());
    }
    return null;
  }
Example #5
0
 void lookupPrefix(org.w3c.dom.Node node) {
   if (node == null) throw new IllegalArgumentException("node must not be null");
   String prefix = node.lookupPrefix(namespace.getUri());
   if (prefix == null) {
     //    check to see if we match the default namespace
     String defaultNamespace = node.lookupNamespaceURI(null);
     if (defaultNamespace == null) defaultNamespace = "";
     String nodeNamespace = namespace.getUri();
     if (nodeNamespace.equals(defaultNamespace)) {
       prefix = "";
     }
   }
   int i = 0;
   while (prefix == null) {
     String generatedPrefix = "e4x_" + i++;
     String generatedUri = node.lookupNamespaceURI(generatedPrefix);
     if (generatedUri == null) {
       prefix = generatedPrefix;
       org.w3c.dom.Node top = node;
       while (top.getParentNode() != null
           && top.getParentNode() instanceof org.w3c.dom.Element) {
         top = top.getParentNode();
       }
       ((org.w3c.dom.Element) top)
           .setAttributeNS(
               "http://www.w3.org/2000/xmlns/", "xmlns:" + prefix, namespace.getUri());
     }
   }
   namespace.setPrefix(prefix);
 }
Example #6
0
 public static boolean isTextNode(Node node) {
   return node.getParentNode() != null
       //        && node.getParentNode().getNodeName().equals("#comment")    // todo why is this
       // commented out?
       && "#text".equalsIgnoreCase(node.getNodeName())
       && !"STYLE".equalsIgnoreCase(node.getParentNode().getNodeName())
       && !"SCRIPT".equalsIgnoreCase(node.getParentNode().getNodeName());
 }
  /**
   * getCommonAncestor method
   *
   * @return org.w3c.dom.Node
   * @param node org.w3c.dom.Node
   */
  private Node getCommonAncestor(Node node1, Node node2) {
    if (node1 == null || node2 == null) return null;

    for (Node na = node2; na != null; na = na.getParentNode()) {
      for (Node ta = node1; ta != null; ta = ta.getParentNode()) {
        if (ta == na) return ta;
      }
    }
    return null; // not found
  }
  private NodeLocationWithParentImpl(
      Node node,
      String id,
      String path,
      Node cachedParent,
      String cachedParentId,
      boolean cacheIfPossible,
      ClientDocumentStfulDelegateImpl clientDoc) {
    super(clientDoc);

    if (node == null) throw new ItsNatException("INTERNAL ERROR");

    this.nodeLocationDeleg = getNodeLocationNotParent(node, id, path, clientDoc);

    this.cachedParent = cachedParent;
    this.cachedParentId = cachedParentId;

    NodeCacheRegistryImpl nodeCache = clientDoc.getNodeCacheRegistry();
    if ((nodeCache != null)
        && cacheIfPossible) // Aunque esté cacheado el nodo principal aprovechamos para cachear los
    // padres.
    {
      // Cacheamos unos cuantos padres inmediatos para que los nodos "adyacentes" (de la zona en
      // general)
      // puedan encontrarse más rápidamente, sobre todo si el cachedParent no se encontró o está muy
      // arriba.

      int maxParents =
          3; // Un valor razonable para evitar cachear en exceso nodos padre (y enviar demasiado
      // JavaScript)
      // que a lo mejor no se usan nunca ni para el cálculo de paths
      Node currParent = node.getParentNode();
      for (int i = 0;
          (currParent != null) && (currParent != cachedParent) && (i < maxParents);
          i++) {
        String parentId = nodeCache.getId(currParent);
        if (parentId == null) // No cacheado
        {
          parentId = nodeCache.addNode(currParent);
          if (parentId != null) {
            // Hemos cacheado un nuevo nodo, DEBEMOS LLAMAR toJSArray y enviar al cliente
            // de otra manera el cliente NO se enterará de este cacheado.
            if (newCachedParentIds == null)
              this.newCachedParentIds = new ArrayList<String>(maxParents);
            newCachedParentIds.add(parentId);
            currParent = currParent.getParentNode();
            i++;
          } else currParent = null; // No se puede cachear, paramos
        } else currParent = null; // Ya cacheado, paramos
      }
    }

    if ((nodeLocationDeleg instanceof NodeLocationAlreadyCachedNotParentImpl)
        && !isNull(cachedParentId)) throw new ItsNatException("INTERNAL ERROR");
  }
  /* get an ancestor element ignoring implicit ones. */
  public static Element getParentElement(Node child) {
    if (child == null) return null;

    Node p = child.getParentNode();
    while (p != null) {
      if (p.getNodeType() == Node.ELEMENT_NODE) {
        return (Element) p;
      }
      p = p.getParentNode();
    }
    return null;
  }
Example #10
0
  /** Reads the configuration file and sets up the filter rules. */
  protected synchronized void loadConfiguration() throws ServletException {

    if (configFileName == null) {
      // Missing init parameter? That's okay, perhaps there is nothing to
      // redirect.
      return;
    }

    File configFile = new File(configFileName);
    DocumentBuilderFactory docBuildFac = DocumentBuilderFactory.newInstance();

    DocumentBuilder docBuild;
    try {
      if (docBuildFac.isValidating()) docBuildFac.setValidating(false);
      docBuild = docBuildFac.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      // Problems with the XML parser? Very unlikely, the container wouldn't
      // work at all. Whatever it is, it is serious, we give up.
      throw new ServletException(e.getMessage());
    }

    Document doc;
    try {
      doc = docBuild.parse(configFile);
    } catch (IOException e) {
      // File configFile not found, or similar.
      throw new ServletException(e.getMessage());
    } catch (SAXException e) {
      // Invalid XML in configFile, or similar.
      throw new ServletException(e.getMessage());
    }

    redirectRules = new Vector<RedirectRule>();

    Node node = doc.getDocumentElement();
    while (node != null) {
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        RedirectRule rule = loadRule((Element) node);
        if (rule != null) redirectRules.add(rule);
      }
      if (node.hasChildNodes() == true) node = node.getFirstChild();
      else if (node.getNextSibling() != null) node = node.getNextSibling();
      else if (node.getParentNode() != null) node = node.getParentNode().getNextSibling();
      else node = null;
    }

    filterConfig
        .getServletContext()
        .log(filterName + ": Loaded " + redirectRules.size() + " rule(s).");
  }
Example #11
0
  protected static void importNodeAfter(Node after, Node source, boolean deep) {
    Node nodeNew = DBSetup.copyNode(after.getOwnerDocument(), source, deep);

    // ////////////////////////////////////////////////
    // Append the node to the target

    Node nodeNext = after.getNextSibling();

    if (nodeNext != null) after.getParentNode().insertBefore(nodeNew, after);
    else after.getParentNode().appendChild(nodeNew);

    // Get Children
    // if(deep == true)
    // DBSetup.importChildNodes(nodeNew, source, deep);
  }
 /*
  * @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;
 }
 /**
  * Update an application in the manifest
  *
  * @param app app to replace for
  */
 public void updateApplication(PhoneLabApplication app) {
   try {
     Node node =
         (Node)
             xpath.evaluate(
                 "/manifest/statusmonitor/parameter[@package_name='" + app.getPackageName() + "']",
                 document,
                 XPathConstants.NODE);
     if (node != null) { // exist
       Node parentNode = node.getParentNode();
       parentNode.removeChild(node);
       Element newElement = document.createElement("application");
       if (app.getPackageName() != null)
         newElement.setAttribute("package_name", app.getPackageName());
       if (app.getName() != null) newElement.setAttribute("name", app.getName());
       if (app.getDescription() != null)
         newElement.setAttribute("description", app.getDescription());
       if (app.getType() != null) newElement.setAttribute("type", app.getType());
       if (app.getStartTime() != null) newElement.setAttribute("start_time", app.getStartTime());
       if (app.getEndTime() != null) newElement.setAttribute("end_time", app.getEndTime());
       if (app.getDownload() != null) newElement.setAttribute("download", app.getDownload());
       if (app.getVersion() != null) newElement.setAttribute("version", app.getVersion());
       if (app.getAction() != null) newElement.setAttribute("action", app.getAction());
       document.getFirstChild().appendChild(newElement);
     }
   } catch (XPathExpressionException e) {
     e.printStackTrace();
   }
 }
Example #14
0
 public static boolean setProjectionDefault(Object flavor, String tableName, ValMap map) {
   if (ProfileManager.transportsLoaded()) {
     String xpath = ProfileManager.transportsSelector + flavorSelector(flavor);
     Element element = selectElement(ProfileManager.transports, xpath);
     if (element != null && notNullOrEmpty(tableName)) {
       Element el = ProfileManager.transports.createElement("PROJECTION");
       try {
         BidiMultiMap projection = (BidiMultiMap) map.get("projection");
         xmlSerialize(projection, el, null);
         el.setAttribute("version", "" + map.get("version"));
         el.setAttribute("table", tableName);
       } catch (Exception e) {
         Log.e(TAG, "setDefaultProjection", e);
         return false;
       }
       NodeList nodes = evaluateXPath(element, "." + projectionSelector(tableName));
       if (nodes != null && nodes.getLength() > 0) {
         Node node = nodes.item(0);
         node.getParentNode().replaceChild(el, node);
       } else element.appendChild(el);
       ProfileManager.saveTransports();
       return true;
     }
   }
   return false;
 }
Example #15
0
  public IAdaptable getAdaptable(Node node) {
    if (node == null) return null;

    IAdaptable element = getAdaptableRegistry().getAdaptable(node);
    if (element == null) {
      if (node instanceof Element) {
        Element e = (Element) node;
        String tagName = e.getTagName();
        if (TAG_P.equals(tagName)) {
          element = new ParagraphImpl(e, this);
        } else if (DOMConstants.TAG_SPAN.equals(tagName)) {
          element = new TextSpanImpl(e, this);
        } else if (DOMConstants.TAG_IMG.equals(tagName)) {
          element = new ImageSpanImpl(e, this);
        } else if (DOMConstants.TAG_A.equals(tagName)) {
          element = new HyperlinkSpanImpl(e, this);
        }
      } else {
        Node p = node.getParentNode();
        if (p instanceof Element) {
          if (TAG_P.equals(p.getNodeName()) || TAG_A.equals(p.getNodeName()))
            element = new TextSpanImpl(node, this);
        }
      }
      if (element != null) {
        getAdaptableRegistry().register(element, node);
      }
    }
    return element;
  }
 /*     */ Node getNextSibling(Node node, Node root) /*     */ {
   /* 311 */ if ((node == null) || (node == root)) return null;
   /*     */
   /* 313 */ Node newNode = node.getNextSibling();
   /* 314 */ if (newNode == null)
   /*     */ {
     /* 316 */ newNode = node.getParentNode();
     /*     */
     /* 318 */ if ((newNode == null) || (newNode == root)) return null;
     /*     */
     /* 320 */ int parentAccept = acceptNode(newNode);
     /*     */
     /* 322 */ if (parentAccept == 3) {
       /* 323 */ return getNextSibling(newNode, root);
       /*     */ }
     /*     */
     /* 326 */ return null;
     /*     */ }
   /*     */
   /* 329 */ int accept = acceptNode(newNode);
   /*     */
   /* 331 */ if (accept == 1) {
     /* 332 */ return newNode;
     /*     */ }
   /* 334 */ if (accept == 3) {
     /* 335 */ Node fChild = getFirstChild(newNode);
     /* 336 */ if (fChild == null) {
       /* 337 */ return getNextSibling(newNode, root);
       /*     */ }
     /* 339 */ return fChild;
     /*     */ }
   /*     */
   /* 344 */ return getNextSibling(newNode, root);
   /*     */ }
Example #17
0
 /**
  * Searches for namespace prefix declarations in the given node. For any prefix declaration, it
  * invokes {@link #declare(String, String)}. This method works recursively: The parent nodes
  * prefix declarations are collected before the current nodes.
  */
 public void searchAllPrefixDeclarations(Node pNode) {
   Node parent = pNode.getParentNode();
   if (parent != null) {
     searchAllPrefixDeclarations(parent);
   }
   searchLocalPrefixDeclarations(pNode);
 }
Example #18
0
 public void removeDomNodes(String xpath) throws XmlException {
   xpath = initXPathNamespaces(xpath);
   Node[] nodes = getDomNodes(xpath);
   for (Node node : nodes) {
     node.getParentNode().removeChild(node);
   }
 }
  @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);
  }
  public static NodeLocationWithParentImpl getNodeLocationWithParentUsingCache(
      Node node, String id, boolean cacheIfPossible, NodeCacheRegistryImpl nodeCache) {
    // nodeCache NO puede ser nulo

    // Se supone que el nodo no ha sido cacheado en el cliente todavía  aunque tenga
    // un id asignado en el servidor (este id puede ser null si no ha sido cacheado en el servidor)
    // por lo que hay que obtener un path, absoluto o relativo respecto a un padre cacheado.

    // Buscamos un nodo padre que esté cacheado para evitar formar un path
    // absoluto que lleva tiempo.

    String parentId = null;
    Node parent = node;

    do {
      parent = parent.getParentNode();
      parentId = nodeCache.getId(parent); // si cachedParent es null devuelve null
    } while ((parentId == null) && (parent != null));

    ClientDocumentStfulDelegateImpl clientDoc = nodeCache.getClientDocumentStfulDelegate();
    String path =
        clientDoc.getStringPathFromNode(
            node,
            parent); // Si cachedParent es null (cachedParentId es null) devuelve un path absoluto

    return new NodeLocationWithParentImpl(
        node, id, path, parent, parentId, cacheIfPossible, clientDoc);
  }
Example #21
0
  public boolean killSite() {
    Document doc;
    final File spec;
    try {
      spec = new File(hostRoot + "/hosts.xml");
      final BufferedReader reader = new BufferedReader(new FileReader(spec));
      String line = "";
      String xml = "";
      while ((line = reader.readLine()) != null) xml += line;
      reader.close();
      doc = DocumentUtils.impl.createDocumentFromString(xml);
    } catch (IOException e) {
      return false;
    }

    if (doc == null) return false;

    NodeList nodes = doc.getElementsByTagName("host");
    for (int i = 0; i < nodes.getLength(); i++) {
      Node current = nodes.item(i);
      if (current.getNodeName().equals("host")
          && DocumentUtils.impl.getAttribute(current, "id").equals(siteID)) {
        current.getParentNode().removeChild(current);
      }
    }

    return writeHostFile(doc, spec);
  }
 private DataserviceTagElement getCurrentDataserviceElement(
     ContentAssistRequest contentAssistRequest) {
   List<String> path = new ArrayList<String>();
   Node currentNode = getCurrentNode(contentAssistRequest);
   while (currentNode != null) {
     if (!(currentNode instanceof Text) && currentNode.getOwnerDocument() != null) {
       path.add(currentNode.getNodeName());
     }
     currentNode = currentNode.getParentNode();
   }
   DataserviceTagElement rootElement = DataserviceTemplate.getRootElement();
   DataserviceTagElement currentElement = null;
   if (rootElement.getName().equals(path.get(path.size() - 1))) {
     currentElement = rootElement;
   } else {
     return null;
   }
   for (int i = path.size() - 2; i >= 0; i--) {
     String s = path.get(i);
     DataserviceTagElement subElement = currentElement.getSubElement(s);
     if (subElement == null) {
       return null;
     } else {
       currentElement = subElement;
     }
   }
   return currentElement;
 }
Example #23
0
  /**
   * Removes all the given tags from the document.
   *
   * @param dom the document object.
   * @param tagName the tag name, examples: script, style, meta
   * @return the changed dom.
   */
  public static Document removeTags(Document dom, String tagName) {
    if (dom != null) {
      // NodeList list = dom.getElementsByTagName("SCRIPT");

      NodeList list;
      try {
        list = XPathHelper.evaluateXpathExpression(dom, "//" + tagName.toUpperCase());

        while (list.getLength() > 0) {
          Node sc = list.item(0);

          if (sc != null) {
            sc.getParentNode().removeChild(sc);
          }

          list = XPathHelper.evaluateXpathExpression(dom, "//" + tagName.toUpperCase());
          // list = dom.getElementsByTagName("SCRIPT");
        }
      } catch (XPathExpressionException e) {
        LOGGER.error(e.getMessage(), e);
      }

      return dom;
    }

    return null;
  }
Example #24
0
  /**
   * Internal function. Return the previousSibling Node, from the input node after applying filter,
   * whatToshow. NEVER TRAVERSES ABOVE THE SPECIFIED ROOT NODE. The current node is not consulted or
   * set.
   */
  Node getPreviousSibling(Node node, Node root) {

    if (node == null || isSameNode(node, root)) return null;

    Node newNode = node.getPreviousSibling();
    if (newNode == null) {

      newNode = node.getParentNode();
      if (newNode == null || isSameNode(newNode, root)) return null;

      int parentAccept = acceptNode(newNode);

      if (parentAccept == NodeFilter.FILTER_SKIP) {
        return getPreviousSibling(newNode, root);
      }

      return null;
    }

    int accept = acceptNode(newNode);

    if (accept == NodeFilter.FILTER_ACCEPT) return newNode;
    else if (accept == NodeFilter.FILTER_SKIP) {
      Node fChild = getLastChild(newNode);
      if (fChild == null) {
        return getPreviousSibling(newNode, root);
      }
      return fChild;
    } else
    // if (accept == NodeFilter.REJECT_NODE)
    {
      return getPreviousSibling(newNode, root);
    }
  } // getPreviousSibling(Node node) {
Example #25
0
  /**
   * Pretty prints a node.
   *
   * @param doc The document the node comes from.
   * @param node The node that should be pretty printed.
   */
  public static void prettyPrint(Document doc, Node node) {
    // Get the text before the node and extract the indenting
    Node parent = node.getParentNode();

    String indenting = "";
    NodeList siblingList = parent.getChildNodes();
    for (int i = 1; i < siblingList.getLength(); i++) {
      Node sibling = siblingList.item(i);
      if (sibling == node) {
        Node nodeBefore = siblingList.item(i - 1);
        // Check whether this is a text node
        if (nodeBefore.getNodeName().equals("#text")) {
          // There is text before the node -> Extract the indenting
          String text = nodeBefore.getNodeValue();
          int newlinePos = text.lastIndexOf('\n');
          if (newlinePos != -1) {
            indenting = text.substring(newlinePos);
            if (indenting.trim().length() != 0) {
              // The indenting is no whitespace -> Forget it
              indenting = "";
            }
          }
        }
        break;
      }
    }

    // Now pretty print the node
    prettyPrint(doc, node, indenting);
  }
 private Node getCurrentNode(ContentAssistRequest contentAssistRequest) {
   Node currentNode = contentAssistRequest.getParent();
   if (currentNode instanceof Text) {
     currentNode = currentNode.getParentNode();
   }
   return currentNode;
 }
Example #27
0
  public void delete()
      throws ParserConfigurationException, SAXException, IOException, TransformerException {
    Document document = new GetDocument().getDocument();
    Element rootElement = document.getDocumentElement();
    NodeList contacts = rootElement.getChildNodes();

    System.out.println("Enter the name of the contact to delete: ");
    BufferedReader inItem = new BufferedReader(new InputStreamReader(System.in));
    String contactToDelete = inItem.readLine();

    boolean isContactFound = false;

    for (int i = 0; i < contacts.getLength(); i++) {
      Node contact = contacts.item(i);
      NodeList contactData = contact.getChildNodes();

      for (int j = 0; j < contactData.getLength(); j++) {
        Node dataNode = contactData.item(j);
        if (dataNode.getNodeName().equals("name")
            && dataNode.getTextContent().equals(contactToDelete)) {
          contact.getParentNode().removeChild(contact);
          isContactFound = true;
          System.out.println("The contact " + contactToDelete + " has been deleted.");
        }
      }
    }
    Transform.transform(document);

    if (!isContactFound) System.out.println("No such contact found.");
  }
Example #28
0
 public void remove(int paramInt) {
   NodeList localNodeList = getElementsByTagName("OPTION");
   Node localNode = localNodeList.item(paramInt);
   if (localNode != null) {
     localNode.getParentNode().removeChild(localNode);
   }
 }
  private IHyperlink openModule(Node current, ITextViewer textViewer, int offset) {
    while (current != null && !(current instanceof Element)) {
      current = current.getParentNode();
    }
    if (current == null) {
      return null;
    }
    String pathUp = XmlUtils.pathUp(current, 2);
    if (!"modules/module".equals(pathUp)) { // $NON-NLS-1$
      // just in case we are in some random plugin configuration snippet..
      return null;
    }

    ITextFileBuffer buf =
        FileBuffers.getTextFileBufferManager().getTextFileBuffer(textViewer.getDocument());
    if (buf == null) {
      // for repository based poms..
      return null;
    }
    IFileStore folder = buf.getFileStore().getParent();

    String path = XmlUtils.getTextValue(current);
    final String fPath = path;
    // construct IPath for the child pom file, handle relative paths..
    while (folder != null && path.startsWith("../")) { // $NON-NLS-1$
      folder = folder.getParent();
      path = path.substring("../".length()); // $NON-NLS-1$
    }
    if (folder == null) {
      return null;
    }
    IFileStore modulePom = folder.getChild(path);
    if (!modulePom.getName().endsWith("xml")) { // $NON-NLS-1$
      modulePom = modulePom.getChild("pom.xml"); // $NON-NLS-1$
    }
    final IFileStore fileStore = modulePom;
    if (!fileStore.fetchInfo().exists()) {
      return null;
    }
    assert current instanceof IndexedRegion;
    final IndexedRegion region = (IndexedRegion) current;

    return new IHyperlink() {
      public IRegion getHyperlinkRegion() {
        return new Region(region.getStartOffset(), region.getEndOffset() - region.getStartOffset());
      }

      public String getHyperlinkText() {
        return NLS.bind(Messages.PomHyperlinkDetector_open_module, fPath);
      }

      public String getTypeLabel() {
        return "pom-module"; //$NON-NLS-1$
      }

      public void open() {
        openXmlEditor(fileStore);
      }
    };
  }
 /*     */ Node getPreviousSibling(Node node, Node root) /*     */ {
   /* 366 */ if ((node == null) || (node == root)) return null;
   /*     */
   /* 368 */ Node newNode = node.getPreviousSibling();
   /* 369 */ if (newNode == null)
   /*     */ {
     /* 371 */ newNode = node.getParentNode();
     /* 372 */ if ((newNode == null) || (newNode == root)) return null;
     /*     */
     /* 374 */ int parentAccept = acceptNode(newNode);
     /*     */
     /* 376 */ if (parentAccept == 3) {
       /* 377 */ return getPreviousSibling(newNode, root);
       /*     */ }
     /*     */
     /* 380 */ return null;
     /*     */ }
   /*     */
   /* 383 */ int accept = acceptNode(newNode);
   /*     */
   /* 385 */ if (accept == 1) {
     /* 386 */ return newNode;
     /*     */ }
   /* 388 */ if (accept == 3) {
     /* 389 */ Node fChild = getLastChild(newNode);
     /* 390 */ if (fChild == null) {
       /* 391 */ return getPreviousSibling(newNode, root);
       /*     */ }
     /* 393 */ return fChild;
     /*     */ }
   /*     */
   /* 398 */ return getPreviousSibling(newNode, root);
   /*     */ }