示例#1
0
  public static void removeEventinXml(String eventNameString) {
    SAXBuilder sxbuilder = new SAXBuilder();
    try {
      Document document = sxbuilder.build(new File(xmlDefaultPath));
      Element racine = document.getRootElement();

      //			List listEvents = racine.getChildren("evenement");
      //			Iterator i = listEvents.iterator();
      //			while(i.hasNext()){
      //				Element elementEvent = (Element)i.next();
      //				if(elementEvent.getAttribute("nomEvent").getValue().equalsIgnoreCase(eventNameString)){
      //					racine.removeChild("evenement");
      //				}
      //			}

      //
      //	if(racine.getChild("evenement").getAttribute("nomEvent").getValue().equalsIgnoreCase(eventNameString)){
      //
      //			}

      //			List<Element> children = racine.getChildren();
      //			for(Element child : children) {
      //
      //				if(child.getAttribute("nomEvent").getValue().equalsIgnoreCase(eventNameString)){
      //					System.out.println("poins");
      ////					child.getParentElement().removeChild("evenement");
      //					System.out.println(child.getAttributeValue("nomEvent"));
      //				}
      //			}

      //			enregistre(document, xmlDefaultPath);
    } catch (Exception e) {
      e.getMessage();
    }
  }
  public IXArchElement cloneElement(int depth) {
    synchronized (DOMUtils.getDOMLock(elt)) {
      Document doc = elt.getOwnerDocument();
      if (depth == 0) {
        Element cloneElt = (Element) elt.cloneNode(false);
        cloneElt = (Element) doc.importNode(cloneElt, true);
        AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt);
        cloneImpl.setXArch(getXArch());
        return cloneImpl;
      } else if (depth == 1) {
        Element cloneElt = (Element) elt.cloneNode(false);
        cloneElt = (Element) doc.importNode(cloneElt, true);
        AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt);
        cloneImpl.setXArch(getXArch());

        NodeList nl = elt.getChildNodes();
        int size = nl.getLength();
        for (int i = 0; i < size; i++) {
          Node n = nl.item(i);
          Node cloneNode = (Node) n.cloneNode(false);
          cloneNode = doc.importNode(cloneNode, true);
          cloneElt.appendChild(cloneNode);
        }
        return cloneImpl;
      } else /* depth = infinity */ {
        Element cloneElt = (Element) elt.cloneNode(true);
        cloneElt = (Element) doc.importNode(cloneElt, true);
        AbstractChangeSetImpl cloneImpl = new AbstractChangeSetImpl(cloneElt);
        cloneImpl.setXArch(getXArch());
        return cloneImpl;
      }
    }
  }
示例#3
0
    public void map(LongWritable key, Text value, Context context)
        throws IOException, InterruptedException {

      String strId = "";
      String strBody = "";

      // Parse the xml and read data (page id and article body)
      // Using XOM library
      Builder builder = new Builder();

      try {
        Document doc = builder.build(value.toString(), null);

        Nodes nodeId = doc.query("//eecs485_article_id");
        strId = nodeId.get(0).getChild(0).getValue();

        Nodes nodeBody = doc.query("//eecs485_article_body");
        strBody = nodeBody.get(0).getChild(0).getValue();
      } catch (ParsingException ex) {
        System.out.println("Not well-formed.");
        System.out.println(ex.getMessage());
      } catch (IOException ex) {
        System.out.println("io exception");
      }

      // Tokenize document body
      Pattern pattern = Pattern.compile("\\w+");
      Matcher matcher = pattern.matcher(strBody);

      while (matcher.find()) {
        // Write the parsed token
        // key = term, docid   value = 1
        context.write(new Text(matcher.group() + "," + strId), one);
      }
    }
