예제 #1
1
 @Override
 public HSDeck getDeckDetail(final HSDeck hsDeck, final float n) {
   try {
     final Document value = Jsoup.connect(HPDeckSource.BASE_URL + hsDeck.getUrl()).get();
     final Elements select = value.select("section.class-listing table.listing td.col-name");
     final HashMap<String, String> classHsItemMap = new HashMap<String, String>();
     final ArrayList<String> list = new ArrayList<String>();
     for (int i = 0; i < select.size(); ++i) {
       final String text = select.get(i).select("a").get(0).text();
       classHsItemMap.put(
           text, select.get(i).text().trim().substring(select.get(i).text().trim().length() - 1));
       list.add(text);
     }
     hsDeck.setClassHsItemMap(classHsItemMap);
     hsDeck.setClassHsItemList(DataBaseManager.getInstance().getAllCardsByNames(list));
     final Elements select2 = value.select("section.neutral-listing table.listing td.col-name");
     final HashMap<String, String> neutralHsItemMap = new HashMap<String, String>();
     final ArrayList<String> list2 = new ArrayList<String>();
     for (int j = 0; j < select2.size(); ++j) {
       final String text2 = select2.get(j).select("a").get(0).text();
       neutralHsItemMap.put(
           text2,
           select2.get(j).text().trim().substring(select2.get(j).text().trim().length() - 1));
       list2.add(text2);
     }
     hsDeck.setNeutralHsItemMap(neutralHsItemMap);
     hsDeck.setNeutralHsItemList(DataBaseManager.getInstance().getAllCardsByNames(list2));
     hsDeck.setDescription(
         HtmlHelper.parseDescription(value.select("div.deck-description").html(), n, false));
     return hsDeck;
   } catch (IOException ex) {
     ex.printStackTrace();
     return hsDeck;
   }
 }
  private ProperTextRange offsetToYPosition(int start, int end) {
    if (myEditorScrollbarTop == -1 || myEditorTargetHeight == -1) {
      recalcEditorDimensions();
    }
    Document document = myEditor.getDocument();
    int startLineNumber = offsetToLine(start, document);
    int startY;
    int lineCount;
    if (myEditorSourceHeight < myEditorTargetHeight) {
      lineCount = 0;
      startY = myEditorScrollbarTop + startLineNumber * myEditor.getLineHeight();
    } else {
      lineCount = myEditorSourceHeight / myEditor.getLineHeight();
      startY =
          myEditorScrollbarTop + (int) ((float) startLineNumber / lineCount * myEditorTargetHeight);
    }

    int endY;
    if (document.getLineNumber(start) == document.getLineNumber(end)) {
      endY = startY; // both offsets are on the same line, no need to recalc Y position
    } else {
      int endLineNumber = offsetToLine(end, document);
      if (myEditorSourceHeight < myEditorTargetHeight) {
        endY = myEditorScrollbarTop + endLineNumber * myEditor.getLineHeight();
      } else {
        endY =
            myEditorScrollbarTop + (int) ((float) endLineNumber / lineCount * myEditorTargetHeight);
      }
      if (endY < startY) endY = startY;
    }
    return new ProperTextRange(startY, endY);
  }
  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);
  }
예제 #4
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);
  }
예제 #5
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;
 }
예제 #6
0
  /**
   * This method exports the single pattern decision instance to the XML. It MUST be called by an
   * XML exporter, as this will not have a complete header.
   *
   * @param ratDoc The ratDoc generated by the XML exporter
   * @return the SAX representation of the object.
   */
  public Element toXML(Document ratDoc) {
    Element decisionE;
    RationaleDB db = RationaleDB.getHandle();

    // Now, add pattern to doc
    String entryID = db.getRef(this);
    if (entryID == null) {
      entryID = db.addPatternDecisionRef(this);
    }

    decisionE = ratDoc.createElement("DR:patternDecision");
    decisionE.setAttribute("rid", entryID);
    decisionE.setAttribute("name", name);
    decisionE.setAttribute("type", type.toString());
    decisionE.setAttribute("phase", devPhase.toString());
    decisionE.setAttribute("status", status.toString());
    // decisionE.setAttribute("artifact", artifact);

    Element descE = ratDoc.createElement("description");
    Text descText = ratDoc.createTextNode(description);
    descE.appendChild(descText);
    decisionE.appendChild(descE);

    // Add child pattern references...
    Iterator<Pattern> cpi = candidatePatterns.iterator();
    while (cpi.hasNext()) {
      Pattern cur = cpi.next();
      Element curE = ratDoc.createElement("refChildPattern");
      Text curText = ratDoc.createTextNode("p" + new Integer(cur.getID()).toString());
      curE.appendChild(curText);
      decisionE.appendChild(curE);
    }

    return decisionE;
  }
