Example #1
0
  /**
   * This will invoke the <code>startElement</code> callback in the <code>ContentHandler</code>.
   *
   * @param element <code>Element</code> used in callbacks.
   * @param nsAtts <code>List</code> of namespaces to declare with the element or <code>null</code>.
   */
  private void startElement(Element element, Attributes nsAtts) throws JDOMException {
    String namespaceURI = element.getNamespaceURI();
    String localName = element.getName();
    String rawName = element.getQualifiedName();

    // Allocate attribute list.
    AttributesImpl atts = (nsAtts != null) ? new AttributesImpl(nsAtts) : new AttributesImpl();

    List attributes = element.getAttributes();
    Iterator i = attributes.iterator();
    while (i.hasNext()) {
      Attribute a = (Attribute) i.next();
      atts.addAttribute(
          a.getNamespaceURI(),
          a.getName(),
          a.getQualifiedName(),
          getAttributeTypeName(a.getAttributeType()),
          a.getValue());
    }

    try {
      contentHandler.startElement(namespaceURI, localName, rawName, atts);
    } catch (SAXException se) {
      throw new JDOMException("Exception in startElement", se);
    }
  }
Example #2
0
  /* (non-Javadoc)
   * @see org.alfresco.service.cmr.view.Exporter#startNode(org.alfresco.service.cmr.repository.NodeRef)
   */
  public void startNode(NodeRef nodeRef) {
    try {
      AttributesImpl attrs = new AttributesImpl();

      Path path = nodeService.getPath(nodeRef);
      if (path.size() > 1) {
        // a child name does not exist for root
        Path.ChildAssocElement pathElement = (Path.ChildAssocElement) path.last();
        QName childQName = pathElement.getRef().getQName();
        attrs.addAttribute(
            NamespaceService.REPOSITORY_VIEW_1_0_URI,
            CHILDNAME_LOCALNAME,
            CHILDNAME_QNAME.toPrefixString(),
            null,
            toPrefixString(childQName));
      }

      QName type = nodeService.getType(nodeRef);
      contentHandler.startElement(
          type.getNamespaceURI(), type.getLocalName(), toPrefixString(type), attrs);
    } catch (SAXException e) {
      throw new ExporterException(
          "Failed to process start node event - node ref " + nodeRef.toString(), e);
    }
  }
Example #3
0
  protected void toXml(Record record) throws SAXException {
    if (!MarcFactory.newInstance().validateRecord(record)) {
      throw new MarcException("Marc record didn't validate");
    }
    char temp[];
    AttributesImpl atts = new AttributesImpl();
    if (indent) handler.ignorableWhitespace("\n  ".toCharArray(), 0, 3);

    handler.startElement(Constants.MARCXML_NS_URI, RECORD, RECORD, atts);

    if (indent) handler.ignorableWhitespace("\n    ".toCharArray(), 0, 5);

    handler.startElement(Constants.MARCXML_NS_URI, LEADER, LEADER, atts);
    Leader leader = record.getLeader();
    temp = leader.toString().toCharArray();
    handler.characters(temp, 0, temp.length);
    handler.endElement(Constants.MARCXML_NS_URI, LEADER, LEADER);

    for (ControlField field : record.getControlFields()) {
      atts = new AttributesImpl();
      atts.addAttribute("", "tag", "tag", "CDATA", field.getTag());

      if (indent) handler.ignorableWhitespace("\n    ".toCharArray(), 0, 5);

      handler.startElement(Constants.MARCXML_NS_URI, CONTROL_FIELD, CONTROL_FIELD, atts);
      temp = getDataElement(field.getData());
      handler.characters(temp, 0, temp.length);
      handler.endElement(Constants.MARCXML_NS_URI, CONTROL_FIELD, CONTROL_FIELD);
    }

    for (DataField field : record.getDataFields()) {
      atts = new AttributesImpl();
      atts.addAttribute("", "tag", "tag", "CDATA", field.getTag());
      atts.addAttribute("", "ind1", "ind1", "CDATA", String.valueOf(field.getIndicator1()));
      atts.addAttribute("", "ind2", "ind2", "CDATA", String.valueOf(field.getIndicator2()));

      if (indent) handler.ignorableWhitespace("\n    ".toCharArray(), 0, 5);

      handler.startElement(Constants.MARCXML_NS_URI, DATA_FIELD, DATA_FIELD, atts);
      for (Subfield subfield : field.getSubfields()) {
        atts = new AttributesImpl();
        atts.addAttribute("", "code", "code", "CDATA", String.valueOf(subfield.getCode()));

        if (indent) handler.ignorableWhitespace("\n      ".toCharArray(), 0, 7);

        handler.startElement(Constants.MARCXML_NS_URI, SUBFIELD, SUBFIELD, atts);
        temp = getDataElement(subfield.getData());
        handler.characters(temp, 0, temp.length);
        handler.endElement(Constants.MARCXML_NS_URI, SUBFIELD, SUBFIELD);
      }

      if (indent) handler.ignorableWhitespace("\n    ".toCharArray(), 0, 5);

      handler.endElement(Constants.MARCXML_NS_URI, DATA_FIELD, DATA_FIELD);
    }

    if (indent) handler.ignorableWhitespace("\n  ".toCharArray(), 0, 3);

    handler.endElement(Constants.MARCXML_NS_URI, RECORD, RECORD);
  }
  /** Retrieve and remove the namespaces declarations from the list of attributes. */
  private Attributes extractNamespaces(Attributes attrs) throws SAXException {
    AttributesImpl attrsOnly;
    String rawName;
    int i;
    int indexColon;
    String prefix;
    int length;

    if (attrs == null) {
      return null;
    }
    length = attrs.getLength();
    attrsOnly = new AttributesImpl(attrs);

    for (i = length - 1; i >= 0; --i) {
      rawName = attrsOnly.getQName(i);

      // We have to exclude the namespaces declarations from the attributes
      // Append only when the feature http://xml.org/sax/features/namespace-prefixes"
      // is TRUE
      if (rawName.startsWith("xmlns")) {
        if (rawName.length() == 5) {
          startPrefixMapping("", attrs.getValue(i));
          attrsOnly.removeAttribute(i);
        } else if (rawName.charAt(5) == ':') {
          startPrefixMapping(rawName.substring(6), attrs.getValue(i));
          attrsOnly.removeAttribute(i);
        }
      }
    }
    return attrsOnly;
  }
