Exemple #1
0
  protected void testCopy(Element element) throws Exception {
    assertTrue("Not null", element != null);

    int attributeCount = element.attributeCount();
    int nodeCount = element.nodeCount();

    Element copy = element.createCopy();

    assertEquals("Node size not equal after copy", element.nodeCount(), nodeCount);
    assertTrue("Same attribute size after copy", element.attributeCount() == attributeCount);

    assertTrue("Copy has same node size", copy.nodeCount() == nodeCount);
    assertTrue("Copy has same attribute size", copy.attributeCount() == attributeCount);

    for (int i = 0; i < attributeCount; i++) {
      Attribute attr1 = element.attribute(i);
      Attribute attr2 = copy.attribute(i);

      assertTrue("Attribute: " + i + " name is equal", attr1.getName().equals(attr2.getName()));
      assertTrue("Attribute: " + i + " value is equal", attr1.getValue().equals(attr2.getValue()));
    }

    for (int i = 0; i < nodeCount; i++) {
      Node node1 = element.node(i);
      Node node2 = copy.node(i);

      assertTrue("Node: " + i + " type is equal", node1.getNodeType() == node2.getNodeType());
      assertTrue("Node: " + i + " value is equal", node1.getText().equals(node2.getText()));
    }
  }
    /*
     * Appends the given tag, including its body, to the XML view,
     * and optionally reset default namespace to "", if none specified.
     */
    private void appendTag(Node n, boolean addDefaultNS) throws JasperException {

      Node.Nodes body = n.getBody();
      String text = n.getText();

      buf.append("<").append(n.getQName());
      buf.append("\n");

      printAttributes(n, addDefaultNS);
      buf.append("  ").append(jspIdPrefix).append(":id").append("=\"");
      buf.append(jspId++).append("\"\n");

      if (ROOT_ACTION.equals(n.getLocalName()) || body != null || text != null) {
        buf.append(">\n");
        if (ROOT_ACTION.equals(n.getLocalName())) {
          if (compiler.getCompilationContext().isTagFile()) {
            appendTagDirective();
          } else {
            appendPageDirective();
          }
        }
        if (body != null) {
          body.visit(this);
        } else {
          appendText(text, false);
        }
        buf.append("</" + n.getQName() + ">\n");
      } else {
        buf.append("/>\n");
      }
    }