示例#4
0
  /**
   * Pretty prints a node.
   *
   * @param doc The document the node comes from.
   * @param node The node that should be pretty printed.
   * @param prefix The prefix the node should get.
   */
  private static void prettyPrint(Document doc, Node node, String prefix) {
    String childPrefix = prefix + "  ";

    // Add the indenting to the children
    NodeList childList = node.getChildNodes();
    boolean hasChildren = false;
    for (int i = childList.getLength() - 1; i >= 0; i--) {
      Node child = childList.item(i);
      boolean isNormalNode = (!child.getNodeName().startsWith("#"));
      if (isNormalNode) {
        // Add the indenting to this node
        Node textNode = doc.createTextNode(childPrefix);
        node.insertBefore(textNode, child);

        // pretty print the child's children
        prettyPrint(doc, child, childPrefix);

        hasChildren = true;
      }
    }

    // Add the indenting to the end tag
    if (hasChildren) {
      Node textNode = doc.createTextNode(prefix);
      node.appendChild(textNode);
    }
  }
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  public void runTest() throws Throwable {
    Document doc;
    NodeList elementList;
    Node employeeNode;
    Node childNode;
    NodeList childNodes;
    int nodeType;
    String childName;
    java.util.List actual = new java.util.ArrayList();

    java.util.List expected = new java.util.ArrayList();
    expected.add("em");
    expected.add("strong");
    expected.add("code");
    expected.add("sup");
    expected.add("var");
    expected.add("acronym");

    doc = (Document) load("hc_staff", false);
    elementList = doc.getElementsByTagName("p");
    employeeNode = elementList.item(1);
    childNodes = employeeNode.getChildNodes();
    for (int indexN1006C = 0; indexN1006C < childNodes.getLength(); indexN1006C++) {
      childNode = (Node) childNodes.item(indexN1006C);
      nodeType = (int) childNode.getNodeType();
      childName = childNode.getNodeName();

      if (equals(1, nodeType)) {
        actual.add(childName);
      } else {
        assertEquals("textNodeType", 3, nodeType);
      }
    }
    assertEqualsAutoCase("element", "elementNames", expected, actual);
  }
  /**
   * Updates the AttributedCharacterIterator by invoking <code>formatToCharacterIterator</code> on
   * the <code>Format</code>. If this is successful, <code>updateMask(AttributedCharacterIterator)
   * </code> is then invoked to update the internal bitmask.
   */
  void updateMask() {
    if (getFormat() != null) {
      Document doc = getFormattedTextField().getDocument();

      validMask = false;
      if (doc != null) {
        try {
          string = doc.getText(0, doc.getLength());
        } catch (BadLocationException ble) {
          string = null;
        }
        if (string != null) {
          try {
            Object value = stringToValue(string);
            AttributedCharacterIterator iterator = getFormat().formatToCharacterIterator(value);

            updateMask(iterator);
          } catch (ParseException pe) {
          } catch (IllegalArgumentException iae) {
          } catch (NullPointerException npe) {
          }
        }
      }
    }
  }
  /**
   * Perform the action of the plugin.
   *
   * @param document the current document.
   */
  public boolean perform(Document document) throws IOException {
    // Interact with the user to get the layer tag/

    Tag layerTag = getLayerTagFromUser(document);
    if (layerTag == null) return false; // User cancled.
    Tag endTag = new Tag(layerTag.getName(), false);
    // Get the output stream to hold the new document text.
    PrintWriter out = new PrintWriter(document.getOutput());
    // Create a lexical stream to tokenize the old document text.
    LexicalStream in = new LexicalStream(new SelectedHTMLReader(document.getInput(), out));
    for (; ; ) {
      // Get the next token of the document.
      Token token = in.next();
      if (token == null) break; //  Null means we've finished the document.
      else if (token instanceof Comment) {
        Comment comment = (Comment) token;
        if (comment.isSelectionStart()) {
          out.print(layerTag);
        } else if (comment.isSelectionEnd()) {
          out.print(comment);
          out.print(endTag);
          continue; // So comment isn't printed twice.
        }
      }
      out.print(token);
    }
    out.close();
    return true;
  }