Example #5
0
  private HashMap<String, String> SetHashSlotMention(
      HashMap<String, ArrayList<String>> fieldAnnotationList,
      HashMap<String, String> fieldTypeHasSlotId) {
    // look through annotation id
    HashMap<String, String> slotMap = new HashMap<String, String>();
    for (String type : fieldAnnotationList.keySet()) {

      //			ArrayList<HashMap<String, String>> annotSlotPairList = fieldAnnotationList.get(type);
      //			for(int i = 0; i < annotSlotPairList.size(); i++ ){
      atts.clear();
      String hasSlotMentionId = getKnowtatorArtificialId();
      fieldTypeHasSlotId.put(type, hasSlotMentionId);

      //				add slot mention id to hashtable
      //				HashMap<String,String> AnnotationSlotPair = fieldAnnotationList.get(type).get(i);
      //				String annotionid = AnnotationSlotPair.keySet().toString();
      //				AnnotationSlotPair.put(annotionid, hasSlotMentionId);

      //				fieldAnnotationList.get(type).set(i, AnnotationSlotPair);
      //				end of add slot mention id

      atts.addAttribute("", "", "id", "", hasSlotMentionId);
      try {
        hd.startElement("", "", "hasSlotMention", atts);
        hd.endElement("", "hasSlotMention", "");
        atts.clear();
      } catch (SAXException e) {
        e.printStackTrace();
      }
    }

    return slotMap;
  }
 @Override
 public void beginSubField(Field designator) {
   if (designator == null) {
     return;
   }
   try {
     AttributesImpl attrs = new AttributesImpl();
     String subfieldId = designator.subfieldId();
     if (subfieldId == null || subfieldId.length() == 0) {
       subfieldId = "a"; // fallback
     }
     attrs.addAttribute(nsUri, CODE, CODE, "CDATA", subfieldId);
     if (contentHandler != null) {
       contentHandler.startElement(nsUri, SUBFIELD, SUBFIELD, attrs);
     }
     if (listener != null) {
       listener.beginSubField(designator);
     }
   } catch (Exception ex) {
     if (fatalerrors) {
       throw new RuntimeException(ex);
     } else if (!silenterrors) {
       logger.warn(designator + ": " + ex.getMessage(), ex);
     }
   }
 }
Example #7
0
  /**
   * Build the SAX attributes object based upon Java's String map. This convenience method will
   * build, or add to an existing attributes object, the attributes detailed in the AttributeMap.
   *
   * @param elementNamespace SAX Helper class to keep track of namespaces able to determine the
   *     correct prefix for a given namespace URI.
   * @param attributes An existing SAX AttributesImpl object to add attributes to. If the value is
   *     null then a new attributes object will be created to house the attributes.
   * @param attributeMap A map of attributes and values.
   * @return
   */
  private AttributesImpl map2sax(Namespace elementNamespace, AttributeMap... attributeMaps) {

    AttributesImpl attributes = new AttributesImpl();
    for (AttributeMap attributeMap : attributeMaps) {
      boolean differentNamespaces = false;
      Namespace attributeNamespace = attributeMap.getNamespace();
      if (attributeNamespace != null && !(attributeNamespace.URI.equals(elementNamespace.URI))) {
        differentNamespaces = true;
      }

      // copy each one over.
      for (Map.Entry<String, String> attr : attributeMap.entrySet()) {
        if (attr.getValue() == null) {
          continue;
        }

        if (differentNamespaces) {
          attributes.addAttribute(
              attributeNamespace.URI,
              attr.getKey(),
              qName(attributeNamespace, attr.getKey()),
              "CDATA",
              attr.getValue());

        } else {
          attributes.addAttribute("", attr.getKey(), attr.getKey(), "CDATA", attr.getValue());
        }
      }
    }
    return attributes;
  }