예제 #7
0
    @Override
    public void actionPerformed(ActionEvent e) {
      Frame frame = getFrame();
      JFileChooser chooser = new JFileChooser();
      int ret = chooser.showOpenDialog(frame);

      if (ret != JFileChooser.APPROVE_OPTION) {
        return;
      }

      File f = chooser.getSelectedFile();
      if (f.isFile() && f.canRead()) {
        Document oldDoc = getEditor().getDocument();
        if (oldDoc != null) {
          oldDoc.removeUndoableEditListener(undoHandler);
        }
        if (elementTreePanel != null) {
          elementTreePanel.setEditor(null);
        }
        getEditor().setDocument(new PlainDocument());
        frame.setTitle(f.getName());
        Thread loader = new FileLoader(f, editor.getDocument());
        loader.start();
      } else {
        JOptionPane.showMessageDialog(
            getFrame(),
            "Could not open file: " + f,
            "Error opening file",
            JOptionPane.ERROR_MESSAGE);
      }
    }
 private void addMetaData(Document document) {
   document.addTitle("My first PDF");
   document.addSubject("Using iText");
   document.addKeywords("Java, PDF, iText");
   document.addAuthor("Lars Vogel");
   document.addCreator("Lars Vogel");
 }
예제 #9
0
      public void onDocument(Document document, String xpath) throws XmlParserException {
        if (xpath.equals(XPATH_IPEAK)) {
          Node node = document.getFirstChild();

          // check whether we're getting the correct ipeak
          Node typeattribute = node.getAttributes().getNamedItem(PeakMLWriter.TYPE);
          if (typeattribute == null)
            throw new XmlParserException("Failed to locate the type attribute.");
          if (!typeattribute.getNodeValue().equals(PeakMLWriter.TYPE_BACKGROUNDION))
            throw new XmlParserException(
                "IPeak ("
                    + typeattribute.getNodeValue()
                    + ") is not of type: '"
                    + PeakMLWriter.TYPE_BACKGROUNDION
                    + "'");

          // parse this node as a mass chromatogram
          BackgroundIon<? extends Peak> backgroundion = parseBackgroundIon(node);
          if (backgroundion != null) peaks.add(backgroundion);

          //
          if (_listener != null && result.header != null && result.header.getNrPeaks() != 0)
            _listener.update((100. * index++) / result.header.getNrPeaks());
        } else if (xpath.equals(XPATH_HEADER)) {
          result.header = parseHeader(document.getFirstChild());
        }
      }
  public void summaryAction(HttpServletRequest req, HttpServletResponse res) {
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<String, Object>();
    DocumentManager docMan = new DocumentManager();

    try {

      if (req.getParameter("documentId") != null) {
        // Get the document ID
        int docId = Integer.parseInt(req.getParameter("documentId"));
        // Get the document using document id
        Document document = docMan.get(docId);
        // Set title to name of the document
        viewData.put("title", document.getDocumentName());
        // Create List of access records
        List<AccessRecord> accessRecords = new LinkedList<AccessRecord>();
        // Add access records for document to the list
        accessRecords = docMan.getAccessRecords(docId);

        viewData.put("accessRecords", accessRecords);
      } else {
        // Go back to thread page.
      }

    } catch (Exception e) {
      Logger.getLogger("").log(Level.SEVERE, "An error occurred when getting profile user", e);
    }

    view(req, res, "/views/group/Document.jsp", viewData);
  }
