Esempio n. 1
0
  public InputStream addAtomInlinecount(final InputStream feed, final int count) throws Exception {
    final XMLEventReader reader = getEventReader(feed);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    try {

      final XMLElement feedElement =
          extractElement(reader, writer, Collections.<String>singletonList("feed"), 0, 1, 1)
              .getValue();

      writer.add(feedElement.getStart());
      addAtomElement(
          IOUtils.toInputStream(String.format("<m:count>%d</m:count>", count), Constants.ENCODING),
          writer);
      writer.add(feedElement.getContentReader());
      writer.add(feedElement.getEnd());

      while (reader.hasNext()) {
        writer.add(reader.nextEvent());
      }

    } finally {
      writer.flush();
      writer.close();
      reader.close();
      IOUtils.closeQuietly(feed);
    }

    return new ByteArrayInputStream(bos.toByteArray());
  }
Esempio n. 2
0
  @Override
  public InputStream addEditLink(final InputStream content, final String title, final String href)
      throws Exception {

    final ByteArrayOutputStream copy = new ByteArrayOutputStream();
    IOUtils.copy(content, copy);
    IOUtils.closeQuietly(content);

    XMLEventReader reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLEventWriter writer = getEventWriter(bos);

    final String editLinkElement =
        String.format("<link rel=\"edit\" title=\"%s\" href=\"%s\" />", title, href);

    try {
      // check edit link existence
      extractElement(
          reader,
          writer,
          Collections.<String>singletonList(Constants.get(ConstantKey.LINK)),
          Collections.<Map.Entry<String, String>>singletonList(
              new AbstractMap.SimpleEntry<String, String>("rel", "edit")),
          false,
          0,
          -1,
          -1);

      addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer);
      writer.add(reader);

    } catch (Exception e) {
      reader.close();
      reader = getEventReader(new ByteArrayInputStream(copy.toByteArray()));

      bos = new ByteArrayOutputStream();
      writer = getEventWriter(bos);

      final XMLElement entryElement =
          extractElement(reader, writer, Collections.<String>singletonList("entry"), 0, 1, 1)
              .getValue();

      writer.add(entryElement.getStart());

      addAtomElement(IOUtils.toInputStream(editLinkElement, Constants.ENCODING), writer);

      writer.add(entryElement.getContentReader());
      writer.add(entryElement.getEnd());

      writer.add(reader);

      writer.flush();
      writer.close();
    } finally {
      reader.close();
    }

    return new ByteArrayInputStream(bos.toByteArray());
  }
Esempio n. 3
0
  public XMLElement getXmlElement(final StartElement start, final XMLEventReader reader)
      throws Exception {

    final XMLElement res = new XMLElement();
    res.setStart(start);

    final Charset encoding = Charset.forName(org.apache.olingo.commons.api.Constants.UTF8);
    final ByteArrayOutputStream content = new ByteArrayOutputStream();
    final OutputStreamWriter writer = new OutputStreamWriter(content, encoding);

    int depth = 1;

    while (reader.hasNext() && depth > 0) {
      final XMLEvent event = reader.nextEvent();

      if (event.getEventType() == XMLStreamConstants.START_ELEMENT) {
        depth++;
      } else if (event.getEventType() == XMLStreamConstants.END_ELEMENT) {
        depth--;
      }

      if (depth == 0) {
        res.setEnd(event.asEndElement());
      } else {
        event.writeAsEncodedUnicode(writer);
      }
    }

    writer.flush();
    writer.close();

    res.setContent(new ByteArrayInputStream(content.toByteArray()));

    return res;
  }
Esempio n. 4
0
	public XMLElement saveSelf () throws XMLCannotSaveException
	{ 	XMLElement result=super.saveSelf();
		result.setName(shortXMLName);
		result.addAttribute(new XMLAttribute ("random-chance",random_chance));
		result.addAttribute(new XMLAttribute ("gamma",gamma));
	  	return result;
	}