示例#8
0
  public void testRemoveHugeLogicalLineThatLaysBeforeSoftWrappedLines() throws IOException {
    String text =
        "short line\n"
            + "this is a long line that is expected to be soft wrapped into more than one or even two visual lines\n"
            + "1. just a line that is long enough to be soft wrapped\n"
            + "2. just a line that is long enough to be soft wrapped\n"
            + "3. just a line that is long enough to be soft wrapped\n"
            + "4. just a line that is long enough to be soft wrapped";

    init(15, text);
    Document document = myEditor.getDocument();
    int start = document.getLineStartOffset(1);
    int end = document.getLineEndOffset(1) + 1;
    int visualLinesToRemove = getSoftWrapModel().getSoftWrapsForLine(1).size() + 1;

    List<VisualPosition> positionsBefore = new ArrayList<VisualPosition>();
    for (int i = end; i < text.length(); i++) {
      positionsBefore.add(myEditor.offsetToVisualPosition(i));
    }
    Collections.reverse(positionsBefore);

    myEditor.getSelectionModel().setSelection(start, end);
    delete();

    // Check that all remembered positions are just shifted to expected number of visual lines.
    for (int i = start; i < document.getTextLength(); i++) {
      VisualPosition position = positionsBefore.remove(positionsBefore.size() - 1);
      assertEquals(
          new VisualPosition(position.line - visualLinesToRemove, position.column),
          myEditor.offsetToVisualPosition(i));
    }
  }
 /**
  * Given a DICOM object encoded as a list of attributes, get an XML document as a DOM tree.
  *
  * @param list the list of DICOM attributes
  */
 public Document getDocument(AttributeList list) {
   Document document = db.newDocument();
   org.w3c.dom.Node element = document.createElement("DicomObject");
   document.appendChild(element);
   addAttributesFromListToNode(list, document, element);
   return document;
 }
示例#10
0
 /* PRIVATE METHODS */
 private DOMDocument createDomDocument(String rootName) {
   DOMDocument domDocument = new DOMDocument(nsURI, rootName, null);
   Document document = domDocument.getDocument();
   Element root = document.getDocumentElement();
   if (includeTypeInfo) {
     root.setAttributeNS(
         XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
         XMLConstants.XMLNS_ATTRIBUTE + ":" + nsPrefix,
         nsURI);
     root.setAttributeNS(
         XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
         XMLConstants.XMLNS_ATTRIBUTE + ":" + NamespaceConstants.NSPREFIX_SCHEMA_XSD,
         NamespaceConstants.NSURI_SCHEMA_XSD);
     root.setAttributeNS(
         XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
         XMLConstants.XMLNS_ATTRIBUTE + ":" + NamespaceConstants.NSPREFIX_SCHEMA_XSI,
         NamespaceConstants.NSURI_SCHEMA_XSI);
     root.setAttributeNS(
         XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
         XMLConstants.XMLNS_ATTRIBUTE + ":" + NamespaceConstants.NSPREFIX_SOAP_ENCODING,
         NamespaceConstants.NSURI_SOAP_ENCODING);
     root.setAttributeNS(
         XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
         XMLConstants.XMLNS_ATTRIBUTE + ":" + Constants.NS_PREFIX_XMLSOAP,
         Constants.NS_URI_XMLSOAP);
   }
   return domDocument;
 }
示例#11
0
  private void countOccurrences() {
    LOG.info("counting occurrences");

    occurrenceCounts = new int[uniqueTermCount];
    cooccurrenceCounts = new int[uniqueTermCount][uniqueTermCount];

    int documentsCounted = 0;
    for (Document doc : corpus) {
      Set<Integer> docTerms = doc.uniqueTermIds();
      for (int i = 0; i < uniqueTermCount; i++) {

        if (docTerms.contains(id2term[i])) {
          occurrenceCounts[i]++;

          for (int j = 0; j < uniqueTermCount; j++) {
            if (docTerms.contains(id2term[j])) {
              cooccurrenceCounts[i][j]++;
            }
          }
        }
      }

      documentsCounted++;
      if (documentsCounted % 1000 == 0) {
        LOG.info(String.format("counted %d documents", documentsCounted));
      }

      if (documentLimit > 0 && documentLimit == documentsCounted) break;
    }
  }
  public static void main(String[] args) throws Exception {

    // final Logger log = Logger.getLogger(sample.class.getCanonicalName());
    JobData jd = new JobData();

    Scanner input = new Scanner(System.in);
    try {
      System.out.print("What is your user name? ");
      jd.setUsername(input.next());
      System.out.print("What is your password? ");
      jd.setPassword(input.next());
    } catch (Exception e) {
      // log.log(Level. SEVERE, "The system encountered an exception while attempting to login");
    } finally {
      input.close();
    }

    jd.setJob("TestREST");
    jd.setServer("http://10.94.0.137");
    jd.setPort("8006");

    URL url = new URL("http://10.94.0.137:8006/api/xml");
    Document dom = new SAXReader().read(url);

    for (Element job : (List<Element>) dom.getRootElement().elements("job")) {
      System.out.println(
          String.format(
              "Job %s with URL %s has status %s",
              job.elementText("name"), job.elementText("url"), job.elementText("color")));
    }
  }