Exemple #3
0
    private void addTreeItem(JSONObject jsonObject, int index) {

      Node node =
          new Node(
              jsonObject.get("id").isString().stringValue(),
              jsonObject.get("leaf").isBoolean().booleanValue(),
              jsonObject.get("text").isString().stringValue());
      if (node.getText() != null) {
        TreeItem item = new TreeItem();
        item.setText(node.getText());
        item.setUserObject(node);
        if (!node.isLeaf()) item.addItem(""); // Temporarily add an item so we can expand this node

        treeItem.addItem(item);
      }
    }
 @Override
 public void performCopy(DataContext dataContext) {
   final Node selectedNode = getSelectedNode();
   assert selectedNode != null;
   final String plainText = selectedNode.getText(UsageViewImpl.this);
   CopyPasteManager.getInstance().setContents(new StringSelection(plainText.trim()));
 }
  @Override
  public String getText() {
    String text = "";

    for (Node node : children) text += node.getText();

    return text;
  }
  /**
   * If CS throws an exception it handled and transalated to a Openfire exception if possible. This
   * is done using <code>exceptionMap</code> that has a mapping from CS to OF. If no mapping is
   * found then it tries to instantiete the original exception. If this fails it throws a <code>
   * Exception</code> with the message of the CS exception.
   *
   * @param response the response from CS to check if it is an exception message.
   * @throws Exception if the response is an exception message.
   */
  private void checkFault(Element response) throws Exception {
    Node node = response.selectSingleNode("ns1:faultstring");
    if (node != null) {
      String exceptionText = node.getText();

      // Text accepted samples:
      // 'java.lang.Exception: Exception message'
      // 'java.lang.Exception'

      // Get the exception class and message if any
      int index = exceptionText.indexOf(":");
      String className;
      String message;
      // If there is no message, save the class only
      if (index == -1) {
        className = exceptionText;
        message = null;
      } else {
        // Else save both
        className = exceptionText.substring(0, index);
        message = exceptionText.substring(index + 2);
      }

      // Map the exception to a Openfire one, if possible
      if (exceptionMap.containsKey(className)) {
        className = exceptionMap.get(className);
      }

      // Tries to create an instance with the message
      Exception exception;
      try {
        Class exceptionClass = Class.forName(className);
        if (message == null) {
          exception = (Exception) exceptionClass.newInstance();
        } else {
          Constructor constructor = exceptionClass.getConstructor(String.class);
          exception = (Exception) constructor.newInstance(message);
        }
      } catch (Exception e) {
        // failed to create an specific exception, creating a standard one.
        exception = new Exception(exceptionText);
      }

      throw exception;
    }
  }
  // 获取一个网站上的链接,filter 用来过滤链接
  public static Set<String> extracLinks(String url, NodeFilter filter) {
    Set<String> links = new HashSet<String>();
    try {
      Parser parser = new Parser(url);
      parser.setEncoding("UTF-8");

      @SuppressWarnings("serial")
      NodeFilter frameFilter =
          new NodeFilter() {
            public boolean accept(Node node) {
              if (node.getText().startsWith("frame src=")) {
                return true;
              } else {
                return false;
              }
            }
          };

      OrFilter linkFilter = new OrFilter(new NodeClassFilter(LinkTag.class), frameFilter);

      NodeList list = parser.extractAllNodesThatMatch(linkFilter);

      System.out.println("length=" + list.size());

      for (int i = 0; i < list.size(); i++) {
        Node tag = list.elementAt(i);

        if (tag instanceof LinkTag) { // <a> 标签
          LinkTag link = (LinkTag) tag;
          String linkUrl = link.getLink(); // URL

          /*
           * if (filter.accept(linkUrl)) { links.add(linkUrl); }
           */

          System.out.println("linkUrl=" + linkUrl);

          if (filter.accept(tag)) {
            links.add(linkUrl);
          }
        } else { // <frame> 标签
          // 提取 frame 里 src 属性的链接,如 <frame src="test.html"/>
          String frame = tag.getText();
          int start = frame.indexOf("src=");
          frame = frame.substring(start);
          int end = frame.indexOf(" ");

          if (end == -1) {
            end = frame.indexOf(">");
          }

          String frameUrl = frame.substring(5, end - 1);
          // if (filter.accept(frameUrl)) {
          // links.add(frameUrl);
          // }

          System.out.println("frameUrl=" + frameUrl);

          if (filter.accept(tag)) {
            links.add(frameUrl);
          }
        }
      }

      /*
       * NodeFilter filter = new TagNameFilter("DIV"); NodeList nodes =
       * parser.extractAllNodesThatMatch(filter); if(nodes!=null) { for
       * (int i = 0; i < nodes.size(); i++) { Node textnode = (Node)
       * nodes.elementAt(i);
       * System.out.println("getText:"+textnode.getText());
       * System.out.println
       * ("================================================="); } }
       */
      /*
       * for(NodeIterator i = parser.elements (); i.hasMoreNodes(); ) {
       * Node node = i.nextNode();
       * System.out.println("getText:"+node.getText());
       * System.out.println("getPlainText:"+node.toPlainTextString());
       * System.out.println("toHtml:"+node.toHtml());
       * System.out.println("toHtml(true):"+node.toHtml(true));
       * System.out.println("toHtml(false):"+node.toHtml(false));
       * System.out.println("toString:"+node.toString());
       * System.out.println
       * ("================================================="); }
       */

      /*
       * TextExtractingVisitor visitor = new TextExtractingVisitor();
       * parser.visitAllNodesWith(visitor); String textInPage =
       * visitor.getExtractedText(); System.out.println(textInPage);
       */

    } catch (ParserException e) {
      e.printStackTrace();
    }
    return links;
  }