Esempio n. 5
0
  /**
   * This method is called when a PCDATA element is encountered. A Java reader is supplied from
   * which you can read the data. The reader will only read the data of the element. You don't need
   * to check for boundaries. If you don't read the full element, the rest of the data is skipped.
   * You also don't have to care about entities; they are resolved by the parser.
   *
   * @param reader the Java reader from which you can retrieve the data
   * @param systemID the system ID of the XML data source
   * @param lineNr the line in the source where the element starts
   * @throws java.lang.Exception If an exception occurred while processing the event.
   */
  public void addPCData(Reader reader, String systemID, int lineNr) throws Exception {
    int bufSize = 2048;
    int sizeRead = 0;
    StringBuffer str = new StringBuffer(bufSize);
    char[] buf = new char[bufSize];

    for (; ; ) {
      if (sizeRead >= bufSize) {
        bufSize *= 2;
        str.ensureCapacity(bufSize);
      }

      int size = reader.read(buf);

      if (size < 0) {
        break;
      }

      str.append(buf, 0, size);
      sizeRead += size;
    }

    XMLElement elt = new XMLElement(null, systemID, lineNr);
    elt.setContent(str.toString());

    if (!this.stack.empty()) {
      XMLElement top = (XMLElement) this.stack.peek();
      top.addChild(elt);
    }
  }
 /**
  * Helper class to write an person attribute if needed
  *
  * @param name name of the attribute
  * @param element element that the attribute will be added to
  * @param rs ResultSet than includes the values of the attribute
  * @throws SQLException
  * @throws Exception
  */
 private static void writeMovieAtt(String name, XMLElement element, ResultSet rs)
     throws SQLException, Exception {
   if (rs.next()) {
     element.addAttribute(name, "M" + rs.getString(1));
     while (rs.next()) {
       element.appendAttribute(name, "M" + rs.getString(1));
     }
   }
 }
Esempio n. 7
0
 public void load(XMLElement myElement, XMLLoader loader)
     throws XMLTreeException, IOException, XMLInvalidInputException {
   super.load(myElement, loader);
   gamma = myElement.getAttribute("gamma").getFloatValue();
   random_chance = myElement.getAttribute("random-chance").getFloatValue();
   q_table = (float[][][][]) XMLArray.loadArray(this, loader);
   // v_table=(float[][][])XMLArray.loadArray(this,loader);
   count = (Vector) XMLArray.loadArray(this, loader, this);
   // p_table=(Vector)XMLArray.loadArray(this,loader,this);
 }
Esempio n. 8
0
  /**
   * This method is called when a new attribute of an XML element is encountered.
   *
   * @param key the key (name) of the attribute
   * @param nsPrefix the prefix used to identify the namespace
   * @param nsSystemID the system ID associated with the namespace
   * @param value the value of the attribute
   * @param type the type of the attribute ("CDATA" if unknown)
   * @throws java.lang.Exception If an exception occurred while processing the event.
   */
  public void addAttribute(
      String key, String nsPrefix, String nsSystemID, String value, String type) throws Exception {
    XMLElement top = (XMLElement) this.stack.peek();

    if (top.hasAttribute(key)) {
      throw new XMLParseException(
          top.getSystemID(), top.getLineNr(), "Duplicate attribute: " + key);
    }

    top.setAttribute(key, value);
  }
Esempio n. 9
0
  /**
   * This method is called when a new XML element is encountered.
   *
   * @see #endElement
   * @param name the name of the element
   * @param nsPrefix the prefix used to identify the namespace
   * @param nsSystemID the system ID associated with the namespace
   * @param systemID the system ID of the XML data source
   * @param lineNr the line in the source where the element starts
   */
  public void startElement(
      String name, String nsPrefix, String nsSystemID, String systemID, int lineNr) {
    XMLElement elt = new XMLElement(name, systemID, lineNr);

    if (this.stack.empty()) {
      this.root = elt;
    } else {
      XMLElement top = (XMLElement) this.stack.peek();
      top.addChild(elt);
    }

    this.stack.push(elt);
  }