예제 #11
0
  private static UpgradeStringResult transformXml(
      String xml, String newFormatVersion, UpgradeOp... ops) {
    try {

      DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder;
      builder = builderFactory.newDocumentBuilder();
      Document document = builder.parse(new InputSource(new StringReader(xml)));

      // Check that this is a NodeBox document and set the new formatVersion.
      Element root = document.getDocumentElement();
      checkArgument(root.getTagName().equals("ndbx"), "This is not a valid NodeBox document.");
      root.setAttribute("formatVersion", newFormatVersion);

      // Loop through all upgrade operations.
      ArrayList<String> warnings = new ArrayList<String>();
      for (UpgradeOp op : ops) {
        op.start(root);
        transformXmlRecursive(document.getDocumentElement(), op);
        op.end(root);
        warnings.addAll(op.getWarnings());
      }

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(document);
      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);
      transformer.transform(source, result);
      return new UpgradeStringResult(sw.toString(), warnings);
    } catch (Exception e) {
      throw new RuntimeException("Error while upgrading to " + newFormatVersion + ".", e);
    }
  }
예제 #12
0
  @Audit
  @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
  @Override
  public void reportSpammersContent(User spammer, User reporter, String comment) {
    if (log.isInfoEnabled()) {
      log.info(
          "Reporting SPAM Abuse on all content of of this spammer: "
              + spammer.getUsername()
              + ". Reporter is: "
              + reporter.getUsername());
    }

    final Date reportDate = new Date();

    Iterable<Document> docs = documentManager.getUserDocuments(spammer, documentStates);
    for (Document document : docs) {
      if (log.isTraceEnabled()) {
        log.trace("Report spam of document: " + document.getDocumentID());
      }
      reportSpam(document, reporter, comment, reportDate);
    }

    Iterable<ForumMessage> messages = forumManager.getUserMessages(spammer);
    for (ForumMessage message : messages) {
      if (log.isTraceEnabled()) {
        log.trace(
            "Report spam of message: "
                + message.getID()
                + ", threadId: "
                + message.getForumThreadID());
      }
      // TODO: Check how works root messages (threads)
      reportSpam(message, reporter, comment, reportDate);
    }

    List<Blog> blogs = blogManager.getExplicitlyEntitledBlogs(spammer);
    for (Blog blog : blogs) {
      if (blog.isUserBlog()) {
        Iterator<BlogPost> blogPosts = blogManager.getBlogPosts(blog);
        while (blogPosts.hasNext()) {
          BlogPost blogPost = blogPosts.next();
          if (log.isTraceEnabled()) {
            log.trace("Report spam for Blog post, id: " + blogPost.getID());
          }
          reportSpam(blogPost, reporter, comment, reportDate);
        }
      }
    }
    Iterator<Favorite> favorites =
        favoriteManager.getUserFavorites(spammer, Sets.newHashSet(externalUrlObjectType));
    while (favorites.hasNext()) {
      Favorite favorite = favorites.next();
      JiveObject favoritedObject = favorite.getObjectFavorite().getFavoritedObject();
      if (log.isTraceEnabled()) {
        log.trace("Report spam Favorite (Bookmark) to external URL: " + favorite.getID());
        log.trace("Favorited object: " + favoritedObject);
      }
      reportSpam(favoritedObject, reporter, comment, reportDate);
    }
  }
  /**
   * Set a property of a resource to a value.
   *
   * @param name the property name
   * @param value the property value
   * @exception com.ibm.webdav.WebDAVException
   */
  public void setProperty(String name, Element value) throws WebDAVException {
    // load the properties
    Document propertiesDocument = resource.loadProperties();
    Element properties = propertiesDocument.getDocumentElement();
    String ns = value.getNamespaceURI();

    Element property = null;
    if (ns == null) {
      property = (Element) ((Element) properties).getElementsByTagName(value.getTagName()).item(0);
    } else {
      property = (Element) properties.getElementsByTagNameNS(ns, value.getLocalName()).item(0);
    }

    if (property != null) {
      try {
        properties.removeChild(property);
      } catch (DOMException exc) {
      }
    }

    properties.appendChild(propertiesDocument.importNode(value, true));

    // write out the properties
    resource.saveProperties(propertiesDocument);
  }