Example #8
0
  /**
   * Appends a namespace declaration in the form of a xmlns attribute to an attribute list,
   * crerating this latter if needed.
   *
   * @param atts <code>AttributeImpl</code> where to add the attribute.
   * @param ns <code>Namespace</code> the namespace to declare.
   * @return <code>AttributeImpl</code> the updated attribute list.
   */
  private AttributesImpl addNsAttribute(AttributesImpl atts, Namespace ns) {
    if (this.declareNamespaces) {
      if (atts == null) {
        atts = new AttributesImpl();
      }

      String prefix = ns.getPrefix();
      if (prefix.equals("")) {
        atts.addAttribute(
            "", // namespace
            "", // local name
            "xmlns", // qualified name
            "CDATA", // type
            ns.getURI()); // value
      } else {
        atts.addAttribute(
            "", // namespace
            "", // local name
            "xmlns:" + ns.getPrefix(), // qualified name
            "CDATA", // type
            ns.getURI()); // value
      }
    }
    return atts;
  }
Example #9
0
 /** regenerate the stream from buffer */
 public void dump(XPathHandler next) {
   int last = byteBuffer.position();
   byteBuffer.position(0);
   while (byteBuffer.position() < last)
     try {
       switch (getByte()) {
         case 0:
           String uri = getString();
           String name = getString();
           String tag = getString();
           AttributesImpl atts = new AttributesImpl();
           int len = getShort();
           for (int i = 0; i < len; i++) atts.addAttribute("", "", getString(), "", getString());
           next.startElement(uri, name, tag, atts);
           break;
         case 1:
           next.endElement(getString(), getString(), getString());
           break;
         case 2:
           char[] text = getChars();
           next.characters(text, 0, text.length);
       }
     } catch (SAXException e) {
       throw new Error(e);
     }
   ;
   byteBuffer.clear();
 }
Example #10
0
    /** @param referencedEnvelope */
    private void handleEnvelope(
        ReferencedEnvelope referencedEnvelope,
        DimensionInfo timeInfo,
        ReaderDimensionsAccessor dimensions) {
      AttributesImpl attributes = new AttributesImpl();

      attributes.addAttribute(
          "", "srsName", "srsName", "", /* "WGS84(DD)" */ "urn:ogc:def:crs:OGC:1.3:CRS84");
      start("wcs:lonLatEnvelope", attributes);
      final StringBuffer minCP =
          new StringBuffer(Double.toString(referencedEnvelope.getMinX()))
              .append(" ")
              .append(referencedEnvelope.getMinY());
      final StringBuffer maxCP =
          new StringBuffer(Double.toString(referencedEnvelope.getMaxX()))
              .append(" ")
              .append(referencedEnvelope.getMaxY());

      element("gml:pos", minCP.toString());
      element("gml:pos", maxCP.toString());

      // are we going to report time?
      if (timeInfo != null && timeInfo.isEnabled()) {
        SimpleDateFormat timeFormat = dimensions.getTimeFormat();
        element("gml:timePosition", timeFormat.format(dimensions.getMinTime()));
        element("gml:timePosition", timeFormat.format(dimensions.getMaxTime()));
      }

      end("wcs:lonLatEnvelope");
    }
  protected void handleControlStart(
      String uri,
      String localname,
      String qName,
      Attributes attributes,
      String effectiveId,
      XFormsControl control)
      throws SAXException {

    final XFormsTriggerControl triggerControl = (XFormsTriggerControl) control;
    final XMLReceiver xmlReceiver = handlerContext.getController().getOutput();

    final AttributesImpl containerAttributes =
        getEmptyNestedControlAttributesMaybeWithId(
            uri, localname, attributes, effectiveId, triggerControl, true);

    // TODO: needs f:url-norewrite="true"?
    containerAttributes.addAttribute("", "href", "href", XMLReceiverHelper.CDATA, "#");

    // xhtml:a
    final String xhtmlPrefix = handlerContext.findXHTMLPrefix();
    final String aQName = XMLUtils.buildQName(xhtmlPrefix, ENCLOSING_ELEMENT_NAME);
    xmlReceiver.startElement(
        XMLConstants.XHTML_NAMESPACE_URI, ENCLOSING_ELEMENT_NAME, aQName, containerAttributes);
    {
      final String labelValue = getTriggerLabel(triggerControl);
      final boolean mustOutputHTMLFragment = triggerControl != null && triggerControl.isHTMLLabel();
      outputLabelText(xmlReceiver, triggerControl, labelValue, xhtmlPrefix, mustOutputHTMLFragment);
    }
    xmlReceiver.endElement(XMLConstants.XHTML_NAMESPACE_URI, ENCLOSING_ELEMENT_NAME, aQName);
  }