Esempio n. 10
0
  @Override
  protected InputStream replaceLink(
      final InputStream toBeChanged, final String linkName, final InputStream replacement)
      throws Exception {
    final XMLEventReader reader = getEventReader(toBeChanged);

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final XMLEventWriter writer = getEventWriter(bos);

    final XMLEventFactory eventFactory = XMLEventFactory.newInstance();
    XMLEvent newLine = eventFactory.createSpace("\n");

    try {
      final XMLElement linkElement =
          extractElement(
                  reader,
                  writer,
                  Collections.<String>singletonList(Constants.get(ConstantKey.LINK)),
                  Collections.<Map.Entry<String, String>>singletonList(
                      new SimpleEntry<String, String>("title", linkName)),
                  false,
                  0,
                  -1,
                  -1)
              .getValue();
      writer.add(linkElement.getStart());

      // ------------------------------------------
      // write inline ...
      // ------------------------------------------
      writer.add(newLine);
      writer.add(eventFactory.createStartElement("m", null, "inline"));

      addAtomElement(replacement, writer);

      writer.add(eventFactory.createEndElement("m", null, "inline"));
      writer.add(newLine);
      // ------------------------------------------

      writer.add(linkElement.getEnd());

      writer.add(reader);
      writer.flush();
      writer.close();
    } finally {
      reader.close();
      IOUtils.closeQuietly(toBeChanged);
    }

    return new ByteArrayInputStream(bos.toByteArray());
  }
Esempio n. 11
0
  /**
   * End of an element.
   *
   * @param namespaceURI : element namespace
   * @param localName : local name
   * @param qName : qualified name
   * @throws org.xml.sax.SAXException : occurs when the element is malformed
   * @see org.xml.sax.ContentHandler#endElement(String, String, String)
   */
  public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    // Get the last element of the list
    XMLElement lastElement = removeLastElement();

    // The name is consistent
    // Add this element last element with if it is not the root
    if (m_elements.length != 0) {
      XMLElement newQueue = m_elements[m_elements.length - 1];
      newQueue.addElement(lastElement);
    } else {
      // It is the last element
      addElement(lastElement);
    }
  }
Esempio n. 12
0
  public static void main(String args[]) throws Exception {
    if (args.length == 0) {
      System.err.println("Usage: java DumpXML file.xml");
      Runtime.getRuntime().exit(1);
    }

    IXMLParser parser = XMLParserFactory.createDefaultXMLParser();
    IXMLReader reader = StdXMLReader.fileReader(args[0]);
    parser.setReader(reader);
    XMLElement xml = (XMLElement) parser.parse();

    Properties prop = xml.getAttributes();
    prop.list(System.out);
  }
Esempio n. 13
0
  /**
   * Called by the XML implementation to signal the end of an XML entity.
   *
   * @param e The XML entity that ends.
   * @throws SAXException on any error
   */
  public void handleEndElement(XMLElement e) throws SAXException {

    try {
      switch (tokens.toToken(e.getName(), false)) {
        case TodoTokenTable.TOKEN_TO_DO:
        case TodoTokenTable.TOKEN_RESOLVEDCRITICS:
        case TodoTokenTable.TOKEN_TO_DO_LIST:
          // NOP
          break;

        case TodoTokenTable.TOKEN_TO_DO_ITEM:
          handleTodoItemEnd(e);
          break;

        case TodoTokenTable.TOKEN_HEADLINE:
          handleHeadline(e);
          break;

        case TodoTokenTable.TOKEN_DESCRIPTION:
          handleDescription(e);
          break;

        case TodoTokenTable.TOKEN_PRIORITY:
          handlePriority(e);
          break;

        case TodoTokenTable.TOKEN_MOREINFOURL:
          handleMoreInfoURL(e);
          break;

        case TodoTokenTable.TOKEN_ISSUE:
          handleIssueEnd(e);
          break;

        case TodoTokenTable.TOKEN_POSTER:
          handlePoster(e);
          break;

        case TodoTokenTable.TOKEN_OFFENDER:
          handleOffender(e);
          break;

        default:
          LOG.log(Level.WARNING, "WARNING: unknown end tag:" + e.getName());
          break;
      }
    } catch (Exception ex) {
      throw new SAXException(ex);
    }
  }
Esempio n. 14
0
  public static void main(String args[]) throws Exception {
    if (args.length == 0) {
      System.err.println("Usage: java DumpXML file.xml");
      Runtime.getRuntime().exit(1);
    }

    IXMLParser parser = XMLParserFactory.createDefaultXMLParser();
    IXMLReader reader = StdXMLReader.fileReader(args[0]);
    parser.setReader(reader);
    XMLElement xml = (XMLElement) parser.parse();

    xml.addChild(null);
    (new XMLWriter(System.out)).write(xml);
  }