예제 #14
0
파일: APFtoXML.java 프로젝트: rgrishman/jet
 /** splits document 'doc' into sentences, adding 'sentence' annotations */
 static void addSentences(Document doc) {
   SpecialZoner.findSpecialZones(doc);
   Vector<Annotation> textSegments = doc.annotationsOfType("TEXT");
   if (textSegments == null) {
     System.out.println("No <TEXT> in document");
     return;
   }
   for (Annotation ann : textSegments) {
     Span textSpan = ann.span();
     // check document case
     Ace.monocase = Ace.allLowerCase(doc);
     // split into sentences
     SentenceSplitter.split(doc, textSpan);
   }
   Vector<Annotation> sentences = doc.annotationsOfType("sentence");
   if (sentences != null) {
     int sentNo = 0;
     for (Annotation sentence : sentences) {
       sentNo++;
       sentence.put("ID", "SENT-" + sentNo);
     }
   }
   doc.removeAnnotationsOfType("dateline");
   doc.removeAnnotationsOfType("textBreak");
   doc.shrink("sentence");
 }
 /**
  * Marshall an array of Genes to an XML Element representation.
  *
  * @param a_geneValues the genes to represent as an XML element
  * @param a_xmlDocument a Document instance that will be used to create the Element instance. Note
  *     that the element will NOT be added to the document by this method
  * @return an Element object representing the given genes
  * @author Neil Rotstan
  * @author Klaus Meffert
  * @since 1.0
  * @deprecated use XMLDocumentBuilder instead
  */
 public static Element representGenesAsElement(
     final Gene[] a_geneValues, final Document a_xmlDocument) {
   // Create the parent genes element.
   // --------------------------------
   Element genesElement = a_xmlDocument.createElement(GENES_TAG);
   // Now add gene sub-elements for each gene in the given array.
   // -----------------------------------------------------------
   Element geneElement;
   for (int i = 0; i < a_geneValues.length; i++) {
     // Create the allele element for this gene.
     // ----------------------------------------
     geneElement = a_xmlDocument.createElement(GENE_TAG);
     // Add the class attribute and set its value to the class
     // name of the concrete class representing the current Gene.
     // ---------------------------------------------------------
     geneElement.setAttribute(CLASS_ATTRIBUTE, a_geneValues[i].getClass().getName());
     // Create a text node to contain the string representation of
     // the gene's value (allele).
     // ----------------------------------------------------------
     Element alleleRepresentation = representAlleleAsElement(a_geneValues[i], a_xmlDocument);
     // And now add the text node to the gene element, and then
     // add the gene element to the genes element.
     // -------------------------------------------------------
     geneElement.appendChild(alleleRepresentation);
     genesElement.appendChild(geneElement);
   }
   return genesElement;
 }
예제 #16
0
  public static void write() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc;

    System.out.println("Writing patient data file\n");

    try {
      DocumentBuilder builder = factory.newDocumentBuilder();
      doc = builder.newDocument();

      Element root = doc.createElement("patientdata");
      root.appendChild(XMLInterface.nl(doc));

      // get first PatientData from DataStore
      Iterator<PatientDataStore> pdsIt = GlobalVars.pds.iterator();
      while (pdsIt.hasNext()) {
        PatientDataStore pds = pdsIt.next();
        Node n = pds.createXMLNode(doc);

        XMLInterface.addNode(doc, root, n, 0);
      }

      root.normalize();
      // create junk to write it out (see java xml tutorial)
      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer();
      DOMSource src = new DOMSource(root);
      StreamResult result = new StreamResult(new File(GlobalVars.XMLDataFile));
      transformer.transform(src, result);
    } catch (Exception e) {
      System.err.println("Error WRITING xml patient data file");
      e.printStackTrace();
    }
  }