Example #12
0
    private void handleCapability(String capabilityName) {
      AttributesImpl attributes = new AttributesImpl();
      start(capabilityName);

      start("wcs:DCPType");
      start("wcs:HTTP");

      // String baseURL = RequestUtils.proxifiedBaseURL(request.getBaseUrl(),
      // wcs.getGeoServer().getGlobal().getProxyBaseUrl());
      String url = ResponseUtils.buildURL(request.getBaseUrl(), "wcs", null, URLType.SERVICE);
      attributes.addAttribute("", "xlink:href", "xlink:href", "", url + "?");

      start("wcs:Get");
      start("wcs:OnlineResource", attributes);
      end("wcs:OnlineResource");
      end("wcs:Get");
      end("wcs:HTTP");
      end("wcs:DCPType");

      attributes = new AttributesImpl();
      attributes.addAttribute("", "xlink:href", "xlink:href", "", url + "?");

      start("wcs:DCPType");
      start("wcs:HTTP");
      start("wcs:Post");
      start("wcs:OnlineResource", attributes);
      end("wcs:OnlineResource");
      end("wcs:Post");
      end("wcs:HTTP");
      end("wcs:DCPType");
      end(capabilityName);
    }
Example #13
0
    /**
     * Handles the service section of the capabilities document.
     *
     * @param config The OGC service to transform.
     * @throws SAXException For any errors.
     */
    private void handleService(boolean allSections) {
      AttributesImpl attributes = new AttributesImpl();
      if (!allSections) {
        attributes.addAttribute("", "version", "version", "", CUR_VERSION);
      }
      start("wcs:Service", attributes);
      handleMetadataLink(wcs.getMetadataLink());
      element("wcs:description", wcs.getAbstract());
      element("wcs:name", wcs.getName());
      element("wcs:label", wcs.getTitle());
      handleKeywords(wcs.getKeywords());
      handleContact();

      String fees = wcs.getFees();

      if ((fees == null) || "".equals(fees)) {
        fees = "NONE";
      }

      element("wcs:fees", fees);

      String accessConstraints = wcs.getAccessConstraints();

      if ((accessConstraints == null) || "".equals(accessConstraints)) {
        accessConstraints = "NONE";
      }

      element("wcs:accessConstraints", accessConstraints);
      end("wcs:Service");
    }
  private void emitValue(String value, ContentHandler contentHandler)
      throws RepositoryException, SAXException {

    // Per Section 7.2 Rule 11a of the JCR 2.0 spec, need to check invalid XML characters

    char[] chars = value.toCharArray();

    boolean allCharsAreValidXml = true;
    for (int i = 0; i < chars.length; i++) {
      if (!XmlCharacters.isValid(chars[i])) {
        allCharsAreValidXml = false;
        break;
      }
    }

    if (allCharsAreValidXml) {

      startElement(contentHandler, JcrSvLexicon.VALUE, null);
      contentHandler.characters(chars, 0, chars.length);
      endElement(contentHandler, JcrSvLexicon.VALUE);
    } else {
      AttributesImpl valueAtts = new AttributesImpl();
      valueAtts.addAttribute("xsi", "type", "xsi:type", "STRING", "xsd:base64Binary");

      startElement(contentHandler, JcrSvLexicon.VALUE, valueAtts);
      try {
        chars = Base64.encodeBytes(value.getBytes("UTF-8")).toCharArray();
      } catch (IOException ioe) {
        throw new RepositoryException(ioe);
      }
      contentHandler.characters(chars, 0, chars.length);
      endElement(contentHandler, JcrSvLexicon.VALUE);
    }
  }
 @Override
 public void beginRecord(String format, String type) {
   if (recordOpen) {
     return;
   }
   try {
     AttributesImpl attrs = new AttributesImpl();
     if (format != null && !"MARC21".equalsIgnoreCase(schema)) {
       attrs.addAttribute(nsUri, FORMAT, FORMAT, "CDATA", format);
     }
     if (type != null) {
       attrs.addAttribute(nsUri, TYPE, TYPE, "CDATA", type);
     }
     if (contentHandler != null) {
       contentHandler.startElement(nsUri, RECORD, RECORD, attrs);
     }
     if (listener != null) {
       listener.beginRecord(format, type);
     }
     this.recordOpen = true;
   } catch (Exception ex) {
     if (fatalerrors) {
       throw new RuntimeException(ex);
     } else if (!silenterrors) {
       logger.warn(designator + ": " + ex.getMessage(), ex);
     }
   }
 }
    @Override
    public void startElement(String uri, String localName, String qName, Attributes origAttrs)
        throws SAXException {
      // If we have an image tag, re-write the src attribute
      //  if required
      if ("img".equals(localName)) {
        AttributesImpl attrs;
        if (origAttrs instanceof AttributesImpl) {
          attrs = (AttributesImpl) origAttrs;
        } else {
          attrs = new AttributesImpl(origAttrs);
        }

        for (int i = 0; i < attrs.getLength(); i++) {
          if ("src".equals(attrs.getLocalName(i))) {
            String src = attrs.getValue(i);
            if (src.startsWith("embedded:")) {
              String newSrc = "";
              if (imageFolder != null) newSrc += imageFolder + "/";
              if (imagePrefix != null) newSrc += imagePrefix;
              newSrc += src.substring(src.indexOf(':') + 1);
              attrs.setValue(i, newSrc);
            }
          }
        }
        super.startElement(uri, localName, qName, attrs);
      } else {
        // For any other tag, pass through as-is
        super.startElement(uri, localName, qName, origAttrs);
      }
    }
 @Override
 public void endDataField(Field designator) {
   try {
     if (!datafieldOpen) {
       return;
     }
     if (listener != null) {
       listener.endDataField(designator);
     }
     if (designator != null) {
       String value = designator.data();
       if (value != null && !value.isEmpty()) {
         value = normalizeValue(value);
         // write data field per default into a subfield with code 'a'
         AttributesImpl attrs = new AttributesImpl();
         attrs.addAttribute(nsUri, CODE, CODE, "CDATA", "a");
         if (contentHandler != null) {
           contentHandler.startElement(nsUri, SUBFIELD, SUBFIELD, attrs);
           contentHandler.characters(value.toCharArray(), 0, value.length());
           contentHandler.endElement(nsUri, SUBFIELD, SUBFIELD);
         }
       }
     }
     if (contentHandler != null) {
       contentHandler.endElement(NS_URI, DATAFIELD, DATAFIELD);
     }
     datafieldOpen = false;
   } catch (Exception ex) {
     if (fatalerrors) {
       throw new RuntimeException(ex);
     } else if (!silenterrors) {
       logger.warn(designator + ": " + ex.getMessage(), ex);
     }
   }
 }
  /**
   * Build the SAX attributes object based upon Java's String map. This convenience method will
   * build, or add to an existing attributes object, the attributes detailed in the AttributeMap.
   *
   * @param namespaces SAX Helper class to keep track of namespaces able to determine the correct
   *     prefix for a given namespace URI.
   * @param attributes An existing SAX AttributesImpl object to add attributes too. If the value is
   *     null then a new attributes object will be created to house the attributes.
   * @param attributeMap A map of attributes and values.
   * @return
   */
  private AttributesImpl map2sax(
      Namespace elementNamespace,
      NamespaceSupport namespaces,
      AttributesImpl attributes,
      AttributeMap attributeMap) {

    if (attributes == null) attributes = new AttributesImpl();
    if (attributeMap != null) {
      // Figure out the namespace issue
      Namespace namespace = attributeMap.getNamespace();
      String URI;
      if (namespace != null) URI = namespace.URI;
      else URI = WingConstants.DRI.URI;

      String prefix = namespaces.getPrefix(URI);

      // copy each one over.
      for (String name : attributeMap.keySet()) {
        String value = attributeMap.get(name);
        if (value == null) continue;

        // If the indended namespace is the element's namespace then we
        // leave
        // off the namespace declaration because w3c say's its redundent
        // and breaks lots of xsl stuff.
        if (elementNamespace.URI.equals(URI))
          attributes.addAttribute("", name, name, "CDATA", value);
        else attributes.addAttribute(URI, name, qName(prefix, name), "CDATA", value);
      }
    }
    return attributes;
  }