Esempio n. 15
0
		public XMLElement saveSelf () throws XMLCannotSaveException
		{ 	XMLElement result=new XMLElement("pktlval");
			result.addAttribute(new XMLAttribute("tl-id",tl.getId()));
			result.addAttribute(new XMLAttribute("pos",pos));
			result.addAttribute(new	XMLAttribute("destination",destination.getId()));
			result.addAttribute(new XMLAttribute("light",light));
			result.addAttribute(new XMLAttribute("newtl-id",tl_new.getId()));
			result.addAttribute(new XMLAttribute("new-pos",pos_new));
			result.addAttribute(new XMLAttribute("value",value));
			result.addAttribute(new XMLAttribute("ktl",Ktl));
	  		return result;
		}
 private void parseProtocolElement(
     XMLExtendedStreamReader reader, PathAddress address, Map<PathAddress, ModelNode> operations)
     throws XMLStreamException {
   XMLElement element = XMLElement.forName(reader.getLocalName());
   switch (element) {
     case PROPERTY:
       {
         this.parseProperty(reader, address, operations);
         break;
       }
     case DEFAULT_THREAD_POOL:
       parseThreadPool(ThreadPoolResourceDefinition.DEFAULT, reader, address, operations);
       break;
     case INTERNAL_THREAD_POOL:
       parseThreadPool(ThreadPoolResourceDefinition.INTERNAL, reader, address, operations);
       break;
     case OOB_THREAD_POOL:
       parseThreadPool(ThreadPoolResourceDefinition.OOB, reader, address, operations);
       break;
     case TIMER_THREAD_POOL:
       parseThreadPool(ThreadPoolResourceDefinition.TIMER, reader, address, operations);
       break;
     default:
       {
         throw ParseUtils.unexpectedElement(reader);
       }
   }
 }
Esempio n. 17
0
  public void fromXML(XMLElement inXML) {
    String[] infoTags = getTags();
    Iterator<XMLElement> infoFields = inXML.getChildren();

    while (infoFields.hasNext()) {
      XMLElement fieldStep = infoFields.next();
      String curField = fieldStep.getTagName();

      for (int i = 0; i < infoTags.length; i++) {
        if (infoTags[i].equals(curField)) {

          handleTag(i, fieldStep);
          break;
        }
      }
    }
  }
Esempio n. 18
0
		public void load (XMLElement myElement,XMLLoader loader) throws XMLTreeException,IOException,XMLInvalidInputException
		{	pos=myElement.getAttribute("pos").getIntValue();
		   	loadData.oldTlId=myElement.getAttribute("tl-id").getIntValue();
			loadData.destNodeId=myElement.getAttribute("destination").getIntValue();
		   	light=myElement.getAttribute("light").getBoolValue();
			loadData.newTlId=myElement.getAttribute("newtl-id").getIntValue();
			pos_new=myElement.getAttribute("new-pos").getIntValue();
			Ktl=myElement.getAttribute("ktl").getIntValue();
			value=myElement.getAttribute("value").getFloatValue(); 
		}
Esempio n. 19
0
 public void load(XMLElement myElement, XMLLoader loader)
     throws XMLTreeException, IOException, XMLInvalidInputException {
   super.load(myElement, loader);
   width = myElement.getAttribute("width").getIntValue();
   alphaRoads = (Road[]) XMLArray.loadArray(this, loader);
   loadData.roads = (int[]) XMLArray.loadArray(this, loader);
   loadData.signconfigs = (int[][]) XMLArray.loadArray(this, loader);
   loadData.signs = (int[]) XMLArray.loadArray(this, loader);
 }