예제 #17
0
  private void guardaRes(String resu, CliGol cliGol)
      throws ParserConfigurationException, SAXException, IOException {

    String[] nodos = {"NoHit", "Hit", "Buro"};

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(resu));
    Document xml = db.parse(is);

    Element raiz = xml.getDocumentElement();

    String nombre = obtenerNombre(raiz);

    for (String s : nodos) {

      Node nodo =
          raiz.getElementsByTagName(s) == null ? null : raiz.getElementsByTagName(s).item(0);

      if (nodo != null) {
        String informacion = sustraerInformacionNodo(cliGol, nodo);

        guardarEnListas(nodo.getNodeName(), nombre + "," + informacion);
      }
    }
  }
  @Nullable
  public Runnable startNonCustomTemplates(
      final Map<TemplateImpl, String> template2argument,
      final Editor editor,
      @Nullable final PairProcessor<String, String> processor) {
    final int caretOffset = editor.getCaretModel().getOffset();
    final Document document = editor.getDocument();
    final CharSequence text = document.getCharsSequence();

    if (template2argument == null || template2argument.isEmpty()) {
      return null;
    }
    if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), myProject)) {
      return null;
    }

    return () -> {
      if (template2argument.size() == 1) {
        TemplateImpl template = template2argument.keySet().iterator().next();
        String argument = template2argument.get(template);
        int templateStart = getTemplateStart(template, argument, caretOffset, text);
        startTemplateWithPrefix(editor, template, templateStart, processor, argument);
      } else {
        ListTemplatesHandler.showTemplatesLookup(myProject, editor, template2argument);
      }
    };
  }
예제 #19
0
 static void writeDoc1(Document doc, PrintStream out) throws IOException {
   Vector<Annotation> entities = doc.annotationsOfType("entity");
   if (entities == null) {
     System.err.println("No Entity: " + doc);
     return;
   }
   Iterator<Annotation> entityIt = entities.iterator();
   int i = 0;
   while (entityIt.hasNext()) {
     Annotation entity = entityIt.next();
     Vector mentions = (Vector) entity.get("mentions");
     Iterator mentionIt = mentions.iterator();
     String nameType = (String) entity.get("nameType");
     while (mentionIt.hasNext()) {
       Annotation mention1 = (Annotation) mentionIt.next();
       Annotation mention2 = new Annotation("refobj", mention1.span(), new FeatureSet());
       mention2.put("objid", Integer.toString(i));
       if (nameType != null) {
         mention2.put("netype", nameType);
       }
       doc.addAnnotation(mention2);
     }
     i++;
   }
   // remove other annotations.
   String[] annotypes = doc.getAnnotationTypes();
   for (i = 0; i < annotypes.length; i++) {
     String t = annotypes[i];
     if (!(t.equals("tagger") || t.equals("refobj") || t.equals("ENAMEX"))) {
       doc.removeAnnotationsOfType(t);
     }
   }
   writeDocRaw(doc, out);
   return;
 }
예제 #20
0
 /**
  * Import an XQuery library module from the given document. The namespace and preferred prefix of
  * the module are extracted from the module itself. The MIME type of the document is set to
  * "application/xquery" as a side-effect.
  *
  * @param module the non-XML document that holds the library module's source
  * @return this service, to chain calls
  * @throws DatabaseException if the module is an XML document, or the module declaration cannot be
  *     found at the top of the document
  */
 public QueryService importModule(Document module) {
   if (module instanceof XMLDocument)
     throw new DatabaseException("module cannot be an XML document: " + module);
   Matcher matcher = MODULE_DECLARATION_DQUOTE.matcher(module.contentsAsString());
   if (!matcher.find()) {
     matcher = MODULE_DECLARATION_SQUOTE.matcher(module.contentsAsString());
     if (!matcher.find())
       throw new DatabaseException("couldn't find a module declaration at the top of " + module);
   }
   module.metadata().setMimeType("application/xquery");
   String moduleNamespace = matcher.group(1);
   // TODO: should do URILiteral processing here to replace entity and character references and
   // normalize
   // whitespace, but since it seems that eXist doesn't do it either (bug?) there's no reason to
   // rush.
   Document prevModule = moduleMap.get(moduleNamespace);
   if (prevModule != null && !prevModule.equals(module))
     throw new DatabaseException(
         "module "
             + moduleNamespace
             + " already bound to "
             + prevModule
             + ", can't rebind to "
             + module);
   moduleMap.put(moduleNamespace, module);
   return this;
 }
