Beispiel #1
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;
  }
Beispiel #2
0
  public void saveToXml(String fileName)
      throws ParserConfigurationException, FileNotFoundException, TransformerException,
          TransformerConfigurationException {
    System.out.println("Saving network topology to file " + fileName);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document doc = parser.newDocument();

    Element root = doc.createElement("neuralNetwork");
    root.setAttribute("dateOfExport", new Date().toString());
    Element layers = doc.createElement("structure");
    layers.setAttribute("numberOfLayers", Integer.toString(this.numberOfLayers()));

    for (int il = 0; il < this.numberOfLayers(); il++) {
      Element layer = doc.createElement("layer");
      layer.setAttribute("index", Integer.toString(il));
      layer.setAttribute("numberOfNeurons", Integer.toString(this.getLayer(il).numberOfNeurons()));

      for (int in = 0; in < this.getLayer(il).numberOfNeurons(); in++) {
        Element neuron = doc.createElement("neuron");
        neuron.setAttribute("index", Integer.toString(in));
        neuron.setAttribute(
            "NumberOfInputs", Integer.toString(this.getLayer(il).getNeuron(in).numberOfInputs()));
        neuron.setAttribute(
            "threshold", Double.toString(this.getLayer(il).getNeuron(in).threshold));

        for (int ii = 0; ii < this.getLayer(il).getNeuron(in).numberOfInputs(); ii++) {
          Element input = doc.createElement("input");
          input.setAttribute("index", Integer.toString(ii));
          input.setAttribute(
              "weight", Double.toString(this.getLayer(il).getNeuron(in).getInput(ii).weight));

          neuron.appendChild(input);
        }

        layer.appendChild(neuron);
      }

      layers.appendChild(layer);
    }

    root.appendChild(layers);
    doc.appendChild(root);

    // save
    File xmlOutputFile = new File(fileName);
    FileOutputStream fos;
    Transformer transformer;

    fos = new FileOutputStream(xmlOutputFile);
    // Use a Transformer for output
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(fos);
    // transform source into result will do save
    transformer.setOutputProperty("encoding", "iso-8859-2");
    transformer.setOutputProperty("indent", "yes");
    transformer.transform(source, result);
  }
 /**
  * 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;
 }
  /**
   * Converts value object to XML representation.
   *
   * @return Element.
   */
  public Element toXml(Document doc) {
    Element root = doc.createElement("InvoiceCustDetail");
    root.setAttribute("Id", String.valueOf(mOrderItemData));

    Element node;

    node = doc.createElement("InvoiceCustDetailData");
    node.appendChild(doc.createTextNode(String.valueOf(mInvoiceCustDetailData)));
    root.appendChild(node);

    return root;
  }
Beispiel #5
0
 public void toWrite(int size, String[] mycontent) {
   Element root = document.createElement("WorkShop");
   document.appendChild(root);
   Element title = document.createElement("Size");
   title.appendChild(document.createTextNode(size + ""));
   root.appendChild(title);
   for (int i = 0; i < size; i++) {
     Element content = document.createElement("Content" + i);
     content.appendChild(document.createTextNode(mycontent[i]));
     root.appendChild(content);
   }
 }
Beispiel #6
0
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      DateFormat df = DateFormat.getDateTimeInstance();
      String titleStr = "C3P0 Status - " + df.format(new Date());

      DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fact.newDocumentBuilder();
      Document doc = db.newDocument();

      Element htmlElem = doc.createElement("html");
      Element headElem = doc.createElement("head");

      Element titleElem = doc.createElement("title");
      titleElem.appendChild(doc.createTextNode(titleStr));

      Element bodyElem = doc.createElement("body");

      Element h1Elem = doc.createElement("h1");
      h1Elem.appendChild(doc.createTextNode(titleStr));

      Element h3Elem = doc.createElement("h3");
      h3Elem.appendChild(doc.createTextNode("PooledDataSources"));

      Element pdsDlElem = doc.createElement("dl");
      pdsDlElem.setAttribute("class", "PooledDataSources");
      for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) {
        PooledDataSource pds = (PooledDataSource) ii.next();
        StatusReporter sr = findStatusReporter(pds, doc);
        pdsDlElem.appendChild(sr.reportDtElem());
        pdsDlElem.appendChild(sr.reportDdElem());
      }

      headElem.appendChild(titleElem);
      htmlElem.appendChild(headElem);

      bodyElem.appendChild(h1Elem);
      bodyElem.appendChild(h3Elem);
      bodyElem.appendChild(pdsDlElem);
      htmlElem.appendChild(bodyElem);

      res.setContentType("application/xhtml+xml");

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      Source src = new DOMSource(doc);
      Result result = new StreamResult(res.getOutputStream());
      transformer.transform(src, result);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
  /**
   * 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);
  }
 public void addElement(Element el, BoxBounds bounds) {
   Layer layer = new Layer(el, bounds);
   layers.add(layer);
   el.getStyle().setPosition(Style.Position.ABSOLUTE);
   presetLayerBounds(layer);
   container.appendChild(el);
 }
Beispiel #9
0
  /**
   * Writes a table to a XML-file
   *
   * @param t - Output Model
   * @param destination - File Destination
   */
  public static void writeXML(Model t, String destination) {

    try {
      // Create the XML document builder, and document that will be used
      DocumentBuilderFactory xmlBuilder = DocumentBuilderFactory.newInstance();
      DocumentBuilder Builder = xmlBuilder.newDocumentBuilder();
      Document xmldoc = Builder.newDocument();

      // create Document node, and get it into the file
      Element Documentnode = xmldoc.createElement("SPREADSHEET");
      xmldoc.appendChild(Documentnode);

      // create element nodes, and their attributes (Cells, and row/column
      // data) and their content
      for (int row = 1; row < t.getRows(); row++) {
        for (int col = 1; col < t.getCols(col); col++) {
          Element cell = xmldoc.createElement("CELL");
          // set attributes
          cell.setAttribute("column", Integer.toString(col));
          cell.setAttribute("row", Integer.toString(col));
          // set content
          cell.appendChild(xmldoc.createTextNode((String) t.getContent(row, col)));
          // append node to document node
          Documentnode.appendChild(cell);
        }
      }
      // Creating a datastream for the DOM tree
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      // Indentation to make the XML file look better
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      // remove the java version
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      DOMSource stream = new DOMSource(xmldoc);
      StreamResult target = new StreamResult(new File(destination));
      // write the file
      transformer.transform(stream, target);

    } catch (ParserConfigurationException e) {
      System.out.println("Can't create the XML document builder");
    } catch (TransformerConfigurationException e) {
      System.out.println("Can't create transformer");
    } catch (TransformerException e) {
      System.out.println("Can't write to file");
    }
  }
 protected void setAttribute(String name, String attName, String attValue) {
   Element elt = getElement(name);
   if (elt == null) {
     elt = doc.createElement(name);
     docElt.appendChild(elt);
   }
   elt.setAttribute(attName, attValue);
 }
  private Element generateGraphicsNode(Document doc, ClassGraphics gr) {

    Element graphicsEl = doc.createElement(EL_GRAPHICS);

    Element bounds = doc.createElement(EL_BOUNDS);
    graphicsEl.appendChild(bounds);
    bounds.setAttribute(ATR_X, Integer.toString(gr.getBoundX()));
    bounds.setAttribute(ATR_Y, Integer.toString(gr.getBoundY()));
    bounds.setAttribute(ATR_WIDTH, Integer.toString(gr.getBoundWidth()));
    bounds.setAttribute(ATR_HEIGHT, Integer.toString(gr.getBoundHeight()));

    for (Shape shape : gr.getShapes()) {

      if (shape instanceof Rect) {
        Rect rect = (Rect) shape;
        Element rectEl = doc.createElement(EL_RECT);
        graphicsEl.appendChild(rectEl);
        rectEl.setAttribute(ATR_X, Integer.toString(rect.getX()));
        rectEl.setAttribute(ATR_Y, Integer.toString(rect.getY()));
        rectEl.setAttribute(ATR_WIDTH, Integer.toString(rect.getWidth()));
        rectEl.setAttribute(ATR_HEIGHT, Integer.toString(rect.getHeight()));
        rectEl.setAttribute(ATR_COLOUR, Integer.toString(rect.getColor().getRGB()));
        rectEl.setAttribute(ATR_FILLED, Boolean.toString(rect.isFilled()));
        rectEl.setAttribute(ATR_FIXED, Boolean.toString(rect.isFixed()));
        rectEl.setAttribute(ATR_STROKE, Float.toString(rect.getStroke().getLineWidth()));
        rectEl.setAttribute(ATR_LINETYPE, Float.toString(rect.getLineType()));
        rectEl.setAttribute(ATR_TRANSPARENCY, Integer.toString(rect.getTransparency()));
      } else if (shape instanceof Text) {
        Text text = (Text) shape;
        Element textEl = doc.createElement(EL_TEXT);
        textEl.setAttribute(ATR_STRING, text.getText());
        textEl.setAttribute(ATR_X, Integer.toString(text.getX()));
        textEl.setAttribute(ATR_Y, Integer.toString(text.getY()));
        textEl.setAttribute(ATR_FONTNAME, text.getFont().getName());
        textEl.setAttribute(ATR_FONTSIZE, Integer.toString(text.getFont().getSize()));
        textEl.setAttribute(ATR_FONTSTYLE, Integer.toString(text.getFont().getStyle()));
        textEl.setAttribute(ATR_TRANSPARENCY, Integer.toString(text.getTransparency()));
        textEl.setAttribute(ATR_COLOUR, Integer.toString(text.getColor().getRGB()));
        graphicsEl.appendChild(textEl);
      } // TODO handle the rest of shapes
    }

    return graphicsEl;
  }
 public Track add(Track track) {
   synchronized (this) {
     Track copy;
     if ((copy = getTrack(track)) == null) {
       copy = new Track((Element) doc.importNode(track.getElement(), false));
       docElt.appendChild(copy.getElement());
       tracks.add(copy);
       hash.put(copy.getKey(), copy);
     }
     return copy;
   }
 }