Esempio n. 20
0
  /**
   * This method is called when the end of an XML elemnt is encountered.
   *
   * @see #startElement
   * @param name the name of the element
   * @param nsPrefix the prefix used to identify the namespace
   * @param nsSystemID the system ID associated with the namespace
   */
  public void endElement(String name, String nsPrefix, String nsSystemID) {
    XMLElement elt = (XMLElement) this.stack.pop();

    if (elt.getChildrenCount() == 1) {
      XMLElement child = elt.getChildAtIndex(0);

      if (child.getName() == null) {
        elt.setContent(child.getContent());
        elt.removeChildAtIndex(0);
      }
    }
  }
  private static String writeOscarsXML(Connection db) throws Exception {

    /*Create and open new oscars.xml file*/
    PrintStream oscarFile = new PrintStream("oscars.XML");
    oscarFile.println("<?xml version=\"1.0\"?>");
    oscarFile.println("<oscars>");

    /* Get oscars */
    Statement stmt = db.createStatement();
    ResultSet results = stmt.executeQuery("SELECT * FROM Oscar;");
    ResultSetMetaData rsmd = results.getMetaData();

    /* Create oscar XMLElements */
    while (results.next()) {
      XMLElement oscar = new XMLElement("oscar", null, false, 1);
      String oscarID;
      if (results.getString(2) == null) {
        oscarID = "O" + results.getString(4) + "0000000";
      } else {
        oscarID = "O" + results.getString(4) + results.getString(2);
      }
      oscar.addAttribute("id", oscarID);

      ArrayList<XMLElement> children = new ArrayList<XMLElement>();
      /* Create children elements if needed */
      for (int i = 3; i < 5; i++) {
        if (results.getString(i) != null) {
          XMLElement child = new XMLElement(rsmd.getColumnLabel(i), results.getString(i), false, 2);
          children.add(child);
        }
      }

      /*Add movie Attribute*/
      oscar.addAttribute("movie_id", "M" + results.getString(1));

      /*Add actor Attribute */
      if (results.getString(2) != null) {
        oscar.addAttribute("person_id", "P" + results.getString(2));
      }

      /*write oscar element and it's children to the file*/
      oscarFile.println(oscar.getOpenTag());
      for (XMLElement child : children) {
        oscarFile.println(child.inlineElement());
      }
      oscarFile.println(oscar.getCloseTag());
    }
    oscarFile.println("</oscars>");

    oscarFile.close();

    return "oscar.xml has been written";
  }
Esempio n. 22
0
  /**
   * Called by the XML implementation to signal the start of an XML entity.
   *
   * @param e The entity being started.
   */
  public void handleStartElement(XMLElement e) {
    // cat.debug("NOTE: TodoParser handleStartTag:" + e.getName());

    try {
      switch (tokens.toToken(e.getName(), true)) {
        case TodoTokenTable.TOKEN_HEADLINE:
        case TodoTokenTable.TOKEN_DESCRIPTION:
        case TodoTokenTable.TOKEN_PRIORITY:
        case TodoTokenTable.TOKEN_MOREINFOURL:
        case TodoTokenTable.TOKEN_POSTER:
        case TodoTokenTable.TOKEN_OFFENDER:
          // NOP
          break;

        case TodoTokenTable.TOKEN_TO_DO:
          handleTodo(e);
          break;

        case TodoTokenTable.TOKEN_TO_DO_LIST:
          handleTodoList(e);
          break;

        case TodoTokenTable.TOKEN_TO_DO_ITEM:
          handleTodoItemStart(e);
          break;

        case TodoTokenTable.TOKEN_RESOLVEDCRITICS:
          handleResolvedCritics(e);
          break;

        case TodoTokenTable.TOKEN_ISSUE:
          handleIssueStart(e);
          break;

        default:
          LOG.log(Level.WARNING, "WARNING: unknown tag:" + e.getName());
          break;
      }
    } catch (Exception ex) {
      LOG.log(Level.SEVERE, "Exception in startelement", ex);
    }
  }