Example #19
0
      public SiteMapFile(int count) throws IOException, SAXException {
        this.fileName = name + '_' + count + ".xml";
        writer = new FileWriter(new File(location, fileName));
        final StreamResult streamResult = new StreamResult(writer);

        try {
          transformerHandler = tf.newTransformerHandler();

          Transformer serializer = transformerHandler.getTransformer();

          serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //
          serializer.setOutputProperty(OutputKeys.METHOD, "xml");
          serializer.setOutputProperty(OutputKeys.INDENT, "yes");

          transformerHandler.setResult(streamResult);
          transformerHandler.startDocument();

          AttributesImpl schemaLocation = new AttributesImpl();

          transformerHandler.startPrefixMapping("xsd", XMLConstants.W3C_XML_SCHEMA_NS_URI);
          transformerHandler.startPrefixMapping("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);

          schemaLocation.addAttribute(
              XMLConstants.W3C_XML_SCHEMA_NS_URI,
              "schemaLocation",
              "xsi:schemaLocation",
              "CDATA",
              "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");

          transformerHandler.startElement(NS, "", "urlset", schemaLocation);
        } catch (TransformerConfigurationException e) {
          throw new RuntimeException(e);
        }
      }
Example #20
0
  public void testLi() throws Exception {
    char[] text;
    AttributesImpl attributes = new AttributesImpl();
    handler.startElement(null, null, "li", attributes);
    handler.characters(text = toCharArray("defaultListItem type li element."), 0, text.length);
    handler.endElement(null, null, "li");

    Li expected = new Li(null, null, "defaultListItem type li element.");
    Li actual = (Li) stack.peek();
    assertEquals(expected, actual);

    attributes = new AttributesImpl();
    attributes.addAttribute(null, null, "value", "String", "test value");
    handler.startElement(null, null, "li", attributes);
    handler.characters(text = toCharArray("valueOnlyListItem type li element."), 0, text.length);
    handler.endElement(null, null, "li");

    expected = new Li(null, "test value", "valueOnlyListItem type li element.");
    actual = (Li) stack.peek();
    assertEquals(expected, actual);

    attributes = new AttributesImpl();
    attributes.addAttribute(null, null, "name", "String", "condition");
    attributes.addAttribute(null, null, "value", "String", "test value");
    handler.startElement(null, null, "li", attributes);
    handler.characters(text = toCharArray("valueOnlyListItem type li element."), 0, text.length);
    handler.endElement(null, null, "li");

    expected = new Li("condition", "test value", "valueOnlyListItem type li element.");
    actual = (Li) stack.peek();
    assertEquals(expected, actual);
  }
Example #21
0
  private void setNSDeclAsAttr(Attributes atts) {
    Enumeration keys = nsMap.keys();
    if (keys.hasMoreElements()) {
      if (!(atts instanceof AttributesImpl)) {
        atts = new AttributesImpl(atts);
      }
      while (keys.hasMoreElements()) {
        String prefix = (String) keys.nextElement();
        String uri = (String) nsMap.get(prefix);
        if ("".equals(prefix)) {
          int index = atts.getIndex("xmlns");
          if (index == -1) {

            ((AttributesImpl) atts).addAttribute("", "", "xmlns", "CDATA", uri);
          } else {
            ((AttributesImpl) atts).setAttribute(index, "", "", "xmlns", "CDATA", uri);
          }
        } else {
          int index = atts.getIndex("xmlns:" + prefix);
          if (index == -1) {
            ((AttributesImpl) atts).addAttribute("", "", "xmlns:" + prefix, "CDATA", uri);
          } else {
            ((AttributesImpl) atts).setAttribute(index, "", "", "xmlns:" + prefix, "CDATA", uri);
          }
        }
      }
      nsMap.clear();
    }
  }
Example #22
0
  public void testTopic() throws Exception {
    char[] text;
    AttributesImpl attributes = new AttributesImpl();
    AttributesImpl topicAtts = new AttributesImpl();
    topicAtts.addAttribute(null, "name", null, "String", "TEST TOPIC");
    handler.startElement(null, null, "topic", topicAtts);
    handler.startElement(null, null, "category", attributes);
    handler.startElement(null, null, "pattern", attributes);
    handler.characters(text = toCharArray("HELLO ALICE I AM *"), 0, text.length);
    handler.endElement(null, null, "pattern");
    handler.startElement(null, null, "template", attributes);
    handler.characters(text = toCharArray("Hello "), 0, text.length);
    handler.startElement(null, null, "star", attributes);
    handler.characters(text = toCharArray(", nice to meet you."), 0, text.length);
    handler.endElement(null, null, "template");
    handler.endElement(null, null, "category");
    handler.endElement(null, null, "topic");

    Topic actual = (Topic) stack.peek();
    Topic expected =
        new Topic(
            "TEST TOPIC",
            new Category(
                new Pattern("HELLO ALICE I AM *"),
                new Template("Hello ", new Star(1), ", nice to meet you.")));
    assertEquals(expected, actual);
    assertEquals("TEST TOPIC", actual.getName());
  }
Example #23
0
  private void SetComplexSlotMention(
      HashMap<String, ArrayList<String>> fieldAnnotationList,
      HashMap<String, String> fieldTypeHasSlotIdMap) {
    for (String type : fieldAnnotationList.keySet()) {
      atts.clear();
      atts.addAttribute(
          "", "", "id", "", fieldTypeHasSlotIdMap.get(type)); // "i2b222009_Instance_990001"
      try {
        hd.startElement("", "", "complexSlotMention", atts);
        atts.clear();

        //				<mentionSlot id="m" />
        HashMap<String, String> maps = new HashMap<String, String>();
        maps.put("f", "fr");
        maps.put("do", "do");
        maps.put("mo", "manner");
        maps.put("r", "reason");
        maps.put("du", "du");
        maps.put("ossd", "other S/S/D");
        maps.put("ad", "adverse");

        String nmType = maps.get(type);
        atts.addAttribute("", "", "id", "", nmType);
        hd.startElement("", "", "mentionSlot", atts);
        hd.endElement("", "mentionSlotn", "");
        atts.clear();
        //
        SetComplexSlotMentionValue(fieldAnnotationList.get(type));

        hd.endElement("", "complexSlotMention", "");
      } catch (SAXException e) {
        e.printStackTrace();
      }
    }
  }
Example #24
0
  public void testAiml() throws Exception {
    char[] text;
    AttributesImpl attributes = new AttributesImpl();
    AttributesImpl aimlAtts = new AttributesImpl();
    aimlAtts.addAttribute(null, "version", null, "String", "1.0.1");
    handler.startElement(null, null, "aiml", aimlAtts);
    handler.startElement(null, null, "category", attributes);
    handler.startElement(null, null, "pattern", attributes);
    handler.characters(text = toCharArray("HELLO ALICE I AM *"), 0, text.length);
    handler.endElement(null, null, "pattern");
    handler.startElement(null, null, "template", attributes);
    handler.characters(text = toCharArray("Hello "), 0, text.length);
    handler.startElement(null, null, "star", attributes);
    handler.characters(text = toCharArray(", nice to meet you."), 0, text.length);
    handler.endElement(null, null, "template");
    handler.endElement(null, null, "category");
    handler.endElement(null, null, "aiml");

    Aiml actual = (Aiml) stack.peek();
    Aiml expected =
        new Aiml(
            new Category(
                new Pattern("HELLO ALICE I AM *"),
                new Template("Hello ", new Star(1), ", nice to meet you.")));
    assertEquals(expected, actual);
    assertEquals("1.0.1", actual.getVersion());
  }
  public void output(ContentHandler handler, Map svgContext) throws SAXException {
    if (dim.getDimensionBlock().length() > 0) {
      AttributesImpl attr = new AttributesImpl();
      StringBuffer buf = new StringBuffer();

      buf.append("translate(");
      buf.append((dim.getInsertPoint().getX()));
      buf.append(" ");
      buf.append((dim.getInsertPoint().getY()));
      buf.append(")");

      SVGUtils.addAttribute(attr, "transform", buf.toString());

      setCommonAttributes(attr, svgContext, dim);

      SVGUtils.startElement(handler, SVGConstants.SVG_GROUP, attr);
      attr = new AttributesImpl();
      attr.addAttribute(
          SVGConstants.XMLNS_NAMESPACE,
          "xlink",
          "xmlns:xlink",
          "CDATA",
          SVGConstants.XLINK_NAMESPACE);
      attr.addAttribute(
          SVGConstants.XLINK_NAMESPACE,
          "href",
          "xlink:href",
          "CDATA",
          "#" + SVGUtils.validateID(dim.getDimensionBlock()));

      SVGUtils.emptyElement(handler, SVGConstants.SVG_USE, attr);

      SVGUtils.endElement(handler, SVGConstants.SVG_GROUP);
    }
  }
  /**
   * Save the specified object.
   *
   * @param object The object to save.
   * @param hd The XML object.
   */
  public void save(final EncogPersistedObject object, final TransformerHandler hd) {
    try {
      final BasicNeuralDataSet set = (BasicNeuralDataSet) object;

      final AttributesImpl atts = EncogPersistedCollection.createAttributes(object);
      hd.startElement("", "", "BasicNeuralDataSet", atts);

      atts.clear();
      for (final NeuralDataPair pair : set) {
        hd.startElement("", "", this.pairXML, atts);
        hd.startElement("", "", this.inputXML, atts);
        for (int i = 0; i < pair.getInput().size(); i++) {
          hd.startElement("", "", this.valueXML, atts);
          final String data = "" + pair.getInput().getData(i);
          hd.characters(data.toCharArray(), 0, data.length());
          hd.endElement("", "", this.valueXML);
        }
        hd.endElement("", "", this.inputXML);
        hd.startElement("", "", this.idealXML, atts);
        for (int i = 0; i < pair.getIdeal().size(); i++) {
          hd.startElement("", "", this.valueXML, atts);
          final String data = "" + pair.getIdeal().getData(i);
          hd.characters(data.toCharArray(), 0, data.length());
          hd.endElement("", "", this.valueXML);
        }
        hd.endElement("", "", this.idealXML);
        hd.endElement("", "", this.pairXML);
      }

      hd.endElement("", "", "BasicNeuralDataSet");
    } catch (final SAXException e) {
      throw new NeuralNetworkError(e);
    }
  }
  private AttributesImpl createWorkflowAccessBinding(
      AttributesImpl atts, int workflow_id, int role_id) {
    String sql = null;
    String name = null;
    atts.clear();

    sql = "SELECT Name FROM AD_Workflow WHERE AD_Workflow_ID=?";
    name = DB.getSQLValueString(null, sql, workflow_id);
    atts.addAttribute("", "", "workflowname", "CDATA", name);

    sql = "SELECT Name FROM AD_Role WHERE AD_Role_ID=?";
    name = DB.getSQLValueString(null, sql, role_id);
    atts.addAttribute("", "", "rolename", "CDATA", name);

    sql =
        "SELECT isActive FROM AD_Workflow_Access WHERE AD_Workflow_ID="
            + workflow_id
            + " and AD_Role_ID=?";
    String TrueFalse = DB.getSQLValueString(null, sql, role_id);
    atts.addAttribute("", "", "isActive", "CDATA", TrueFalse);

    sql =
        "SELECT isReadWrite FROM AD_Workflow_Access WHERE AD_Workflow_ID="
            + workflow_id
            + " and AD_Role_ID=?";
    String isReadWrite = DB.getSQLValueString(null, sql, role_id);
    atts.addAttribute("", "", "isReadWrite", "CDATA", isReadWrite);

    return atts;
  }
  public void beginCollection() throws SAXException {
    if (contentHandler == null) {
      logger.warn("no content handler set");
      return;
    }
    contentHandler.startDocument();
    // write schema info
    AttributesImpl attrs = new AttributesImpl();
    if ("MARC21".equalsIgnoreCase(schema)) {
      this.nsUri = MARC21_NS_URI;
      attrs.addAttribute(
          XMLNS.NS_URI, XSI.NS_PREFIX, XMLNS.NS_PREFIX + ":" + XSI.NS_PREFIX, "CDATA", XSI.NS_URI);
      attrs.addAttribute(
          XSI.NS_URI,
          "schemaLocation",
          XSI.NS_PREFIX + ":schemaLocation",
          "CDATA",
          MARC21_NS_URI + " " + MARC21_SCHEMA);

    } else {
      this.nsUri = NS_URI;
      attrs.addAttribute(
          XMLNS.NS_URI, XSI.NS_PREFIX, XMLNS.NS_PREFIX + ":" + XSI.NS_PREFIX, "CDATA", XSI.NS_URI);
      attrs.addAttribute(
          XSI.NS_URI,
          "schemaLocation",
          XSI.NS_PREFIX + ":schemaLocation",
          "CDATA",
          NS_URI + " " + MARCXCHANGE_SCHEMA);
    }
    contentHandler.startPrefixMapping("", nsUri);
    contentHandler.startElement(nsUri, COLLECTION, COLLECTION, attrs);
  }
  public void endDocument() throws SAXException {

    outputFirstElementIfNeeded();

    // Output global properties
    if (properties.size() > 0) {
      final AttributesImpl newAttributes = new AttributesImpl();
      for (final Map.Entry<String, String> currentEntry : properties.entrySet()) {
        final String propertyName = currentEntry.getKey();
        newAttributes.addAttribute(
            XFormsConstants.XXFORMS_NAMESPACE_URI,
            propertyName,
            "xxforms:" + propertyName,
            ContentHandlerHelper.CDATA,
            currentEntry.getValue());
      }

      super.startPrefixMapping("xxforms", XFormsConstants.XXFORMS_NAMESPACE_URI);
      super.startElement("", "properties", "properties", newAttributes);
      super.endElement("", "properties", "properties");
      super.endPrefixMapping("xxforms");
    }

    super.endElement("", "static-state", "static-state");
    super.endDocument();
  }
  private static void serializeEntry(TransformerHandler hd, Entry entry) throws SAXException {

    AttributesImpl entryAttributes = new AttributesImpl();

    for (Iterator<String> it = entry.getAttributes().iterator(); it.hasNext(); ) {
      String key = it.next();

      entryAttributes.addAttribute("", "", key, "", entry.getAttributes().getValue(key));
    }

    hd.startElement("", "", ENTRY_ELEMENT, entryAttributes);

    StringList tokens = entry.getTokens();

    for (Iterator<String> it = tokens.iterator(); it.hasNext(); ) {

      hd.startElement("", "", TOKEN_ELEMENT, new AttributesImpl());

      String token = it.next();

      hd.characters(token.toCharArray(), 0, token.length());

      hd.endElement("", "", TOKEN_ELEMENT);
    }

    hd.endElement("", "", ENTRY_ELEMENT);
  }