예제 #21
0
  /**
   * Processes the messages from the server
   *
   * @param message
   */
  private synchronized void processServerMessage(String message) {
    SAXBuilder builder = new SAXBuilder();
    String what = new String();
    Document doc = null;

    try {
      doc = builder.build(new StringReader(message));
      Element root = doc.getRootElement();
      List childs = root.getChildren();
      Iterator i = childs.iterator();
      what = ((Element) i.next()).getName();
    } catch (Exception e) {
    }

    if (what.equalsIgnoreCase("LOGIN") == true) _login(doc);
    else if (what.equalsIgnoreCase("LOGOUT") == true) _logout(doc);
    else if (what.equalsIgnoreCase("MESSAGE") == true) _message(doc);
    else if (what.equalsIgnoreCase("WALL") == true) _wall(doc);
    else if (what.equalsIgnoreCase("CREATEGROUP") == true) _creategroup(doc);
    else if (what.equalsIgnoreCase("JOINGROUP") == true) _joingroup(doc);
    else if (what.equalsIgnoreCase("PARTGROUP") == true) _partgroup(doc);
    else if (what.equalsIgnoreCase("GROUPMESSAGE") == true) _groupmessage(doc);
    else if (what.equalsIgnoreCase("KICK") == true) _kick(doc);
    else if (what.equalsIgnoreCase("LISTUSER") == true) _listuser(doc);
    else if (what.equalsIgnoreCase("LISTGROUP") == true) _listgroup(doc);
  }
예제 #22
0
  /**
   * Process index terms.
   *
   * @param theInput input document
   * @return read index terms
   * @throws ProcessException if processing index terms failed
   */
  public IndexPreprocessResult process(final Document theInput) throws ProcessException {
    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    try {
      documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (final ParserConfigurationException e) {
      throw new RuntimeException("Unable to create a document builder: " + e.getMessage(), e);
    }
    final Document doc = documentBuilder.newDocument();

    final Node rootElement = theInput.getDocumentElement();

    final ArrayList<IndexEntry> indexes = new ArrayList<IndexEntry>();

    final IndexEntryFoundListener listener =
        new IndexEntryFoundListener() {
          public void foundEntry(final IndexEntry theEntry) {
            indexes.add(theEntry);
          }
        };

    final Node node = processCurrNode(rootElement, doc, listener)[0];

    doc.appendChild(node);

    doc.getDocumentElement().setAttribute(XMLNS_ATTRIBUTE + ":" + this.prefix, this.namespace_url);

    return new IndexPreprocessResult(doc, (IndexEntry[]) indexes.toArray(new IndexEntry[0]));
  }
  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")));
    }
  }