Esempio n. 23
0
  /**
   * Start an element.
   *
   * @param namespaceURI : element namespace.
   * @param localName : local element.
   * @param qName : qualified name.
   * @param atts : attribute
   * @throws org.xml.sax.SAXException : occurs if the element cannot be parsed correctly.
   * @see org.xml.sax.ContentHandler#startElement(String, String, String, org.xml.sax.Attributes)
   */
  public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
      throws SAXException {
    String namespace = namespaceURI;
    if (namespaceURI != null && (namespaceURI.equalsIgnoreCase(CorePluginFactory.NAMESPACE))) {
      namespace = null; // Remove the 'org.apache.felix.ipojo' namespace
    }
    // System.out.println("XML.e/// " + namespace + ":" + localName);
    XMLElement elem = new XMLElement(localName, namespace);
    for (int i = 0; i < atts.getLength(); i++) {
      String name = (String) atts.getLocalName(i);
      String ns = (String) atts.getURI(i);
      String value = (String) atts.getValue(i);
      // System.out.println("XML.a/// " + ns + ":" + name + "=" + value);
      XMLAttribute att = new XMLAttribute(name, ns, value);
      elem.addAttribute(att);
    }

    addElement(elem);
    // System.out.println("XML/// good");
  }
  /**
   * Helper class to write an Oscar attribute if needed
   *
   * @param name Name of the attribute
   * @param element the element that the attribute will be added to
   * @param rs the result set that includes the values of the attributes
   * @throws SQLException
   * @throws Exception
   */
  private static void writeOscarAtt(String name, XMLElement element, ResultSet rs)
      throws SQLException, Exception {
    String oscAtt = "";

    if (rs.next()) {
      if (rs.getString(2) == null) {
        oscAtt = "O" + rs.getString(1) + "0000000";
      } else {
        oscAtt = "O" + rs.getString(1) + rs.getString(2);
      }
      element.addAttribute(name, oscAtt);
      while (rs.next()) {
        if (rs.getString(2) == null) {
          oscAtt = "O" + rs.getString(1) + "0000000";
        } else {
          oscAtt = "O" + rs.getString(1) + rs.getString(2);
        }
        element.appendAttribute(name, oscAtt);
      }
    }
  }
  private void parseChannel(
      XMLExtendedStreamReader reader,
      PathAddress subsystemAddress,
      Map<PathAddress, ModelNode> operations)
      throws XMLStreamException {
    String name = require(reader, XMLAttribute.NAME);
    PathAddress address = subsystemAddress.append(ChannelResourceDefinition.pathElement(name));
    ModelNode operation = Util.createAddOperation(address);
    operations.put(address, operation);

    for (int i = 0; i < reader.getAttributeCount(); i++) {
      ParseUtils.requireNoNamespaceAttribute(reader, i);
      XMLAttribute attribute = XMLAttribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case NAME:
          {
            // Already parsed
            break;
          }
        case STACK:
          {
            readAttribute(reader, i, operation, ChannelResourceDefinition.Attribute.STACK);
            break;
          }
        case MODULE:
          {
            readAttribute(reader, i, operation, ChannelResourceDefinition.Attribute.MODULE);
            break;
          }
        default:
          {
            throw ParseUtils.unexpectedAttribute(reader, i);
          }
      }
    }

    while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) {
      XMLElement element = XMLElement.forName(reader.getLocalName());
      switch (element) {
        case FORK:
          {
            this.parseFork(reader, address, operations);
            break;
          }
        default:
          {
            throw ParseUtils.unexpectedElement(reader);
          }
      }
    }
  }
Esempio n. 26
0
		public XMLElement saveSelf () throws XMLCannotSaveException
		{ 	XMLElement result=new XMLElement("count");
			result.addAttribute(new XMLAttribute("tl-id",tl.getId()));
			result.addAttribute(new XMLAttribute("pos",pos));
			result.addAttribute(new	XMLAttribute("destination",destination.getId()));
			result.addAttribute(new XMLAttribute("light",light));
			result.addAttribute(new XMLAttribute("newtl-id",tl_new.getId()));
			result.addAttribute(new XMLAttribute("new-pos",pos_new));
			result.addAttribute(new XMLAttribute("ktl",Ktl));
			result.addAttribute(new XMLAttribute("value",value));
			if ( ! infrastructure.laneDictionary.containsKey
			     (new Integer (tl.getId())))
			{     
			     System.out.println
			     ("WARNING : Unknown Trafficlight ID "+tl.getId()+
			      " in TC3$CountEntry. Loading will go wrong");
			}
	  		return result;
		}