示例#13
0
 private void analyseDocument(Document document, int lineNum, PythonIndentation indentationLogic)
     throws BadLocationException {
   Element map = document.getDefaultRootElement();
   int endPos = map.getElement(lineNum).getEndOffset();
   indentationLogic.reset();
   indentationLogic.addText(document.getText(0, endPos));
 }
示例#14
0
  public static List<String> getEventsNameByXml() {
    SAXBuilder sxb = new SAXBuilder();
    Document document;
    List<String> listEvenementsString = null;
    //		Object obj=null;
    try {
      document = sxb.build(new File(xmlDefaultPath));

      //			listevents=getEventsNameByDoc(document);

      Element racine = document.getRootElement();

      //			System.out.println("racine="+racine.getText()+"finracine");
      List<Element> listEvenementsElement = racine.getChildren("evenement");
      listEvenementsString = new ArrayList<String>();

      for (Element evenementElement : listEvenementsElement) {
        listEvenementsString.add(evenementElement.getAttributeValue("nomEvent"));
      }

      //			System.out.println("listofEventsJdomtaille ="+listEvenementsString.size());

      // il faut valider le fichier xml avec la dtd
      //			JDomOperations.validateJDOM(document);
      //			afficheXml(document);
    } catch (Exception e) {
      // afficher un popup qui dit que le format du fichier xml entré n'est pas valide
      System.out.println("format xml non respecté");
      System.out.println(e.getMessage());
    }
    return listEvenementsString;
  }
示例#15
0
文件: Worker.java 项目: m1/Parker
  public Worker(String url, boolean verbose) throws Exception {
    Document doc;
    doc = Jsoup.connect(url).get();
    // select anchors with href only
    Elements links = doc.select("a[href]");
    String l_Href;
    String host;
    int linksNum;
    Parser parser;
    for (Element link : links) {
      // absolute = http:// added
      l_Href = link.attr("abs:href");
      if (!l_Href.isEmpty()) {
        parser = new Parser(l_Href);
        host = parser.getHost();
        // if tempStats contains the url, add one to the value
        if (tempStats.containsKey(host)) {
          linksNum = tempStats.get(host);
          tempStats.put(host, linksNum += 1);
        }
        // if it doesn't, add it

        else {
          tempStats.put(host, 1);
        }
        // parse the url
        tempQueue.add(parser.getURL());
      }
    }
    if (verbose) {
      System.out.println(
          Thread.currentThread().getName() + " : " + tempQueue.size() + " links from " + url);
    }
  }
示例#16
0
 /**
  * 得到反馈信息列表
  *
  * @param xml
  * @return
  * @throws DocumentException
  */
 public static List<TradingFeedBackDetail> getFeedBackListElement(String xml) throws Exception {
   List<TradingFeedBackDetail> lifb = new ArrayList();
   Document document = formatStr2Doc(xml);
   Element rootElt = document.getRootElement();
   Element recommend = rootElt.element("FeedbackDetailArray");
   Iterator<Element> iter = recommend.elementIterator("FeedbackDetail");
   while (iter.hasNext()) {
     Element element = iter.next();
     TradingFeedBackDetail tfbd = new TradingFeedBackDetail();
     tfbd.setCommentinguser(element.elementText("CommentingUser"));
     tfbd.setCommentinguserscore(Long.parseLong(element.elementText("CommentingUserScore")));
     tfbd.setCommenttext(
         StringEscapeUtils.escapeXml(element.element("CommentText").getStringValue()));
     tfbd.setCommenttime(DateUtils.returnDate(element.elementText("CommentTime")));
     tfbd.setCommenttype(element.elementText("CommentType"));
     tfbd.setItemid(element.elementText("ItemID"));
     tfbd.setRole(element.elementText("Role"));
     tfbd.setFeedbackid(element.elementText("FeedbackID"));
     tfbd.setTransactionid(element.elementText("TransactionID"));
     tfbd.setOrderlineitemid(element.elementText("OrderLineItemID"));
     tfbd.setItemtitle(element.elementText("ItemTitle"));
     tfbd.setCreateTime(new Date());
     if (element.elementText("ItemPrice") != null) {
       tfbd.setItemprice(Double.parseDouble(element.elementText("ItemPrice")));
     }
     lifb.add(tfbd);
   }
   return lifb;
 }