Beispiel #13
0
    public Element reportDtElem() {
      StringBuffer sb = new StringBuffer(255);
      sb.append(shortTypeName);
      sb.append(" [ dataSourceName: ");
      sb.append(pds.getDataSourceName());
      sb.append("; identityToken: ");
      sb.append(pds.getIdentityToken());
      sb.append(" ]");

      Element dtElem = doc.createElement("dt");
      dtElem.appendChild(doc.createTextNode(sb.toString()));
      return dtElem;
    }
  /**
   * @param chkKeys List of String objects with the shas
   * @param targetFile target file
   * @return true if write was successful
   */
  public static boolean writeRequestFile(
      final FileRequestFileContent content, final File targetFile) {

    final Document doc = XMLTools.createDomDocument();
    if (doc == null) {
      logger.severe("Error - writeRequestFile: factory could'nt create XML Document.");
      return false;
    }

    final Element rootElement = doc.createElement(TAG_FrostFileRequestFile);
    doc.appendChild(rootElement);

    final Element timeStampElement = doc.createElement(TAG_timestamp);
    final Text timeStampText = doc.createTextNode(Long.toString(content.getTimestamp()));
    timeStampElement.appendChild(timeStampText);
    rootElement.appendChild(timeStampElement);

    final Element rootChkElement = doc.createElement(TAG_shaList);
    rootElement.appendChild(rootChkElement);

    for (final String chkKey : content.getShaStrings()) {

      final Element nameElement = doc.createElement(TAG_sha);
      final Text text = doc.createTextNode(chkKey);
      nameElement.appendChild(text);

      rootChkElement.appendChild(nameElement);
    }

    boolean writeOK = false;
    try {
      writeOK = XMLTools.writeXmlFile(doc, targetFile);
    } catch (final Throwable t) {
      logger.log(Level.SEVERE, "Exception in writeRequestFile/writeXmlFile", t);
    }

    return writeOK;
  }
 /**
  * set container
  *
  * @param container container
  * @return content layer
  */
 public Element init(
     Element container, int insetLeft, int insetTop, int insetRight, int insetBottom) {
   this.container = container;
   if (!"absolute".equals(container.getStyle().getPosition())
       && !"relative".equals(container.getStyle().getPosition())) {
     container.getStyle().setPosition(Style.Position.RELATIVE);
   }
   Element contentLayer = DOM.createDiv();
   contentLayer.getStyle().setPosition(Style.Position.ABSOLUTE);
   if (insetTop > 0) contentLayer.getStyle().setPaddingTop(insetTop, Style.Unit.PX);
   if (insetLeft > 0) contentLayer.getStyle().setPaddingLeft(insetLeft, Style.Unit.PX);
   if (insetRight > 0) contentLayer.getStyle().setPaddingRight(insetRight, Style.Unit.PX);
   if (insetBottom > 0) contentLayer.getStyle().setPaddingBottom(insetBottom, Style.Unit.PX);
   container.appendChild(contentLayer);
   return contentLayer;
 }