예제 #24
0
 /**
  * Overwrite this method if you want to filter the input, apply hashing, etc.
  *
  * @param feature the current feature.
  * @param document the current document.
  * @param featureFieldName the field hashFunctionsFileName of the feature.
  */
 protected void addToDocument(LireFeature feature, Document document, String featureFieldName) {
   if (run == 0) {
   } // just count documents
   else if (run == 1) { // Select the representatives ...
     if (representativesID.contains(docCount)
         && feature
             .getClass()
             .getCanonicalName()
             .equals(featureClass.getCanonicalName())) { // it's a representative.
       // put it into a temporary data structure ...
       representatives.add(feature);
     }
   } else if (run
       == 2) { // actual hashing: find the nearest representatives and put those as a hash into a
     // document.
     if (feature
         .getClass()
         .getCanonicalName()
         .equals(featureClass.getCanonicalName())) { // it's a feature to be hashed
       int[] hashes = getHashes(feature);
       document.add(
           new TextField(
               featureFieldName + "_hash",
               createDocumentString(hashes, hashes.length),
               Field.Store.YES));
       document.add(
           new TextField(
               featureFieldName + "_hash_q", createDocumentString(hashes, 10), Field.Store.YES));
     }
     document.add(new StoredField(featureFieldName, feature.getByteArrayRepresentation()));
   }
 }
 /**
  * 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;
 }
  public void testDocSynchronizerPrefersLineBoundaryChanges() throws Exception {
    String text =
        "import java.awt.List;\n"
            + "[import java.util.ArrayList;\n]"
            + "import java.util.HashMap;\n"
            + "import java.util.Map;";
    RangeMarker marker = createMarker(text);
    synchronizer.startTransaction(getProject(), document, psiFile);

    String newText = StringUtil.replaceSubstring(document.getText(), TextRange.create(marker), "");
    synchronizer.replaceString(document, 0, document.getTextLength(), newText);

    final List<DocumentEvent> events = new ArrayList<DocumentEvent>();
    document.addDocumentListener(
        new DocumentAdapter() {
          @Override
          public void documentChanged(DocumentEvent e) {
            events.add(e);
          }
        });
    synchronizer.commitTransaction(document);

    assertEquals(newText, document.getText());
    DocumentEvent event = assertOneElement(events);
    assertEquals(
        "DocumentEventImpl[myOffset=22, myOldLength=28, myNewLength=0, myOldString='import java.util.ArrayList;\n', myNewString=''].",
        event.toString());
  }
  /**
   * 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) {
          }
        }
      }
    }
  }
  public void testRangeMarkersAreLazyCreated() throws Exception {
    final Document document = EditorFactory.getInstance().createDocument("[xxxxxxxxxxxxxx]");
    RangeMarker m1 = document.createRangeMarker(2, 4);
    RangeMarker m2 = document.createRangeMarker(2, 4);

    assertEquals(2, ((DocumentImpl) document).getRangeMarkersSize());
    assertEquals(1, ((DocumentImpl) document).getRangeMarkersNodeSize());

    RangeMarker m3 = document.createRangeMarker(2, 5);
    assertEquals(2, ((DocumentImpl) document).getRangeMarkersNodeSize());
    document.deleteString(4, 5);
    assertTrue(m1.isValid());
    assertTrue(m2.isValid());
    assertTrue(m3.isValid());
    assertEquals(1, ((DocumentImpl) document).getRangeMarkersNodeSize());

    m1.setGreedyToLeft(true);
    assertTrue(m1.isValid());
    assertEquals(3, ((DocumentImpl) document).getRangeMarkersSize());
    assertEquals(2, ((DocumentImpl) document).getRangeMarkersNodeSize());

    m3.dispose();
    assertTrue(m1.isValid());
    assertTrue(m2.isValid());
    assertFalse(m3.isValid());
    assertEquals(2, ((DocumentImpl) document).getRangeMarkersSize());
    assertEquals(2, ((DocumentImpl) document).getRangeMarkersNodeSize());
  }
  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;
      }
    }
  }
예제 #30
0
  /**
   * Creates a new Outline object.
   *
   * @param djvuBean the DjVuBean to navigate.
   * @throws ArrayIndexOutOfBoundsException if the document has less than 2 pages.
   */
  public Outline(final DjVuBean djvuBean) {
    this.djvuBean = djvuBean;

    if (djvuBean.getDocument().size() < 2) {
      throw new ArrayIndexOutOfBoundsException("Can not navigate documents with only one page.");
    }

    final MouseListener mouseListener =
        new MouseAdapter() {
          public void mouseClicked(final MouseEvent e) {
            try {
              clickLocation(e.getX(), e.getY());
            } catch (final Throwable exp) {
              exp.printStackTrace(DjVuOptions.err);
              System.gc();
            }
          }
        };

    addMouseListener(mouseListener);

    final Document document = djvuBean.getDocument();
    final Bookmark bookmark = (Bookmark) document.getBookmark();
    bookmark.setDjVmDir(document.getDjVmDir());
    setFirstBookmark(bookmark);

    final Properties properties = djvuBean.properties;
    properties.put("addOn.NavPane", "Outline," + properties.getProperty("addOn.NavPane", "None"));
    djvuBean.addPropertyChangeListener(this);
  }