示例#17
0
  public String SqlExcute(String xmlStr) {
    String outstr = "false";
    Document doc;
    Element rootNode;
    String intStr = Basic.decode(xmlStr);

    try {
      Reader reader = new StringReader(intStr);
      SAXBuilder ss = new SAXBuilder();
      doc = ss.build(reader);

      rootNode = doc.getRootElement();

      List list = rootNode.getChildren();

      DBTable datatable = new DBTable();

      for (int i = 0; i < list.size(); i++) {
        Element childRoot = (Element) list.get(i);
        // System.out.print(childRoot.getText());
        outstr = String.valueOf(datatable.SaveDateStr(childRoot.getText()));
      }

    } catch (JDOMException ex) {
      System.out.print(ex.getMessage());
    }
    return outstr;
  }
示例#18
0
 /**
  * 通过Title 查询是相似分类信息
  *
  * @param xml
  * @return
  * @throws DocumentException
  */
 public static List<TradingReseCategory> selectCategoryByKey(String xml) throws Exception {
   List<TradingReseCategory> litrc = new ArrayList();
   // 商品分类目录查询
   Document document = formatStr2Doc(xml);
   Element rootElt = document.getRootElement();
   if (rootElt == null) {
     return litrc;
   }
   Element recommend = rootElt.element("SuggestedCategoryArray");
   if (recommend == null) {
     return litrc;
   }
   Iterator<Element> ite = recommend.elementIterator("SuggestedCategory");
   while (ite.hasNext()) {
     Element ele = ite.next();
     Element cate = ele.element("Category");
     Element PercentItemFound = ele.element("PercentItemFound");
     TradingReseCategory trc = new TradingReseCategory();
     trc.setId(Long.parseLong(cate.elementText("CategoryID")));
     trc.setCategoryId(cate.elementText("CategoryID"));
     Iterator<Element> ites = cate.elementIterator("CategoryParentName");
     String cateName = "";
     while (ites.hasNext()) {
       Element ent = ites.next();
       cateName = cateName + ent.getText() + ":";
     }
     trc.setCategoryKey(PercentItemFound.getText() + "%");
     trc.setCategoryName(cateName + cate.elementText("CategoryName"));
     litrc.add(trc);
   }
   return litrc;
 }
示例#19
0
  private void addProductDetails(Document document) throws BadElementException, DocumentException {
    Paragraph preface = new Paragraph();
    addEmptyLine(preface, 5);
    document.add(preface);

    PdfPTable table = new PdfPTable(3);

    table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
    PdfPCell c1 = new PdfPCell(new Phrase("Product ID"));
    c1.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c1);

    PdfPCell c2 = new PdfPCell(new Phrase("Current Stock"));
    c2.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c2);

    PdfPCell c3 = new PdfPCell(new Phrase("Minimum Stock"));
    c3.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(c3);

    table.setHeaderRows(1);

    ArrayList<ArrayList<String>> products = rprtDBAccess.getLowStockedProducts();

    for (int i = 0; i < products.size(); i++) {
      ArrayList<String> product = products.get(i);
      table.addCell(product.get(0)); // product id
      table.addCell(product.get(1)); // currentstock
      table.addCell(product.get(2)); // minimumstock

      table.completeRow();
    }
    document.add(table);
  }