Esempio n. 27
0
 @Override
 public void startElement(XMLElement element, Attributes attributes) {
   if (PersistenceTagNames.PROPERTY.equals(element.getQName())) {
     assert (attributes.getLength() == 2);
     assert (attributes.getIndex(PersistenceTagNames.PROPERTY_NAME) != -1);
     assert (attributes.getIndex(PersistenceTagNames.PROPERTY_VALUE) != -1);
     PersistenceUnitDescriptor persistenceUnitDescriptor =
         (PersistenceUnitDescriptor) getDescriptor();
     String propName = attributes.getValue(PersistenceTagNames.PROPERTY_NAME);
     String propValue = attributes.getValue(PersistenceTagNames.PROPERTY_VALUE);
     persistenceUnitDescriptor.addProperty(propName, propValue);
     return;
   }
   super.startElement(element, attributes);
 }
  private void parseRelay(
      XMLExtendedStreamReader reader,
      PathAddress stackAddress,
      Map<PathAddress, ModelNode> operations)
      throws XMLStreamException {
    PathAddress address = stackAddress.append(RelayResourceDefinition.PATH);
    ModelNode operation = Util.createAddOperation(address);
    operations.put(address, operation);

    for (int i = 0; i < reader.getAttributeCount(); i++) {
      XMLAttribute attribute = XMLAttribute.forName(reader.getAttributeLocalName(i));
      switch (attribute) {
        case SITE:
          {
            readAttribute(reader, i, operation, RelayResourceDefinition.Attribute.SITE);
            break;
          }
        default:
          {
            throw ParseUtils.unexpectedAttribute(reader, i);
          }
      }
    }

    if (!operation.hasDefined(RelayResourceDefinition.Attribute.SITE.getDefinition().getName())) {
      throw ParseUtils.missingRequired(reader, EnumSet.of(XMLAttribute.SITE));
    }

    while (reader.hasNext() && (reader.nextTag() != XMLStreamConstants.END_ELEMENT)) {
      XMLElement element = XMLElement.forName(reader.getLocalName());
      switch (element) {
        case REMOTE_SITE:
          {
            this.parseRemoteSite(reader, address, operations);
            break;
          }
        case PROPERTY:
          {
            this.parseProperty(reader, address, operations);
            break;
          }
        default:
          {
            throw ParseUtils.unexpectedElement(reader);
          }
      }
    }
  }
Esempio n. 29
0
  /**
   * {@inheritDoc}
   *
   * @param raw Description of the Parameter
   * @return Description of the Return Value
   */
  protected boolean handleElement(Element raw) {

    if (super.handleElement(raw)) {
      return true;
    }

    XMLElement elem = (XMLElement) raw;

    if (DEST_PID_TAG.equals(elem.getName())) {
      try {
        URI pID = new URI(elem.getTextValue());

        setDestPeerID((PeerID) IDFactory.fromURI(pID));
      } catch (URISyntaxException badID) {
        throw new IllegalArgumentException("Bad PeerID in advertisement");
      } catch (ClassCastException badID) {
        throw new IllegalArgumentException("ID in advertisement is not a peer id");
      }
      return true;
    }

    if (elem.getName().equals("Dst")) {
      for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements(); ) {
        TextElement aXpt = (TextElement) eachXpt.nextElement();

        AccessPointAdvertisement xptAdv =
            (AccessPointAdvertisement) AdvertisementFactory.newAdvertisement(aXpt);

        setDest(xptAdv);
      }
      return true;
    }

    if (elem.getName().equals("Hops")) {
      Vector hops = new Vector();

      for (Enumeration eachXpt = elem.getChildren(); eachXpt.hasMoreElements(); ) {
        TextElement aXpt = (TextElement) eachXpt.nextElement();

        AccessPointAdvertisement xptAdv =
            (AccessPointAdvertisement) AdvertisementFactory.newAdvertisement(aXpt);

        hops.addElement(xptAdv);
      }
      setHops(hops);
      return true;
    }

    return false;
  }
Esempio n. 30
0
  /**
   * Private constructor. Use instantiator
   *
   * @param root Description of the Parameter
   */
  private RouteAdv(Element root) {
    if (!XMLElement.class.isInstance(root)) {
      throw new IllegalArgumentException(getClass().getName() + " only supports XLMElement");
    }

    XMLElement doc = (XMLElement) root;

    String doctype = doc.getName();

    String typedoctype = "";
    Attribute itsType = doc.getAttribute("type");

    if (null != itsType) {
      typedoctype = itsType.getValue();
    }

    if (!doctype.equals(getAdvertisementType()) && !getAdvertisementType().equals(typedoctype)) {
      throw new IllegalArgumentException(
          "Could not construct : "
              + getClass().getName()
              + "from doc containing a "
              + doc.getName());
    }

    Enumeration elements = doc.getChildren();

    while (elements.hasMoreElements()) {
      XMLElement elem = (XMLElement) elements.nextElement();

      if (!handleElement(elem)) {
        if (LOG.isEnabledFor(Level.DEBUG)) {
          LOG.debug("Unhandled Element: " + elem.toString());
        }
      }
    }

    // HACK Compatibility

    setDestPeerID(getDestPeerID());

    // Sanity Check!!!

    if (hasALoop()) {
      throw new IllegalArgumentException("Route contains a loop!");
    }
  }