Exemple #8
0
 private static boolean handleURL(String address) {
   Main.status(String.format("Processing page \"%s\".", address));
   try {
     NodeList posts = getPosts(address);
     if (posts.toNodeArray().length == 0) {
       return false;
     }
     for (Node post_node : posts.toNodeArray()) {
       if (post_node instanceof TagNode) {
         TagNode post = (TagNode) post_node;
         Post new_post = new Post(Long.parseLong(post.getAttribute("id").substring(5)));
         if (!Main.post_post_hash.containsKey(new_post)) {
           NodeList photo_posts = getPhotoPosts(post.getChildren());
           NodeList remarks = getRemarks(photo_posts);
           for (Node node : remarks.toNodeArray()) {
             Matcher matcher = lores.matcher(node.getText());
             String media_url = "";
             if (matcher.find()) {
               media_url = matcher.group();
               media_url = media_url.substring(17, media_url.length() - 1);
             }
             String thumb =
                 media_url.replace(
                     media_url.substring(media_url.lastIndexOf("_"), media_url.lastIndexOf(".")),
                     "_75sq");
             URL thumb_url = new URL(thumb);
             new_post.pictures.add(new Picture(new URL(media_url), thumb_url));
           }
           NodeList photoset_posts = getPhotosetPosts(post.getChildren());
           NodeList iframes = getIFrames(photoset_posts);
           for (Node node : iframes.toNodeArray()) {
             if (node instanceof TagNode) {
               String iframe_url = ((TagNode) node).getAttribute("src");
               Parser parser2 = new Parser(iframe_url);
               NodeList a_list = parser2.extractAllNodesThatMatch(new TagNameFilter("a"));
               Node[] a_array = a_list.toNodeArray();
               Node[] img_array =
                   a_list.extractAllNodesThatMatch(new TagNameFilter("img"), true).toNodeArray();
               String media_url;
               for (int i = 0; i < a_array.length; i++) {
                 media_url = ((TagNode) img_array[i]).getAttribute("src");
                 String thumb =
                     media_url.replace(
                         media_url.substring(
                             media_url.lastIndexOf("_"), media_url.lastIndexOf(".")),
                         "_75sq");
                 URL thumb_url = new URL(thumb);
                 new_post.pictures.add(new Picture(new URL(media_url), thumb_url));
               }
             }
           }
           Main.handlePost(new_post);
         } else {
           new_post = post_post_hash.get(new_post);
           handleNonDownloadPost(new_post);
         }
       }
     }
   } catch (Exception ex) {
     ex.printStackTrace();
     Main.status("Error handling post.");
   }
   return true;
 }
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.getName().equals("getText")) {
      return node.getText();
    } else if (method.getName().equals("getTextRange")) {
      return new TextRange(node.getRange().getStart(), node.getRange().getEnd());
    } else if (method.getName().equals("getElementType")) {
      return node.getElementType();
    } else if (method.getName().equals("getPsi")) {
      return node.getPsi();
    } else if (method.getName().equals("getChildren")) {
      TokenSet types = (TokenSet) args[0];
      Node[] children = node.getChildren(types);
      ASTNode[] out = new ASTNode[children.length];
      for (int i = 0; i < children.length; i++) {
        out[i] = children[i].getASTNode();
      }

      return out;
    } else if (method.getName().equals("findChildByType")) {
      if (args[0] instanceof IElementType) {
        Node[] node2 = node.findChildrenByType((IElementType) args[0]);
        if (node2.length > 0) {
          return node2[0].getASTNode();
        } else {
          return null;
        }
      } else {
        // args[0] instanceof TokenSet
        Node[] node2 = node.findChildrenByTypes((TokenSet) args[0]);
        if (node2.length == 1) {
          return node2[0].getASTNode();
        } else {
          return null;
        }
      }
    } else if (method.getName().equals("getFirstChildNode")) {
      Node[] children = node.getChildren();
      if (children.length > 0) {
        return children[0].getASTNode();
      } else {
        return null; /// throw new IllegalAccessException();
      }
    } else if (method.getName().equals("getTreeNext")) {
      Node next = node.getTreeNext();
      if (next != null) {
        return next.getASTNode();
      }
      return null;
      /*
                  Node parent = node.getParent();
                  if (parent != null) {
                      int index = parent.indexOf(node);
                      Node next = parent.getChild(index + 1);
                      if (next != null) {
                          return next.getASTNode();
                      }
                  }
                  return null;
      */
    } else if (method.getName().equals("getTreeParent")) {
      Node parent = node.getParent();
      if (parent != null) {
        return parent.getASTNode();
      }
      return null;
    } else if (method.getName().equals("toString")) {
      return node.getElementType().toString();
    } else {
      System.out.println("Method not implemented: " + method.getName());
      throw new IllegalAccessException("Not supported: " + method.getName());
    }
  }