示例#20
0
 // 解析价格跟踪
 public static List<TradingPriceTracking> getPriceTrackingItemByItemId(String res)
     throws Exception {
   List<TradingPriceTracking> priceTrackings = new ArrayList<TradingPriceTracking>();
   Document document = formatStr2Doc(res);
   Element rootElt = document.getRootElement();
   Iterator items = rootElt.elementIterator("Item");
   while (items.hasNext()) {
     TradingPriceTracking priceTracking = new TradingPriceTracking();
     Element item = (Element) items.next();
     priceTracking.setItemid(SamplePaseXml.getSpecifyElementText(item, "ItemID"));
     priceTracking.setTitle(SamplePaseXml.getSpecifyElementText(item, "Title"));
     priceTracking.setCurrentprice(
         SamplePaseXml.getSpecifyElementText(item, "ConvertedCurrentPrice"));
     priceTracking.setBidcount(SamplePaseXml.getSpecifyElementText(item, "BidCount"));
     Element ConvertedCurrentPrice = item.element("ConvertedCurrentPrice");
     String endtime = SamplePaseXml.getSpecifyElementText(item, "EndTime");
     if (StringUtils.isNotBlank(endtime)) {
       priceTracking.setEndtime(DateUtils.returnDate(endtime));
     }
     String currencyId1 = "";
     if (ConvertedCurrentPrice != null) {
       Attribute currencyId = ConvertedCurrentPrice.attribute("currencyId");
       if (currencyId != null) {
         currencyId1 = currencyId.getValue();
       }
     }
     priceTracking.setCurrencyid(currencyId1);
     priceTrackings.add(priceTracking);
   }
   return priceTrackings;
 }
  /** setAttribute, getAttribute, hasAttributes, hasAttribute. */
  public void testAttributes() {
    Document doc = Document.get();
    DivElement div = doc.createDivElement();

    div.setAttribute("id", "myId");
    assertEquals("myId", div.getAttribute("id"));
  }
示例#22
0
  /**
   * Returns the result of an XSL Transformation as a JDOM document.
   *
   * <p>If the result of the transformation is a list of nodes, this method attempts to convert it
   * into a JDOM document. If successful, any subsequent call to {@link #getResult} will return an
   * empty list.
   *
   * <p><strong>Warning</strong>: The XSLT 1.0 specification states that the output of an XSL
   * transformation is not a well-formed XML document but a list of nodes. Applications should thus
   * use {@link #getResult} instead of this method or at least expect <code>null</code> documents to
   * be returned.
   *
   * @return the transformation result as a JDOM document or <code>null</code> if the result of the
   *     transformation can not be converted into a well-formed document.
   * @see #getResult
   */
  public Document getDocument() {
    Document doc = null;

    // Retrieve result from the document builder if not set.
    this.retrieveResult();

    if (result instanceof Document) {
      doc = (Document) result;
    } else {
      if ((result instanceof List) && (queried == false)) {
        // Try to create a document from the result nodes
        try {
          JDOMFactory f = this.getFactory();
          if (f == null) {
            f = new DefaultJDOMFactory();
          }

          doc = f.document(null);
          doc.setContent((List) result);

          result = doc;
        } catch (RuntimeException ex1) {
          // Some of the result nodes are not valid children of a
          // Document node. => return null.
        }
      }
    }
    queried = true;

    return (doc);
  }
示例#23
0
 /**
  * Determines the preferred span for this view along an axis.
  *
  * @param axis may be either View.X_AXIS or View.Y_AXIS
  * @return the span the view would like to be rendered into &gt;= 0. Typically the view is told to
  *     render into the span that is returned, although there is no guarantee. The parent may
  *     choose to resize or break the view.
  */
 public float getPreferredSpan(int axis) {
   switch (axis) {
     case View.X_AXIS:
       Segment buff = SegmentCache.getSharedSegment();
       Document doc = getDocument();
       int width;
       try {
         FontMetrics fm = getFontMetrics();
         doc.getText(0, doc.getLength(), buff);
         width = Utilities.getTabbedTextWidth(buff, fm, 0, this, 0);
         if (buff.count > 0) {
           Component c = getContainer();
           firstLineOffset =
               j86.sun.swing.SwingUtilities2.getLeftSideBearing(
                   (c instanceof JComponent) ? (JComponent) c : null, fm, buff.array[buff.offset]);
           firstLineOffset = Math.max(0, -firstLineOffset);
         } else {
           firstLineOffset = 0;
         }
       } catch (BadLocationException bl) {
         width = 0;
       }
       SegmentCache.releaseSharedSegment(buff);
       return width + firstLineOffset;
     default:
       return super.getPreferredSpan(axis);
   }
 }