Beispiel #16
0
  /**
   * Carries out preprocessing that makes JEuclid handle the document better.
   *
   * @param doc Document
   */
  static void preprocessForJEuclid(Document doc) {
    // underbrace and overbrace
    NodeList list = doc.getElementsByTagName("mo");
    for (int i = 0; i < list.getLength(); i++) {
      Element mo = (Element) list.item(i);
      String parentName = ((Element) mo.getParentNode()).getTagName();
      if (parentName == null) {
        continue;
      }
      if (parentName.equals("munder") && isTextChild(mo, "\ufe38")) {
        mo.setAttribute("stretchy", "true");
        mo.removeChild(mo.getFirstChild());
        mo.appendChild(doc.createTextNode("\u23df"));
      } else if (parentName.equals("mover") && isTextChild(mo, "\ufe37")) {
        mo.setAttribute("stretchy", "true");
        mo.removeChild(mo.getFirstChild());
        mo.appendChild(doc.createTextNode("\u23de"));
      }
    }

    // menclose for long division doesn't allow enough top padding. Oh, and
    // <mpadded> isn't implemented. And there isn't enough padding to left of
    // the bar either. Solve by adding an <mover> with just an <mspace> over#
    // the longdiv, contained within an mrow that adds a <mspace> before it.
    list = doc.getElementsByTagName("menclose");
    for (int i = 0; i < list.getLength(); i++) {
      Element menclose = (Element) list.item(i);
      // Only for longdiv
      if (!"longdiv".equals(menclose.getAttribute("notation"))) {
        continue;
      }
      Element mrow = doc.createElementNS(WebMathsService.NS, "mrow");
      Element mover = doc.createElementNS(WebMathsService.NS, "mover");
      Element mspace = doc.createElementNS(WebMathsService.NS, "mspace");
      Element mspaceW = doc.createElementNS(WebMathsService.NS, "mspace");
      boolean previousElement = false;
      for (Node previous = menclose.getPreviousSibling();
          previous != null;
          previous = previous.getPreviousSibling()) {
        if (previous.getNodeType() == Node.ELEMENT_NODE) {
          previousElement = true;
          break;
        }
      }
      if (previousElement) {
        mspaceW.setAttribute("width", "4px");
      }
      menclose.getParentNode().insertBefore(mrow, menclose);
      menclose.getParentNode().removeChild(menclose);
      mrow.appendChild(mspaceW);
      mrow.appendChild(mover);
      mover.appendChild(menclose);
      mover.appendChild(mspace);
    }
  }
 /**
  * Marshall a Chromosome instance to an XML Element representation, including its contained Genes
  * as sub-elements. This may be useful in scenarios where representation as an entire Document is
  * undesirable, such as when the representation of this Chromosome is to be combined with other
  * elements in a single Document.
  *
  * @param a_subject the chromosome 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 Chromosome
  * @author Neil Rotstan
  * @since 1.0
  * @deprecated use XMLDocumentBuilder instead
  */
 public static Element representChromosomeAsElement(
     final IChromosome a_subject, final Document a_xmlDocument) {
   // Start by creating an element for the chromosome and its size
   // attribute, which represents the number of genes in the chromosome.
   // ------------------------------------------------------------------
   Element chromosomeElement = a_xmlDocument.createElement(CHROMOSOME_TAG);
   chromosomeElement.setAttribute(SIZE_ATTRIBUTE, Integer.toString(a_subject.size()));
   // Next create the genes element with its nested gene elements,
   // which will contain string representations of the alleles.
   // --------------------------------------------------------------
   Element genesElement = representGenesAsElement(a_subject.getGenes(), a_xmlDocument);
   // Add the new genes element to the chromosome element and then
   // return the chromosome element.
   // -------------------------------------------------------------
   chromosomeElement.appendChild(genesElement);
   return chromosomeElement;
 }
 /**
  * Marshall a Genotype instance into an XML Element representation, including its population of
  * Chromosome instances as sub-elements. This may be useful in scenarios where representation as
  * an entire Document is undesirable, such as when the representation of this Genotype is to be
  * combined with other elements in a single Document.
  *
  * @param a_subject the genotype 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 Genotype
  * @author Neil Rotstan
  * @since 1.0
  * @deprecated use XMLDocumentBuilder instead
  */
 public static Element representGenotypeAsElement(
     final Genotype a_subject, final Document a_xmlDocument) {
   Population population = a_subject.getPopulation();
   // Start by creating the genotype element and its size attribute,
   // which represents the number of chromosomes present in the
   // genotype.
   // --------------------------------------------------------------
   Element genotypeTag = a_xmlDocument.createElement(GENOTYPE_TAG);
   genotypeTag.setAttribute(SIZE_ATTRIBUTE, Integer.toString(population.size()));
   // Next, add nested elements for each of the chromosomes in the
   // genotype.
   // ------------------------------------------------------------
   for (int i = 0; i < population.size(); i++) {
     Element chromosomeElement =
         representChromosomeAsElement(population.getChromosome(i), a_xmlDocument);
     genotypeTag.appendChild(chromosomeElement);
   }
   return genotypeTag;
 }
  /**
   * Converts value object to XML representation.
   *
   * @return Element.
   */
  public Element toXml(Document doc) {
    Element root = doc.createElement("InboundPollockOrderGuideLoader");
    root.setAttribute("Id", String.valueOf(mEditType));

    Element node;

    node = doc.createElement("RecordType");
    node.appendChild(doc.createTextNode(String.valueOf(mRecordType)));
    root.appendChild(node);

    node = doc.createElement("RecordValue1");
    node.appendChild(doc.createTextNode(String.valueOf(mRecordValue1)));
    root.appendChild(node);

    node = doc.createElement("RecordValue2");
    node.appendChild(doc.createTextNode(String.valueOf(mRecordValue2)));
    root.appendChild(node);

    node = doc.createElement("RecordValue3");
    node.appendChild(doc.createTextNode(String.valueOf(mRecordValue3)));
    root.appendChild(node);

    return root;
  }
  public void build_bricks() {

    ImagePlus imp;
    ImagePlus orgimp;
    ImageStack stack;
    FileInfo finfo;

    if (lvImgTitle.isEmpty()) return;
    orgimp = WindowManager.getImage(lvImgTitle.get(0));
    imp = orgimp;

    finfo = imp.getFileInfo();
    if (finfo == null) return;

    int[] dims = imp.getDimensions();
    int imageW = dims[0];
    int imageH = dims[1];
    int nCh = dims[2];
    int imageD = dims[3];
    int nFrame = dims[4];
    int bdepth = imp.getBitDepth();
    double xspc = finfo.pixelWidth;
    double yspc = finfo.pixelHeight;
    double zspc = finfo.pixelDepth;
    double z_aspect = Math.max(xspc, yspc) / zspc;

    int orgW = imageW;
    int orgH = imageH;
    int orgD = imageD;
    double orgxspc = xspc;
    double orgyspc = yspc;
    double orgzspc = zspc;

    lv = lvImgTitle.size();
    if (filetype == "JPEG") {
      for (int l = 0; l < lv; l++) {
        if (WindowManager.getImage(lvImgTitle.get(l)).getBitDepth() != 8) {
          IJ.error("A SOURCE IMAGE MUST BE 8BIT GLAYSCALE");
          return;
        }
      }
    }

    // calculate levels
    /*		int baseXY = 256;
    		int baseZ = 256;

    		if (z_aspect < 0.5) baseZ = 128;
    		if (z_aspect > 2.0) baseXY = 128;
    		if (z_aspect >= 0.5 && z_aspect < 1.0) baseZ = (int)(baseZ*z_aspect);
    		if (z_aspect > 1.0 && z_aspect <= 2.0) baseXY = (int)(baseXY/z_aspect);

    		IJ.log("Z_aspect: " + z_aspect);
    		IJ.log("BaseXY: " + baseXY);
    		IJ.log("BaseZ: " + baseZ);
    */

    int baseXY = 256;
    int baseZ = 128;
    int dbXY = Math.max(orgW, orgH) / baseXY;
    if (Math.max(orgW, orgH) % baseXY > 0) dbXY *= 2;
    int dbZ = orgD / baseZ;
    if (orgD % baseZ > 0) dbZ *= 2;
    lv = Math.max(log2(dbXY), log2(dbZ)) + 1;

    int ww = orgW;
    int hh = orgH;
    int dd = orgD;
    for (int l = 0; l < lv; l++) {
      int bwnum = ww / baseXY;
      if (ww % baseXY > 0) bwnum++;
      int bhnum = hh / baseXY;
      if (hh % baseXY > 0) bhnum++;
      int bdnum = dd / baseZ;
      if (dd % baseZ > 0) bdnum++;

      if (bwnum % 2 == 0) bwnum++;
      if (bhnum % 2 == 0) bhnum++;
      if (bdnum % 2 == 0) bdnum++;

      int bw = (bwnum <= 1) ? ww : ww / bwnum + 1 + (ww % bwnum > 0 ? 1 : 0);
      int bh = (bhnum <= 1) ? hh : hh / bhnum + 1 + (hh % bhnum > 0 ? 1 : 0);
      int bd = (bdnum <= 1) ? dd : dd / bdnum + 1 + (dd % bdnum > 0 ? 1 : 0);

      bwlist.add(bw);
      bhlist.add(bh);
      bdlist.add(bd);

      IJ.log("LEVEL: " + l);
      IJ.log("  width: " + ww);
      IJ.log("  hight: " + hh);
      IJ.log("  depth: " + dd);
      IJ.log("  bw: " + bw);
      IJ.log("  bh: " + bh);
      IJ.log("  bd: " + bd);

      int xyl2 = Math.max(ww, hh) / baseXY;
      if (Math.max(ww, hh) % baseXY > 0) xyl2 *= 2;
      if (lv - 1 - log2(xyl2) <= l) {
        ww /= 2;
        hh /= 2;
      }
      IJ.log("  xyl2: " + (lv - 1 - log2(xyl2)));

      int zl2 = dd / baseZ;
      if (dd % baseZ > 0) zl2 *= 2;
      if (lv - 1 - log2(zl2) <= l) dd /= 2;
      IJ.log("  zl2: " + (lv - 1 - log2(zl2)));

      if (l < lv - 1) {
        lvImgTitle.add(lvImgTitle.get(0) + "_level" + (l + 1));
        IJ.selectWindow(lvImgTitle.get(0));
        IJ.run(
            "Scale...",
            "x=- y=- z=- width="
                + ww
                + " height="
                + hh
                + " depth="
                + dd
                + " interpolation=Bicubic average process create title="
                + lvImgTitle.get(l + 1));
      }
    }

    for (int l = 0; l < lv; l++) {
      IJ.log(lvImgTitle.get(l));
    }

    Document doc = newXMLDocument();
    Element root = doc.createElement("BRK");
    root.setAttribute("version", "1.0");
    root.setAttribute("nLevel", String.valueOf(lv));
    root.setAttribute("nChannel", String.valueOf(nCh));
    root.setAttribute("nFrame", String.valueOf(nFrame));
    doc.appendChild(root);

    for (int l = 0; l < lv; l++) {
      IJ.showProgress(0.0);

      int[] dims2 = imp.getDimensions();
      IJ.log(
          "W: "
              + String.valueOf(dims2[0])
              + " H: "
              + String.valueOf(dims2[1])
              + " C: "
              + String.valueOf(dims2[2])
              + " D: "
              + String.valueOf(dims2[3])
              + " T: "
              + String.valueOf(dims2[4])
              + " b: "
              + String.valueOf(bdepth));

      bw = bwlist.get(l).intValue();
      bh = bhlist.get(l).intValue();
      bd = bdlist.get(l).intValue();

      boolean force_pow2 = false;
      /*			if(IsPowerOf2(bw) && IsPowerOf2(bh) && IsPowerOf2(bd)) force_pow2 = true;

      			if(force_pow2){
      				//force pow2
      				if(Pow2(bw) > bw) bw = Pow2(bw)/2;
      				if(Pow2(bh) > bh) bh = Pow2(bh)/2;
      				if(Pow2(bd) > bd) bd = Pow2(bd)/2;
      			}

      			if(bw > imageW) bw = (Pow2(imageW) == imageW) ? imageW : Pow2(imageW)/2;
      			if(bh > imageH) bh = (Pow2(imageH) == imageH) ? imageH : Pow2(imageH)/2;
      			if(bd > imageD) bd = (Pow2(imageD) == imageD) ? imageD : Pow2(imageD)/2;

      */
      if (bw > imageW) bw = imageW;
      if (bh > imageH) bh = imageH;
      if (bd > imageD) bd = imageD;

      if (bw <= 1 || bh <= 1 || bd <= 1) break;

      if (filetype == "JPEG" && (bw < 8 || bh < 8)) break;

      Element lvnode = doc.createElement("Level");
      lvnode.setAttribute("lv", String.valueOf(l));
      lvnode.setAttribute("imageW", String.valueOf(imageW));
      lvnode.setAttribute("imageH", String.valueOf(imageH));
      lvnode.setAttribute("imageD", String.valueOf(imageD));
      lvnode.setAttribute("xspc", String.valueOf(xspc));
      lvnode.setAttribute("yspc", String.valueOf(yspc));
      lvnode.setAttribute("zspc", String.valueOf(zspc));
      lvnode.setAttribute("bitDepth", String.valueOf(bdepth));
      root.appendChild(lvnode);

      Element brksnode = doc.createElement("Bricks");
      brksnode.setAttribute("brick_baseW", String.valueOf(bw));
      brksnode.setAttribute("brick_baseH", String.valueOf(bh));
      brksnode.setAttribute("brick_baseD", String.valueOf(bd));
      lvnode.appendChild(brksnode);

      ArrayList<Brick> bricks = new ArrayList<Brick>();
      int mw, mh, md, mw2, mh2, md2;
      double tx0, ty0, tz0, tx1, ty1, tz1;
      double bx0, by0, bz0, bx1, by1, bz1;
      for (int k = 0; k < imageD; k += bd) {
        if (k > 0) k--;
        for (int j = 0; j < imageH; j += bh) {
          if (j > 0) j--;
          for (int i = 0; i < imageW; i += bw) {
            if (i > 0) i--;
            mw = Math.min(bw, imageW - i);
            mh = Math.min(bh, imageH - j);
            md = Math.min(bd, imageD - k);

            if (force_pow2) {
              mw2 = Pow2(mw);
              mh2 = Pow2(mh);
              md2 = Pow2(md);
            } else {
              mw2 = mw;
              mh2 = mh;
              md2 = md;
            }

            if (filetype == "JPEG") {
              if (mw2 < 8) mw2 = 8;
              if (mh2 < 8) mh2 = 8;
            }

            tx0 = i == 0 ? 0.0d : ((mw2 - mw + 0.5d) / mw2);
            ty0 = j == 0 ? 0.0d : ((mh2 - mh + 0.5d) / mh2);
            tz0 = k == 0 ? 0.0d : ((md2 - md + 0.5d) / md2);

            tx1 = 1.0d - 0.5d / mw2;
            if (mw < bw) tx1 = 1.0d;
            if (imageW - i == bw) tx1 = 1.0d;

            ty1 = 1.0d - 0.5d / mh2;
            if (mh < bh) ty1 = 1.0d;
            if (imageH - j == bh) ty1 = 1.0d;

            tz1 = 1.0d - 0.5d / md2;
            if (md < bd) tz1 = 1.0d;
            if (imageD - k == bd) tz1 = 1.0d;

            bx0 = i == 0 ? 0.0d : (i + 0.5d) / (double) imageW;
            by0 = j == 0 ? 0.0d : (j + 0.5d) / (double) imageH;
            bz0 = k == 0 ? 0.0d : (k + 0.5d) / (double) imageD;

            bx1 = Math.min((i + bw - 0.5d) / (double) imageW, 1.0d);
            if (imageW - i == bw) bx1 = 1.0d;

            by1 = Math.min((j + bh - 0.5d) / (double) imageH, 1.0d);
            if (imageH - j == bh) by1 = 1.0d;

            bz1 = Math.min((k + bd - 0.5d) / (double) imageD, 1.0d);
            if (imageD - k == bd) bz1 = 1.0d;

            int x, y, z;
            x = i - (mw2 - mw);
            y = j - (mh2 - mh);
            z = k - (md2 - md);
            bricks.add(
                new Brick(
                    x, y, z, mw2, mh2, md2, 0, 0, tx0, ty0, tz0, tx1, ty1, tz1, bx0, by0, bz0, bx1,
                    by1, bz1));
          }
        }
      }

      Element fsnode = doc.createElement("Files");
      lvnode.appendChild(fsnode);

      stack = imp.getStack();

      int totalbricknum = nFrame * nCh * bricks.size();
      int curbricknum = 0;
      for (int f = 0; f < nFrame; f++) {
        for (int ch = 0; ch < nCh; ch++) {
          int sizelimit = bdsizelimit * 1024 * 1024;
          int bytecount = 0;
          int filecount = 0;
          int pd_bufsize = Math.max(sizelimit, bw * bh * bd * bdepth / 8);
          byte[] packed_data = new byte[pd_bufsize];
          String base_dataname =
              basename
                  + "_Lv"
                  + String.valueOf(l)
                  + "_Ch"
                  + String.valueOf(ch)
                  + "_Fr"
                  + String.valueOf(f);
          String current_dataname = base_dataname + "_data" + filecount;

          Brick b_first = bricks.get(0);
          if (b_first.z_ != 0) IJ.log("warning");
          int st_z = b_first.z_;
          int ed_z = b_first.z_ + b_first.d_;
          LinkedList<ImageProcessor> iplist = new LinkedList<ImageProcessor>();
          for (int s = st_z; s < ed_z; s++)
            iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));

          //					ImagePlus test;
          //					ImageStack tsst;
          //					test = NewImage.createByteImage("test", imageW, imageH, imageD,
          // NewImage.FILL_BLACK);
          //					tsst = test.getStack();
          for (int i = 0; i < bricks.size(); i++) {
            Brick b = bricks.get(i);

            if (ed_z > b.z_ || st_z < b.z_ + b.d_) {
              if (b.z_ > st_z) {
                for (int s = 0; s < b.z_ - st_z; s++) iplist.pollFirst();
                st_z = b.z_;
              } else if (b.z_ < st_z) {
                IJ.log("warning");
                for (int s = st_z - 1; s > b.z_; s--)
                  iplist.addFirst(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                st_z = b.z_;
              }

              if (b.z_ + b.d_ > ed_z) {
                for (int s = ed_z; s < b.z_ + b.d_; s++)
                  iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
                ed_z = b.z_ + b.d_;
              } else if (b.z_ + b.d_ < ed_z) {
                IJ.log("warning");
                for (int s = 0; s < ed_z - (b.z_ + b.d_); s++) iplist.pollLast();
                ed_z = b.z_ + b.d_;
              }
            } else {
              IJ.log("warning");
              iplist.clear();
              st_z = b.z_;
              ed_z = b.z_ + b.d_;
              for (int s = st_z; s < ed_z; s++)
                iplist.add(stack.getProcessor(imp.getStackIndex(ch + 1, s + 1, f + 1)));
            }

            if (iplist.size() != b.d_) {
              IJ.log("Stack Error");
              return;
            }

            //						int zz = st_z;

            int bsize = 0;
            byte[] bdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
            Iterator<ImageProcessor> ipite = iplist.iterator();
            while (ipite.hasNext()) {

              //							ImageProcessor tsip = tsst.getProcessor(zz+1);

              ImageProcessor ip = ipite.next();
              ip.setRoi(b.x_, b.y_, b.w_, b.h_);
              if (bdepth == 8) {
                byte[] data = (byte[]) ip.crop().getPixels();
                System.arraycopy(data, 0, bdata, bsize, data.length);
                bsize += data.length;
              } else if (bdepth == 16) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                short[] data = (short[]) ip.crop().getPixels();
                for (short e : data) buffer.putShort(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              } else if (bdepth == 32) {
                ByteBuffer buffer = ByteBuffer.allocate(b.w_ * b.h_ * bdepth / 8);
                buffer.order(ByteOrder.LITTLE_ENDIAN);
                float[] data = (float[]) ip.crop().getPixels();
                for (float e : data) buffer.putFloat(e);
                System.arraycopy(buffer.array(), 0, bdata, bsize, buffer.array().length);
                bsize += buffer.array().length;
              }
            }

            String filename =
                basename
                    + "_Lv"
                    + String.valueOf(l)
                    + "_Ch"
                    + String.valueOf(ch)
                    + "_Fr"
                    + String.valueOf(f)
                    + "_ID"
                    + String.valueOf(i);

            int offset = bytecount;
            int datasize = bdata.length;

            if (filetype == "RAW") {
              int dummy = -1;
              // do nothing
            }
            if (filetype == "JPEG" && bdepth == 8) {
              try {
                DataBufferByte db = new DataBufferByte(bdata, datasize);
                Raster raster = Raster.createPackedRaster(db, b.w_, b.h_ * b.d_, 8, null);
                BufferedImage img =
                    new BufferedImage(b.w_, b.h_ * b.d_, BufferedImage.TYPE_BYTE_GRAY);
                img.setData(raster);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
                String format = "jpg";
                Iterator<javax.imageio.ImageWriter> iter =
                    ImageIO.getImageWritersByFormatName("jpeg");
                javax.imageio.ImageWriter writer = iter.next();
                ImageWriteParam iwp = writer.getDefaultWriteParam();
                iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwp.setCompressionQuality((float) jpeg_quality * 0.01f);
                writer.setOutput(ios);
                writer.write(null, new IIOImage(img, null, null), iwp);
                // ImageIO.write(img, format, baos);
                bdata = baos.toByteArray();
                datasize = bdata.length;
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
            if (filetype == "ZLIB") {
              byte[] tmpdata = new byte[b.w_ * b.h_ * b.d_ * bdepth / 8];
              Deflater compresser = new Deflater();
              compresser.setInput(bdata);
              compresser.setLevel(Deflater.DEFAULT_COMPRESSION);
              compresser.setStrategy(Deflater.DEFAULT_STRATEGY);
              compresser.finish();
              datasize = compresser.deflate(tmpdata);
              bdata = tmpdata;
              compresser.end();
            }

            if (bytecount + datasize > sizelimit && bytecount > 0) {
              BufferedOutputStream fis = null;
              try {
                File file = new File(directory + current_dataname);
                fis = new BufferedOutputStream(new FileOutputStream(file));
                fis.write(packed_data, 0, bytecount);
              } catch (IOException e) {
                e.printStackTrace();
                return;
              } finally {
                try {
                  if (fis != null) fis.close();
                } catch (IOException e) {
                  e.printStackTrace();
                  return;
                }
              }
              filecount++;
              current_dataname = base_dataname + "_data" + filecount;
              bytecount = 0;
              offset = 0;
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            } else {
              System.arraycopy(bdata, 0, packed_data, bytecount, datasize);
              bytecount += datasize;
            }

            Element filenode = doc.createElement("File");
            filenode.setAttribute("filename", current_dataname);
            filenode.setAttribute("channel", String.valueOf(ch));
            filenode.setAttribute("frame", String.valueOf(f));
            filenode.setAttribute("brickID", String.valueOf(i));
            filenode.setAttribute("offset", String.valueOf(offset));
            filenode.setAttribute("datasize", String.valueOf(datasize));
            filenode.setAttribute("filetype", String.valueOf(filetype));

            fsnode.appendChild(filenode);

            curbricknum++;
            IJ.showProgress((double) (curbricknum) / (double) (totalbricknum));
          }
          if (bytecount > 0) {
            BufferedOutputStream fis = null;
            try {
              File file = new File(directory + current_dataname);
              fis = new BufferedOutputStream(new FileOutputStream(file));
              fis.write(packed_data, 0, bytecount);
            } catch (IOException e) {
              e.printStackTrace();
              return;
            } finally {
              try {
                if (fis != null) fis.close();
              } catch (IOException e) {
                e.printStackTrace();
                return;
              }
            }
          }
        }
      }

      for (int i = 0; i < bricks.size(); i++) {
        Brick b = bricks.get(i);
        Element bricknode = doc.createElement("Brick");
        bricknode.setAttribute("id", String.valueOf(i));
        bricknode.setAttribute("st_x", String.valueOf(b.x_));
        bricknode.setAttribute("st_y", String.valueOf(b.y_));
        bricknode.setAttribute("st_z", String.valueOf(b.z_));
        bricknode.setAttribute("width", String.valueOf(b.w_));
        bricknode.setAttribute("height", String.valueOf(b.h_));
        bricknode.setAttribute("depth", String.valueOf(b.d_));
        brksnode.appendChild(bricknode);

        Element tboxnode = doc.createElement("tbox");
        tboxnode.setAttribute("x0", String.valueOf(b.tx0_));
        tboxnode.setAttribute("y0", String.valueOf(b.ty0_));
        tboxnode.setAttribute("z0", String.valueOf(b.tz0_));
        tboxnode.setAttribute("x1", String.valueOf(b.tx1_));
        tboxnode.setAttribute("y1", String.valueOf(b.ty1_));
        tboxnode.setAttribute("z1", String.valueOf(b.tz1_));
        bricknode.appendChild(tboxnode);

        Element bboxnode = doc.createElement("bbox");
        bboxnode.setAttribute("x0", String.valueOf(b.bx0_));
        bboxnode.setAttribute("y0", String.valueOf(b.by0_));
        bboxnode.setAttribute("z0", String.valueOf(b.bz0_));
        bboxnode.setAttribute("x1", String.valueOf(b.bx1_));
        bboxnode.setAttribute("y1", String.valueOf(b.by1_));
        bboxnode.setAttribute("z1", String.valueOf(b.bz1_));
        bricknode.appendChild(bboxnode);
      }

      if (l < lv - 1) {
        imp = WindowManager.getImage(lvImgTitle.get(l + 1));
        int[] newdims = imp.getDimensions();
        imageW = newdims[0];
        imageH = newdims[1];
        imageD = newdims[3];
        xspc = orgxspc * ((double) orgW / (double) imageW);
        yspc = orgyspc * ((double) orgH / (double) imageH);
        zspc = orgzspc * ((double) orgD / (double) imageD);
        bdepth = imp.getBitDepth();
      }
    }

    File newXMLfile = new File(directory + basename + ".vvd");
    writeXML(newXMLfile, doc);

    for (int l = 1; l < lv; l++) {
      imp = WindowManager.getImage(lvImgTitle.get(l));
      imp.changes = false;
      imp.close();
    }
  }
 void appendCellToRow(Element tableRow, String content) {
   Element newCell = document.createElement("td");
   newCell.setTextContent(content);
   tableRow.appendChild(newCell);
 }
Beispiel #22
0
  public void CollectData(String link) {

    try {
      // Creating an empty XML Document

      DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
      Document doc = docBuilder.newDocument();
      int flag = 0;
      // create the root element and add it to the document
      Element movie = doc.createElement("movie");
      doc.appendChild(movie);
      movie.setAttribute("id", String.valueOf(n));
      n++;
      // create sub elements
      Element genres = doc.createElement("genres");
      Element actors = doc.createElement("actors");
      Element reviews = doc.createElement("reviews");

      URL movieUrl = new URL(link);
      URL reviewsURL = new URL(link + "reviews/#type=top_critics");
      BufferedWriter bw3 = new BufferedWriter(new FileWriter("movies.xml", true));
      int count = -1;
      String auth = "";
      BufferedReader br3 = new BufferedReader(new InputStreamReader(movieUrl.openStream()));
      String str2 = "";
      String info = "";
      while (null != (str2 = br3.readLine())) {
        // start reading the html document
        if (str2.isEmpty()) continue;
        if (count == 14) break;
        if (count == 12) {
          if (!str2.contains("<h3>Cast</h3>")) continue;
          else count++;
        }
        if (count == 13) {
          if (str2.contains(">ADVERTISEMENT</p>")) {
            count++;
            movie.appendChild(actors);
            continue;
          } else {
            if (str2.contains("itemprop=\"name\">")) {
              Element actor = doc.createElement("actor");
              actors.appendChild(actor);
              Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text());
              actor.appendChild(text);
            } else continue;
          }
        }

        if (count <= 11) {
          switch (count) {
            case -1:
              {
                if (!str2.contains("property=\"og:image\"")) continue;
                else {
                  Pattern image =
                      Pattern.compile("http://.*.jpg", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
                  Matcher match = image.matcher(str2);
                  while (match.find()) {

                    Element imageLink = doc.createElement("imageLink");
                    movie.appendChild(imageLink);
                    Text text = doc.createTextNode(match.group());
                    imageLink.appendChild(text);
                    count++;
                  }
                }
                break;
              }
            case 0:
              {
                if (str2.contains("<title>")) {

                  Element name = doc.createElement("name");
                  movie.appendChild(name);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(str2.toString().replace(" - Rotten Tomatoes", "")).text());
                  name.appendChild(text);
                  count++;
                }
                break;
              }
            case 1:
              {
                if (!str2.contains("itemprop=\"ratingValue\"")) break;
                else {
                  Element score = doc.createElement("score");
                  movie.appendChild(score);
                  Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text());
                  score.appendChild(text);
                  count++;
                }
                break;
              }
            case 2:
              {
                if (!str2.contains("itemprop=\"description\">")) continue;
                else count++;
                break;
              }
            case 3:
              {
                if (!str2.contains("itemprop=\"duration\"")) info = info.concat(str2);
                else {
                  Element MovieInfo = doc.createElement("MovieInfo");
                  movie.appendChild(MovieInfo);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  MovieInfo.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 4:
              {
                if (!str2.contains("itemprop=\"genre\"")) info = info.concat(str2);
                else {
                  Element duration = doc.createElement("duration");
                  movie.appendChild(duration);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  duration.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 5:
              {
                if (info.contains("itemprop=\"genre\"")) {
                  Element genre = doc.createElement("genre");
                  genres.appendChild(genre);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  genre.appendChild(text);
                  info = "";
                }
                if (str2.contains(">Directed By:<")) {
                  count++;
                  movie.appendChild(genres);
                  continue;
                } else {

                  if (str2.contains("itemprop=\"genre\"")) {
                    Element genre = doc.createElement("genre");
                    genres.appendChild(genre);
                    Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text());
                    genre.appendChild(text);
                  } else continue;
                }
                break;
              }
            case 6:
              {
                if (!str2.contains(">Written By:<")) {
                  if (str2.contains(">In Theaters:<")) {
                    Element director = doc.createElement("director");
                    movie.appendChild(director);
                    Text text =
                        doc.createTextNode(
                            Jsoup.parse(info.toString().replace("Directed By: ", "")).text());
                    director.appendChild(text);
                    info = str2;
                    count += 2;
                    break;
                  }
                  info = info.concat(str2);
                } else {
                  Element director = doc.createElement("director");
                  movie.appendChild(director);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("Directed By: ", "")).text());
                  director.appendChild(text);
                  info = "";
                  count++;
                }
                break;
              }
            case 7:
              {
                if (!str2.contains(">In Theaters:<")) {
                  if (str2.contains(">On DVD:<")) {
                    Element writer = doc.createElement("writer");
                    movie.appendChild(writer);
                    Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                    writer.appendChild(text);
                    info = str2;
                    count += 2;
                    break;
                  }
                  info = info.concat(str2);
                } else {
                  Element writer = doc.createElement("writer");
                  movie.appendChild(writer);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  writer.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 8:
              {
                if (!str2.contains(">On DVD:<")) info = info.concat(str2);
                else {
                  Element TheatreRelease = doc.createElement("TheatreRelease");
                  movie.appendChild(TheatreRelease);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("In Theaters:", "")).text());
                  TheatreRelease.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 9:
              {
                if (!str2.contains(">US Box Office:<")) {
                  if (str2.contains("itemprop=\"productionCompany\"")) {
                    Element DvdRelease = doc.createElement("DvdRelease");
                    movie.appendChild(DvdRelease);
                    Text text =
                        doc.createTextNode(
                            Jsoup.parse(info.toString().replace("On DVD:", "")).text());
                    DvdRelease.appendChild(text);
                    info = str2;
                    count += 2;
                    break;
                  }
                  info = info.concat(str2);
                } else {
                  Element DvdRelease = doc.createElement("DvdRelease");
                  movie.appendChild(DvdRelease);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("On DVD:", "")).text());
                  DvdRelease.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 10:
              {
                if (!str2.contains("itemprop=\"productionCompany\"")) info = info.concat(str2);
                else {
                  Element BOCollection = doc.createElement("BOCollection");
                  movie.appendChild(BOCollection);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("US Box Office:", "")).text());
                  BOCollection.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 11:
              {
                if (!str2.contains(">Official Site")) info = info.concat(str2);
                else {
                  Element Production = doc.createElement("Production");
                  movie.appendChild(Production);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  Production.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }

            default:
              break;
          }
        }
      }
      BufferedReader br4 = new BufferedReader(new InputStreamReader(reviewsURL.openStream()));
      String str3 = "";
      String info2 = "";
      int count2 = 0;
      while (null != (str3 = br4.readLine())) {
        if (count2 == 0) {

          if (!str3.contains("<div class=\"reviewsnippet\">")) continue;
          else count2++;
        }
        if (count2 == 1) {
          if (!str3.contains("<p class=\"small subtle\">")) info2 = info2.concat(str3);
          else {
            Element review = doc.createElement("review");
            reviews.appendChild(review);
            Text text = doc.createTextNode(Jsoup.parse(info2.toString()).text());
            review.appendChild(text);
            info2 = "";
            count2 = 0;
          }
        }
      }
      movie.appendChild(reviews);
      TransformerFactory transfac = TransformerFactory.newInstance();
      Transformer trans = transfac.newTransformer();
      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      trans.setOutputProperty(OutputKeys.INDENT, "yes");

      // create string from xml tree
      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);
      DOMSource source = new DOMSource(doc);
      trans.transform(source, result);
      String xmlString = sw.toString();
      bw3.write(xmlString);
      br3.close();
      br4.close();
      bw3.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Beispiel #23
0
  /**
   * Converts value object to XML representation.
   *
   * @return Element.
   */
  public Element toXml(Document doc) {
    Element root = doc.createElement("OrderAssoc");

    Element node;

    root.setAttribute("Id", String.valueOf(mOrderAssocId));

    node = doc.createElement("Order1Id");
    node.appendChild(doc.createTextNode(String.valueOf(mOrder1Id)));
    root.appendChild(node);

    node = doc.createElement("Order2Id");
    node.appendChild(doc.createTextNode(String.valueOf(mOrder2Id)));
    root.appendChild(node);

    node = doc.createElement("OrderAssocCd");
    node.appendChild(doc.createTextNode(String.valueOf(mOrderAssocCd)));
    root.appendChild(node);

    node = doc.createElement("OrderAssocStatusCd");
    node.appendChild(doc.createTextNode(String.valueOf(mOrderAssocStatusCd)));
    root.appendChild(node);

    node = doc.createElement("AddDate");
    node.appendChild(doc.createTextNode(String.valueOf(mAddDate)));
    root.appendChild(node);

    node = doc.createElement("AddBy");
    node.appendChild(doc.createTextNode(String.valueOf(mAddBy)));
    root.appendChild(node);

    node = doc.createElement("ModDate");
    node.appendChild(doc.createTextNode(String.valueOf(mModDate)));
    root.appendChild(node);

    node = doc.createElement("ModBy");
    node.appendChild(doc.createTextNode(String.valueOf(mModBy)));
    root.appendChild(node);

    node = doc.createElement("WorkOrderItemId");
    node.appendChild(doc.createTextNode(String.valueOf(mWorkOrderItemId)));
    root.appendChild(node);

    node = doc.createElement("ServiceTicketId");
    node.appendChild(doc.createTextNode(String.valueOf(mServiceTicketId)));
    root.appendChild(node);

    return root;
  }
  public boolean runTest(Test test) throws Exception {
    String filename = test.file.toString();
    if (this.verbose) {
      System.out.println(
          "Running "
              + filename
              + " against "
              + this.host
              + ":"
              + this.port
              + " with "
              + this.browser);
    }
    this.document = parseDocument(filename);

    if (this.baseUrl == null) {
      NodeList links = this.document.getElementsByTagName("link");
      if (links.getLength() != 0) {
        Element link = (Element) links.item(0);
        setBaseUrl(link.getAttribute("href"));
      }
    }
    if (this.verbose) {
      System.out.println("Base URL=" + this.baseUrl);
    }

    Node body = this.document.getElementsByTagName("body").item(0);
    Element resultContainer = document.createElement("div");
    resultContainer.setTextContent("Result: ");
    Element resultElt = document.createElement("span");
    resultElt.setAttribute("id", "result");
    resultElt.setIdAttribute("id", true);
    resultContainer.appendChild(resultElt);
    body.insertBefore(resultContainer, body.getFirstChild());

    Element executionLogContainer = document.createElement("div");
    executionLogContainer.setTextContent("Execution Log:");
    Element executionLog = document.createElement("div");
    executionLog.setAttribute("id", "log");
    executionLog.setIdAttribute("id", true);
    executionLog.setAttribute("style", "white-space: pre;");
    executionLogContainer.appendChild(executionLog);
    body.appendChild(executionLogContainer);

    NodeList tableRows = document.getElementsByTagName("tr");
    Element theadRow = (Element) tableRows.item(0);
    test.name = theadRow.getTextContent();
    appendCellToRow(theadRow, "Result");

    this.commandProcessor =
        new HtmlCommandProcessor(this.host, this.port, this.browser, this.baseUrl);
    String resultState;
    String resultLog;
    test.result = true;
    try {
      this.commandProcessor.start();
      test.commands = new Command[tableRows.getLength() - 1];
      for (int i = 1; i < tableRows.getLength(); i++) {
        Element stepRow = (Element) tableRows.item(i);
        Command command = executeStep(stepRow);
        appendCellToRow(stepRow, command.result);
        test.commands[i - 1] = command;
        if (command.error) {
          test.result = false;
        }
        if (command.failure) {
          test.result = false;
          // break;
        }
      }
      resultState = test.result ? "PASSED" : "FAILED";
      resultLog = (test.result ? "Test Complete" : "Error");
      this.commandProcessor.stop();
    } catch (Exception e) {
      test.result = false;
      resultState = "ERROR";
      resultLog = "Failed to initialize session\n" + e;
      e.printStackTrace();
    }
    document.getElementById("result").setTextContent(resultState);
    Element log = document.getElementById("log");
    log.setTextContent(log.getTextContent() + resultLog + "\n");
    return test.result;
  }
Beispiel #25
0
  /**
   * Converts value object to XML representation.
   *
   * @return Element.
   */
  public Element toXml(Document doc) {
    Element root = doc.createElement("NscUs");
    root.setAttribute("Id", String.valueOf(mUserName));

    Element node;

    node = doc.createElement("Password");
    node.appendChild(doc.createTextNode(String.valueOf(mPassword)));
    root.appendChild(node);

    node = doc.createElement("CustomerNumber");
    node.appendChild(doc.createTextNode(String.valueOf(mCustomerNumber)));
    root.appendChild(node);

    node = doc.createElement("ContactName");
    node.appendChild(doc.createTextNode(String.valueOf(mContactName)));
    root.appendChild(node);

    node = doc.createElement("EmailAddress");
    node.appendChild(doc.createTextNode(String.valueOf(mEmailAddress)));
    root.appendChild(node);

    node = doc.createElement("CatalogName");
    node.appendChild(doc.createTextNode(String.valueOf(mCatalogName)));
    root.appendChild(node);

    node = doc.createElement("LocationNumber");
    node.appendChild(doc.createTextNode(String.valueOf(mLocationNumber)));
    root.appendChild(node);

    node = doc.createElement("MemberNumber");
    node.appendChild(doc.createTextNode(String.valueOf(mMemberNumber)));
    root.appendChild(node);

    node = doc.createElement("FirstName");
    node.appendChild(doc.createTextNode(String.valueOf(mFirstName)));
    root.appendChild(node);

    node = doc.createElement("LastName");
    node.appendChild(doc.createTextNode(String.valueOf(mLastName)));
    root.appendChild(node);

    node = doc.createElement("UserId");
    node.appendChild(doc.createTextNode(String.valueOf(mUserId)));
    root.appendChild(node);

    node = doc.createElement("UserAction");
    node.appendChild(doc.createTextNode(String.valueOf(mUserAction)));
    root.appendChild(node);

    node = doc.createElement("StoreId");
    node.appendChild(doc.createTextNode(String.valueOf(mStoreId)));
    root.appendChild(node);

    node = doc.createElement("StoreAssocId");
    node.appendChild(doc.createTextNode(String.valueOf(mStoreAssocId)));
    root.appendChild(node);

    node = doc.createElement("StoreAssocAction");
    node.appendChild(doc.createTextNode(String.valueOf(mStoreAssocAction)));
    root.appendChild(node);

    node = doc.createElement("AccountId");
    node.appendChild(doc.createTextNode(String.valueOf(mAccountId)));
    root.appendChild(node);

    node = doc.createElement("AccountAssocId");
    node.appendChild(doc.createTextNode(String.valueOf(mAccountAssocId)));
    root.appendChild(node);

    node = doc.createElement("AccountAssocAction");
    node.appendChild(doc.createTextNode(String.valueOf(mAccountAssocAction)));
    root.appendChild(node);

    node = doc.createElement("SiteId");
    node.appendChild(doc.createTextNode(String.valueOf(mSiteId)));
    root.appendChild(node);

    node = doc.createElement("SiteAssocId");
    node.appendChild(doc.createTextNode(String.valueOf(mSiteAssocId)));
    root.appendChild(node);

    node = doc.createElement("SiteAssocAction");
    node.appendChild(doc.createTextNode(String.valueOf(mSiteAssocAction)));
    root.appendChild(node);

    node = doc.createElement("EmailId");
    node.appendChild(doc.createTextNode(String.valueOf(mEmailId)));
    root.appendChild(node);

    node = doc.createElement("EmailAction");
    node.appendChild(doc.createTextNode(String.valueOf(mEmailAction)));
    root.appendChild(node);

    node = doc.createElement("MemberId");
    node.appendChild(doc.createTextNode(String.valueOf(mMemberId)));
    root.appendChild(node);

    node = doc.createElement("CatalogId");
    node.appendChild(doc.createTextNode(String.valueOf(mCatalogId)));
    root.appendChild(node);

    return root;
  }
  /**
   * Edit the properties of a resource. The updates must refer to a Document containing a WebDAV
   * propertyupdates element as the document root.
   *
   * @param updates an XML Document containing propertyupdate elements
   * @return the result of making the updates describing the edits to be made.
   * @exception com.ibm.webdav.WebDAVException
   */
  public MultiStatus setProperties(Document propertyUpdates) throws WebDAVException {
    // create a MultiStatus to hold the results. It will hold a MethodResponse
    // for each update, and one for the method as a whole
    MultiStatus multiStatus = new MultiStatus();
    boolean errorsOccurred = false;

    // first, load the properties so they can be edited
    Document propertiesDocument = resource.loadProperties();
    Element properties = (Element) propertiesDocument.getDocumentElement();

    // be sure the updates have at least one update
    Element propertyupdate = (Element) propertyUpdates.getDocumentElement();
    String tagName = propertyupdate.getNamespaceURI() + propertyupdate.getLocalName();

    if (!tagName.equals("DAV:propertyupdate")) {
      throw new WebDAVException(
          WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "missing propertyupdate element");
    }

    NodeList updates = propertyupdate.getChildNodes();

    if (updates.getLength() == 0) {
      throw new WebDAVException(WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no updates in request");
    }

    Vector propsGood = new Vector(); // a list of properties that

    // were patched correctly or would have been if another
    // property hadn't gone bad.
    // apply the updates
    Node temp = null;

    for (int i = 0; i < updates.getLength(); i++) {
      temp = updates.item(i);

      // skip any ignorable TXText elements
      if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
        continue;
      }

      Element update = (Element) temp;
      int updateCommand = -1;
      tagName = update.getNamespaceURI() + update.getLocalName();

      if (tagName.equals("DAV:set")) {
        updateCommand = set;
      } else if (tagName.equals("DAV:remove")) {
        updateCommand = remove;
      } else {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY,
            update.getTagName() + " is not a valid property update request");
      }

      // iterate through the props in the set or remove element and update the
      // properties as directed
      Element prop = (Element) update.getElementsByTagNameNS("DAV:", "prop").item(0);

      if (prop == null) {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no propeprties in update request");
      }

      NodeList propsToUpdate = prop.getChildNodes();

      for (int j = 0; j < propsToUpdate.getLength(); j++) {
        temp = propsToUpdate.item(j);

        // skip any TXText elements??
        if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
          continue;
        }

        Element propToUpdate = (Element) temp;

        // find the property in the properties element
        Element property = null;
        PropertyName propertyName = new PropertyName(propToUpdate);

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

        boolean liveone = isLive(propertyName.asExpandedString());

        if (liveone) {
          errorsOccurred = true;

          PropertyResponse response = new PropertyResponse(resource.getURL().toString());
          response.addProperty(propertyName, propToUpdate, WebDAVStatus.SC_FORBIDDEN);
          multiStatus.addResponse(response);
        }

        // do the update
        if (updateCommand == set) {
          if (property != null) {
            try {
              properties.removeChild(property);
            } catch (DOMException exc) {
            }
          }

          if (!liveone) {
            // I don't think we're allowed to update live properties
            //    here.  Doing so effects the cache.  A case in
            //    point is the lockdiscoveryproperty.  properties
            //    is actually the properites cache "document" of this
            //    resource.  Even though we don't "save" the request
            //    if it includes live properties, we don't remove
            //    it from the cache after we'd set it here, so it
            //    can affect other queries. (jlc 991002)
            properties.appendChild(propertiesDocument.importNode(propToUpdate, true));

            propsGood.addElement(propToUpdate);
          }
        } else if (updateCommand == remove) {
          try {
            if (property != null) {
              properties.removeChild(property);
              propsGood.addElement(propToUpdate);
            }
          } catch (DOMException exc) {
          }
        }
      }
    }

    {
      Enumeration els = propsGood.elements();

      for (; els.hasMoreElements(); ) {
        Object ob1 = els.nextElement();
        Element elProp = (Element) ob1;
        PropertyName pn = new PropertyName(elProp);
        PropertyResponse response = new PropertyResponse(resource.getURL().toString());
        response.addProperty(
            pn,
            (Element) elProp.cloneNode(false),
            (errorsOccurred ? WebDAVStatus.SC_FAILED_DEPENDENCY : WebDAVStatus.SC_OK));

        // todo: add code for responsedescription
        multiStatus.addResponse(response);
      }
    }

    // write out the properties
    if (!errorsOccurred) {
      resource.saveProperties(propertiesDocument);
    }

    return multiStatus;
  }
  /**
   * Converts value object to XML representation.
   *
   * @return Element.
   */
  public Element toXml(Document doc) {
    Element root = doc.createElement("ProductViewDef");

    Element node;

    root.setAttribute("Id", String.valueOf(mProductViewDefId));

    node = doc.createElement("StatusCd");
    node.appendChild(doc.createTextNode(String.valueOf(mStatusCd)));
    root.appendChild(node);

    node = doc.createElement("AccountId");
    node.appendChild(doc.createTextNode(String.valueOf(mAccountId)));
    root.appendChild(node);

    node = doc.createElement("Attributename");
    node.appendChild(doc.createTextNode(String.valueOf(mAttributename)));
    root.appendChild(node);

    node = doc.createElement("SortOrder");
    node.appendChild(doc.createTextNode(String.valueOf(mSortOrder)));
    root.appendChild(node);

    node = doc.createElement("Width");
    node.appendChild(doc.createTextNode(String.valueOf(mWidth)));
    root.appendChild(node);

    node = doc.createElement("StyleClass");
    node.appendChild(doc.createTextNode(String.valueOf(mStyleClass)));
    root.appendChild(node);

    node = doc.createElement("ProductViewCd");
    node.appendChild(doc.createTextNode(String.valueOf(mProductViewCd)));
    root.appendChild(node);

    node = doc.createElement("AddDate");
    node.appendChild(doc.createTextNode(String.valueOf(mAddDate)));
    root.appendChild(node);

    node = doc.createElement("AddBy");
    node.appendChild(doc.createTextNode(String.valueOf(mAddBy)));
    root.appendChild(node);

    node = doc.createElement("ModDate");
    node.appendChild(doc.createTextNode(String.valueOf(mModDate)));
    root.appendChild(node);

    node = doc.createElement("ModBy");
    node.appendChild(doc.createTextNode(String.valueOf(mModBy)));
    root.appendChild(node);

    return root;
  }
  public void addPackageClass(PackageClass pClass) {

    Document doc;
    try {
      doc = getDocument();
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }

    String name = pClass.getName();

    // check if such class exists and remove duplicates
    Element rootEl = doc.getDocumentElement();
    NodeList classEls = rootEl.getElementsByTagName(EL_CLASS);
    for (int i = 0; i < classEls.getLength(); i++) {
      Element nameEl = getElementByName((Element) classEls.item(i), EL_NAME);
      if (name.equals(nameEl.getTextContent())) {
        rootEl.removeChild(classEls.item(i));
      }
    }

    Element classNode = doc.createElement(EL_CLASS);
    doc.getDocumentElement().appendChild(classNode);
    classNode.setAttribute(ATR_TYPE, PackageClass.ComponentType.SCHEME.getXmlName());
    classNode.setAttribute(ATR_STATIC, "false");

    Element className = doc.createElement(EL_NAME);
    className.setTextContent(name);
    classNode.appendChild(className);

    Element desrc = doc.createElement(EL_DESCRIPTION);
    desrc.setTextContent(pClass.getDescription());
    classNode.appendChild(desrc);

    Element icon = doc.createElement(EL_ICON);
    icon.setTextContent(pClass.getIcon());
    classNode.appendChild(icon);

    // graphics
    classNode.appendChild(generateGraphicsNode(doc, pClass.getGraphics()));

    // ports
    List<Port> ports = pClass.getPorts();
    if (!ports.isEmpty()) {
      Element portsEl = doc.createElement(EL_PORTS);
      classNode.appendChild(portsEl);

      for (Port port : ports) {
        portsEl.appendChild(generatePortNode(doc, port));
      }
    }

    // fields
    Collection<ClassField> fields = pClass.getFields();
    if (!fields.isEmpty()) {
      Element fieldsEl = doc.createElement(EL_FIELDS);
      classNode.appendChild(fieldsEl);

      for (ClassField cf : fields) {
        fieldsEl.appendChild(generateFieldNode(doc, cf));
      }
    }

    // write
    try {
      writeDocument(doc, new FileOutputStream(xmlFile));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
Beispiel #29
0
  /**
   * Converts value object to XML representation.
   *
   * @return Element.
   */
  public Element toXml(Document doc) {
    Element root = doc.createElement("Event");

    Element node;

    root.setAttribute("Id", String.valueOf(mEventId));

    node = doc.createElement("Type");
    node.appendChild(doc.createTextNode(String.valueOf(mType)));
    root.appendChild(node);

    node = doc.createElement("Status");
    node.appendChild(doc.createTextNode(String.valueOf(mStatus)));
    root.appendChild(node);

    node = doc.createElement("Cd");
    node.appendChild(doc.createTextNode(String.valueOf(mCd)));
    root.appendChild(node);

    node = doc.createElement("Attempt");
    node.appendChild(doc.createTextNode(String.valueOf(mAttempt)));
    root.appendChild(node);

    node = doc.createElement("AddDate");
    node.appendChild(doc.createTextNode(String.valueOf(mAddDate)));
    root.appendChild(node);

    node = doc.createElement("AddBy");
    node.appendChild(doc.createTextNode(String.valueOf(mAddBy)));
    root.appendChild(node);

    node = doc.createElement("ModDate");
    node.appendChild(doc.createTextNode(String.valueOf(mModDate)));
    root.appendChild(node);

    node = doc.createElement("ModBy");
    node.appendChild(doc.createTextNode(String.valueOf(mModBy)));
    root.appendChild(node);

    node = doc.createElement("EventPriority");
    node.appendChild(doc.createTextNode(String.valueOf(mEventPriority)));
    root.appendChild(node);

    node = doc.createElement("ProcessTime");
    node.appendChild(doc.createTextNode(String.valueOf(mProcessTime)));
    root.appendChild(node);

    return root;
  }