示例#24
0
 /**
  * Creates a DOM representation of the object. Result is appended to the Node <code>parent</code>.
  *
  * @param parent
  */
 public void makeElement(Node parent) {
   Document doc;
   if (parent instanceof Document) {
     doc = (Document) parent;
   } else {
     doc = parent.getOwnerDocument();
   }
   Element element = doc.createElement("rem");
   int size;
   if (definitionURL != null) {
     URelaxer2.setAttributePropertyByString(
         element, "http://www.w3.org/1998/Math/MathML", "definitionURL", definitionURL);
   }
   if (classValue != null) {
     URelaxer2.setAttributePropertyByString(
         element, "http://www.w3.org/1998/Math/MathML", "class", classValue);
   }
   if (style != null) {
     URelaxer2.setAttributePropertyByString(
         element, "http://www.w3.org/1998/Math/MathML", "style", style);
   }
   if (id != null) {
     URelaxer2.setAttributePropertyByString(
         element, "http://www.w3.org/1998/Math/MathML", "id", id);
   }
   if (other != null) {
     URelaxer2.setAttributePropertyByString(
         element, "http://www.w3.org/1998/Math/MathML", "other", other);
   }
   parent.appendChild(element);
 }
  public ArrayList<String> parseXML() throws Exception {
    ArrayList<String> ret = new ArrayList<String>();

    handshake();

    URL url =
        new URL(
            "http://mangaonweb.com/page.do?cdn="
                + cdn
                + "&cpn=book.xml&crcod="
                + crcod
                + "&rid="
                + (int) (Math.random() * 10000));
    String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(page));
    Document d = builder.parse(is);
    Element doc = d.getDocumentElement();

    NodeList pages = doc.getElementsByTagName("page");
    total = pages.getLength();
    for (int i = 0; i < pages.getLength(); i++) {
      Element e = (Element) pages.item(i);
      ret.add(e.getAttribute("path"));
    }

    return (ret);
  }
示例#26
0
  /**
   * Attempts to find the next subsequence of the input sequence that matches the pattern.
   *
   * <p>This method starts at the beginning of the input sequence or, if a previous invocation of
   * the method was successful and the matcher has not since been reset, at the first character not
   * matched by the previous match.
   *
   * @return the index of the first occurrence of the search string, starting at the specified
   *     offset, or -1 if no occurrence was found.
   */
  public int findNext() {
    // Don't match empty strings and don't match if we are at the end of the document.
    if (findString.length() == 0 || document.getLength() - findString.length() < startIndex) {
      return -1;
    }

    try {
      int nextMatch = 0; // index of next matching character

      // Iterate through all segments of the document starting from offset
      Segment text = new Segment();
      text.setPartialReturn(true);
      int offset = startIndex;
      int nleft = document.getLength() - startIndex;
      while (nleft > 0) {
        document.getText(offset, nleft, text);

        // Iterate through the characters in the current segment
        char next = text.first();
        for (text.first(); next != Segment.DONE; next = text.next()) {

          // Check if the current character matches with the next
          // search character.
          char current = text.current();
          if (current == matchUpperCase[nextMatch] || current == matchLowerCase[nextMatch]) {
            nextMatch++;

            // Did we match all search characters?
            if (nextMatch == matchLowerCase.length) {
              int foundIndex =
                  text.getIndex() - text.getBeginIndex() + offset - matchLowerCase.length + 1;
              if (matchType == MatchType.CONTAINS) {
                return foundIndex;
                // break; <- never reached
              } else if (matchType == MatchType.STARTS_WITH) {
                if (!isWordChar(foundIndex - 1)) {
                  return foundIndex;
                }
              } else if (matchType == MatchType.FULL_WORD) {
                if (!isWordChar(foundIndex - 1)
                    && !isWordChar(foundIndex + matchLowerCase.length)) {
                  return foundIndex;
                }
              }
              nextMatch = 0;
            }
          } else {
            nextMatch = 0;
          }
        }

        // Move forward to the next segment
        nleft -= text.count;
        offset += text.count;
      }
      return -1;
    } catch (BadLocationException e) {
      throw new IndexOutOfBoundsException();
    }
  }
示例#27
0
  public Element getFileRoot(String filename) {

    // find file & load file
    Element root = null;

    boolean verify = false;

    try {
      SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", verify);

      builder.setFeature("http://apache.org/xml/features/xinclude", true);
      builder.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false);
      builder.setFeature("http://apache.org/xml/features/allow-java-encodings", true);
      builder.setFeature("http://apache.org/xml/features/validation/schema", verify);
      builder.setFeature("http://apache.org/xml/features/validation/schema-full-checking", verify);
      builder.setFeature("http://xml.org/sax/features/namespaces", true);

      Document doc =
          builder.build(new BufferedInputStream(new FileInputStream(new File(filename))));
      root = doc.getRootElement();
    } catch (Exception e) {
      System.out.println("While reading file: " + e);
    }
    return root;
  }
示例#28
0
 private void readDatatypeArray(int type, Document document, String key) {
   ValueList tempList = valueList.getNextList();
   if (tempList == null) {
     document.put(key, null);
     return;
   }
   int len = tempList.length();
   Object[] array = null;
   if (type == ElementType.TYPE_STRING_ARRAY) {
     array = new String[len];
     for (int i = 0; i < len; i++) {
       array[i] = tempList.getNextString();
     }
   } else if (type == ElementType.TYPE_INTEGER_ARRAY) {
     array = new Integer[len];
     for (int i = 0; i < len; i++) {
       array[i] = tempList.getNextInt();
     }
   } else if (type == ElementType.TYPE_LONG_ARRAY) {
     array = new Long[len];
     for (int i = 0; i < len; i++) {
       array[i] = tempList.getNextLong();
     }
   } else if (type == ElementType.TYPE_DOUBLE_ARRAY) {
     array = new Double[len];
     for (int i = 0; i < len; i++) {
       array[i] = tempList.getNextDouble();
     }
   }
   document.put(key, array);
 }
示例#29
0
  /**
   * Parses a given .svg for nodes
   *
   * @return <b>bothNodeLists</b> an Array with two NodeLists
   */
  public static NodeList[] parseSVG(Date date) {

    /* As it has to return two things, it can not return them
     * directly but has to encapsulate it in another object.
     */
    NodeList[] bothNodeLists = new NodeList[2];
    ;
    try {

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

      String SVGFileName = "./draw_map_svg.svg";
      File svgMap = new File(SVGFileName);

      System.out.println("Parsing the svg"); // Status message #1 Parsing
      System.out.println("This should not longer than 30 seconds"); // Status message #2 Parsing

      Document doc = docBuilder.parse(SVGFileName);

      // "text" is the actual planet/warplanet
      NodeList listOfPlanetsAsXMLNode = doc.getElementsByTagName("text");

      // "line" is the line drawn by a warplanet. Used for calculation of warplanet coordinates.
      NodeList listOfLinesAsXMLNode = doc.getElementsByTagName("line");
      bothNodeLists[0] = listOfPlanetsAsXMLNode;
      bothNodeLists[1] = listOfLinesAsXMLNode;

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

      // Build the fileName the .svg should be renamed to, using the dateStringBuilder
      String newSVGFileName = MapTool.dateStringBuilder(MapTool.getKosmorDate(date), date);
      newSVGFileName = newSVGFileName.concat(" - Map - kosmor.com - .svg");

      // Making sure the directory does exist, if not, it is created
      File svgdir = new File("svg");
      if (!svgdir.exists() || !svgdir.isDirectory()) {
        svgdir.mkdir();
      }

      svgMap.renameTo(new File(svgdir + "\\" + newSVGFileName));

      System.out.println("Done parsing"); // Status message #3 Parsing

    } catch (SAXParseException err) {
      System.out.println(
          "** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
      System.out.println(" " + err.getMessage());

    } catch (SAXException e) {
      Exception x = e.getException();
      ((x == null) ? e : x).printStackTrace();

    } catch (Throwable t) {
      t.printStackTrace();
    }

    return bothNodeLists;
  }
  // 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;
  }