List of usage examples for org.xml.sax SAXException SAXException
public SAXException(Exception e)
From source file:org.enhydra.shark.wfxml.util.BeanDeserializerShark.java
/** * Deserializer interface called on each child element encountered in * the XML stream./*from ww w .j a va2 s . c om*/ * @param namespace is the namespace of the child element * @param localName is the local name of the child element * @param prefix is the prefix used on the name of the child element * @param attributes are the attributes of the child element * @param context is the deserialization context. * @return is a Deserializer to use to deserialize a child (must be * a derived class of SOAPHandler) or null if no deserialization should * be performed. */ public SOAPHandler onStartChild(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { //System.err.println("onStartChild namespace:"+namespace); //System.err.println("onStartChild localName:"+localName); //System.err.println("onStartChild prefix :"+prefix); if (xmlType.toString().endsWith("GetPropertiesRs") || xmlType.toString().endsWith("SetPropertiesRs")) { //new Throwable("onStartChild namespace:"+namespace // + "\nonStartChild localName:"+localName // + "\nonStartChild prefix :"+prefix).printStackTrace(); int failures = 0; SOAPHandler sHnd = null; for (int n = 0; n < additional.length; ++n) { try { if (alreadyFailed[n]) { ++failures; continue; } sHnd = additional[n].onStartChild(namespace, localName, prefix, attributes, context); } catch (Throwable t) { //t.printStackTrace(); alreadyFailed[n] = true; ++failures; } } if (additional.length == failures) throw new SAXException(Messages.getMessage("cantCreateBean00", _addLocalNames[0], "")); return sHnd; } handleMixedContent(); BeanPropertyDescriptor propDesc = null; FieldDesc fieldDesc = null; SOAPConstants soapConstants = context.getSOAPConstants(); String encodingStyle = context.getMessageContext().getEncodingStyle(); boolean isEncoded = Constants.isSOAP_ENC(encodingStyle); QName elemQName = new QName(namespace, localName); // The collectionIndex needs to be reset for Beans with multiple arrays if ((prevQName == null) || (!prevQName.equals(elemQName))) { collectionIndex = -1; } prevQName = elemQName; if (typeDesc != null) { // Lookup the name appropriately (assuming an unqualified // name for SOAP encoding, using the namespace otherwise) String fieldName = typeDesc.getFieldNameForElement(elemQName, isEncoded); propDesc = (BeanPropertyDescriptor) propertyMap.get(fieldName); fieldDesc = typeDesc.getFieldByName(fieldName); } if (propDesc == null) { // look for a field by this name. propDesc = (BeanPropertyDescriptor) propertyMap.get(localName); } // try and see if this is an xsd:any namespace="##any" element before // reporting a problem if (propDesc == null) { // try to put unknown elements into a SOAPElement property, if // appropriate propDesc = getAnyPropertyDesc(); if (propDesc != null) { try { MessageElement[] curElements = (MessageElement[]) propDesc.get(value); int length = 0; if (curElements != null) { length = curElements.length; } MessageElement[] newElements = new MessageElement[length + 1]; if (curElements != null) { System.arraycopy(curElements, 0, newElements, 0, length); } MessageElement thisEl = context.getCurElement(); newElements[length] = thisEl; propDesc.set(value, newElements); // if this is the first pass through the MessageContexts // make sure that the correct any element is set, // that is the child of the current MessageElement, however // on the first pass this child has not been set yet, so // defer it to the child SOAPHandler if (!localName.equals(thisEl.getName())) { return new SOAPHandler(newElements, length); } return new SOAPHandler(); } catch (Exception e) { throw new SAXException(e); } } } if (propDesc == null) { // No such field throw new SAXException(Messages.getMessage("badElem00", javaType.getName(), localName)); } // Get the child's xsi:type if available QName childXMLType = context.getTypeFromAttributes(namespace, localName, attributes); String href = attributes.getValue(soapConstants.getAttrHref()); // If no xsi:type or href, check the meta-data for the field if (childXMLType == null && fieldDesc != null && href == null) { childXMLType = fieldDesc.getXmlType(); } // Get Deserializer for child, default to using DeserializerImpl Deserializer dSer = getDeserializer(childXMLType, propDesc.getType(), href, context); // It is an error if the dSer is not found - the only case where we // wouldn't have a deserializer at this point is when we're trying // to deserialize something we have no clue about (no good xsi:type, // no good metadata). if (dSer == null) { dSer = context.getDeserializerForClass(propDesc.getType()); } // Fastpath nil checks... if (context.isNil(attributes)) { if (propDesc != null && propDesc.isIndexed()) { if (!((dSer != null) && (dSer instanceof ArrayDeserializer)) || propDesc.getType().isArray()) { collectionIndex++; dSer.registerValueTarget(new BeanPropertyTarget(value, propDesc, collectionIndex)); addChildDeserializer(dSer); return (SOAPHandler) dSer; } } return null; } if (dSer == null) { throw new SAXException(Messages.getMessage("noDeser00", childXMLType.toString())); } // Register value target if (propDesc.isWriteable()) { // If this is an indexed property, and the deserializer we found // was NOT the ArrayDeserializer, this is a non-SOAP array: // <bean> // <field>value1</field> // <field>value2</field> // ... // In this case, we want to use the collectionIndex and make sure // the deserialized value for the child element goes into the // right place in the collection. if (propDesc.isIndexed() && (!(dSer instanceof ArrayDeserializer) || propDesc.getType().isArray())) { collectionIndex++; dSer.registerValueTarget(new BeanPropertyTarget(value, propDesc, collectionIndex)); } else { // If we're here, the element maps to a single field value, // whether that be a "basic" type or an array, so use the // normal (non-indexed) BeanPropertyTarget form. collectionIndex = -1; dSer.registerValueTarget(new BeanPropertyTarget(value, propDesc)); } } // Let the framework know that we need this deserializer to complete // for the bean to complete. addChildDeserializer(dSer); return (SOAPHandler) dSer; }
From source file:org.enhydra.shark.wfxml.util.BeanDeserializerShark.java
/** * Set the bean properties that correspond to element attributes. * * This method is invoked after startElement when the element requires * deserialization (i.e. the element is not an href and the value is not * nil.)/*from w w w .ja va2 s . c om*/ * @param namespace is the namespace of the element * @param localName is the name of the element * @param prefix is the prefix of the element * @param attributes are the attributes on the element...used to get the * type * @param context is the DeserializationContext */ public void onStartElement(String namespace, String localName, String prefix, Attributes attributes, DeserializationContext context) throws SAXException { if (xmlType.toString().endsWith("GetPropertiesRs") || xmlType.toString().endsWith("SetPropertiesRs")) { //new Throwable("onStartElement namespace:"+namespace // + "\nonStartElement localName:"+localName // + "\nonStartElement prefix :"+prefix).printStackTrace(); String pp = xmlType.toString().substring(0, xmlType.toString().length() - "GetPropertiesRs".length()); try { additional = new BeanDeserializerShark[4]; additional[0] = new BeanDeserializerShark( Class.forName("org.enhydra.shark.asap.types.ObserverPropertiesGroup"), new QName(pp + _addLocalNames[0])); additional[1] = new BeanDeserializerShark( Class.forName("org.enhydra.shark.asap.types.InstancePropertiesGroup"), new QName(pp + _addLocalNames[1])); additional[2] = new BeanDeserializerShark( Class.forName("org.enhydra.shark.asap.types.FactoryPropertiesGroup"), new QName(pp + _addLocalNames[2])); additional[3] = new BeanDeserializerShark( Class.forName("org.enhydra.shark.wfxml.types.RegistryPropertiesGroup"), new QName(pp + _addLocalNames[3])); } catch (Throwable t) { t.printStackTrace(); throw new SAXException(t.getMessage()); } alreadyFailed = new boolean[additional.length]; int failures = 0; for (int n = 0; n < additional.length; ++n) { try { alreadyFailed[n] = false; additional[n].startElement(namespace, _addLocalNames[n], prefix, attributes, context); } catch (Throwable t) { t.printStackTrace(); alreadyFailed[n] = true; ++failures; } } if (additional.length == failures) throw new SAXException(Messages.getMessage("cantCreateBean00", _addLocalNames[0], "")); } // The value should have been created or assigned already. // This code may no longer be needed. if (value == null) { // create a value try { value = javaType.newInstance(); } catch (Exception e) { throw new SAXException(Messages.getMessage("cantCreateBean00", javaType.getName(), e.toString())); } } // If no type description meta data, there are no attributes, // so we are done. if (typeDesc == null) return; // loop through the attributes and set bean properties that // correspond to attributes for (int i = 0; i < attributes.getLength(); i++) { QName attrQName = new QName(attributes.getURI(i), attributes.getLocalName(i)); String fieldName = typeDesc.getFieldNameForAttribute(attrQName); if (fieldName == null) continue; FieldDesc fieldDesc = typeDesc.getFieldByName(fieldName); // look for the attribute property BeanPropertyDescriptor bpd = (BeanPropertyDescriptor) propertyMap.get(fieldName); if (bpd != null) { if (!bpd.isWriteable() || bpd.isIndexed()) continue; // Get the Deserializer for the attribute Deserializer dSer = getDeserializer(fieldDesc.getXmlType(), bpd.getType(), null, context); if (dSer == null) { dSer = context.getDeserializerForClass(bpd.getType()); } if (dSer == null) throw new SAXException(Messages.getMessage("unregistered00", bpd.getType().toString())); if (!(dSer instanceof SimpleDeserializer)) throw new SAXException( Messages.getMessage("AttrNotSimpleType00", bpd.getName(), bpd.getType().toString())); // Success! Create an object from the string and set // it in the bean try { dSer.onStartElement(namespace, localName, prefix, attributes, context); Object val = ((SimpleDeserializer) dSer).makeValue(attributes.getValue(i)); bpd.set(value, val); } catch (Exception e) { throw new SAXException(e); } } // if } // attribute loop }
From source file:org.enhydra.shark.wfxml.util.BeanDeserializerShark.java
public void onEndElement(String namespace, String localName, DeserializationContext context) throws SAXException { if (xmlType.toString().endsWith("GetPropertiesRs") || xmlType.toString().endsWith("SetPropertiesRs")) { for (int n = 0; n < additional.length; ++n) { if (!alreadyFailed[n]) { BeanPropertyDescriptor propDesc = (BeanPropertyDescriptor) propertyMap.get(_addLocalNames[n]); System.err.println("localName:" + _addLocalNames[n] + ", propDesc:" + propDesc); try { propDesc.set(value, additional[n].getValue()); } catch (Throwable t) { t.printStackTrace(); throw new SAXException(t.getMessage()); }/*w w w . j a v a2s .c o m*/ } } } handleMixedContent(); }
From source file:org.exist.cocoon.XMLDBSource.java
private void resourceToSAX(ContentHandler handler) throws SAXException, XMLDBException, SourceException { if (!(resource instanceof XMLResource)) { throw new SAXException("Not an XML resource: " + getURI()); }/*from ww w. ja v a2 s.c om*/ if (query != null) { // Query resource if (getLogger().isDebugEnabled()) { getLogger().debug( "Querying resource " + resName + " from collection " + url + "; query= " + this.query); } queryToSAX(handler, collection, resName); } else { // Return entire resource if (getLogger().isDebugEnabled()) { getLogger().debug("Obtaining resource " + resName + " from collection " + colPath); } // <frederic.glorieux@ajlsm.com> exist specific improvements if (resource instanceof org.exist.xmldb.EXistResource) { // To output comments ((org.exist.xmldb.EXistResource) resource).setLexicalHandler((LexicalHandler) handler); } ((XMLResource) resource).getContentAsSAX(handler); } }
From source file:org.exolab.castor.xml.EndElementProcessor.java
public void compute(String name) throws org.xml.sax.SAXException { if (LOG.isTraceEnabled()) { String trace = MessageFormat.format(resourceBundle.getString("unmarshalHandler.log.trace.endElement"), new Object[] { name }); LOG.trace(trace);/*from ww w . j av a2 s .c om*/ } // -- If we are skipping elements that have appeared in the XML but for // -- which we have no mapping, decrease the ignore depth counter and // return if (_unmarshalHandler.getStrictElementHandler().skipEndElement()) { return; } // -- Do delagation if necessary if (_unmarshalHandler.getAnyNodeHandler().hasAnyUnmarshaller()) { _unmarshalHandler.getAnyNodeHandler().endElement(name); // we are back to the starting node if (_unmarshalHandler.getAnyNodeHandler().isStartingNode()) { _unmarshalHandler.setAnyNode(_unmarshalHandler.getAnyNodeHandler().getStartingNode()); } else return; } if (_unmarshalHandler.getStateStack().isEmpty()) { String err = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.missing.startElement"), new Object[] { name }); throw new SAXException(err); } // -- * Begin Namespace Handling // -- XXX Note: This code will change when we update the XML event API int idx = name.indexOf(':'); if (idx >= 0) { name = name.substring(idx + 1); } // -- * End Namespace Handling UnmarshalState state = _unmarshalHandler.getStateStack().removeLastState(); // -- make sure we have the correct closing tag XMLFieldDescriptor descriptor = state.getFieldDescriptor(); if (!state.getElementName().equals(name)) { // maybe there is still a container to end if (descriptor.isContainer()) { _unmarshalHandler.getStateStack().pushState(state); // -- check for possible characters added to // -- the container's state that should // -- really belong to the parent state StringBuffer tmpBuffer = null; if (state.getBuffer() != null) { if (!UnmarshalHandler.isWhitespace(state.getBuffer())) { if (state.getClassDescriptor().getContentDescriptor() == null) { tmpBuffer = state.getBuffer(); state.setBuffer(null); } } } // -- end container _unmarshalHandler.endElement(state.getElementName()); if (tmpBuffer != null) { state = _unmarshalHandler.getStateStack().getLastState(); if (state.getBuffer() == null) state.setBuffer(tmpBuffer); else state.getBuffer().append(tmpBuffer.toString()); } _unmarshalHandler.endElement(name); return; } String err = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.different.endElement.expected"), new Object[] { state.getElementName(), name }); throw new SAXException(err); } // -- clean up current Object Class<?> type = state.getType(); if (type == null) { if (!state.isWrapper()) { // -- this message will only show up if debug // -- is turned on...how should we handle this case? // -- should it be a fatal error? String info = MessageFormat.format( resourceBundle.getString("unmarshalHandler.log.info.no.Descriptor.found"), new Object[] { state.getElementName() }); LOG.info(info); } // -- handle possible location text content // -- TODO: cleanup location path support. // -- the following code needs to be improved as // -- for searching descriptors in this manner can // -- be slow StringBuffer tmpBuffer = null; if (state.getBuffer() != null) { if (!UnmarshalHandler.isWhitespace(state.getBuffer())) { tmpBuffer = state.getBuffer(); state.setBuffer(null); } } if (tmpBuffer != null) { UnmarshalState targetState = state; String locPath = targetState.getElementName(); while ((targetState = targetState.getParent()) != null) { if ((targetState.isWrapper()) || (targetState.getClassDescriptor() == null)) { locPath = targetState.getElementName() + "/" + locPath; continue; } XMLFieldDescriptor tmpDesc = targetState.getClassDescriptor().getContentDescriptor(); if (tmpDesc != null && locPath.equals(tmpDesc.getLocationPath())) { if (targetState.getBuffer() == null) targetState.setBuffer(tmpBuffer); else targetState.getBuffer().append(tmpBuffer.toString()); } } } // -- remove current namespace scoping _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance(); return; } // -- check for special cases boolean byteArray = false; if (type.isArray()) { byteArray = (type.getComponentType() == Byte.TYPE); } // -- If we don't have an instance object and the Class type // -- is not a primitive or a byte[] we must simply return if ((state.getObject() == null) && (!state.isPrimitiveOrImmutable())) { // -- remove current namespace scoping _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance(); return; } // / DEBUG System.out.println("end: " + name); if (state.isPrimitiveOrImmutable()) { String str = null; if (state.getBuffer() != null) { str = state.getBuffer().toString(); state.getBuffer().setLength(0); } if (type == String.class && !((XMLFieldDescriptorImpl) descriptor).isDerivedFromXSList()) { if (str != null) state.setObject(str); else if (state.isNil()) { state.setObject(null); } else { state.setObject(""); } } // -- special handling for byte[] else if (byteArray && !descriptor.isDerivedFromXSList()) { if (str == null) state.setObject(new byte[0]); else { state.setObject(_unmarshalHandler.decodeBinaryData(descriptor, str)); } } else if (state.getConstructorArguments() != null) { state.setObject(_unmarshalHandler.createInstance(state.getType(), state.getConstructorArguments())); } else if (descriptor.isMultivalued() && descriptor.getSchemaType() != null && descriptor.getSchemaType().equals("list") && ((XMLFieldDescriptorImpl) descriptor).isDerivedFromXSList()) { StringTokenizer attrValueTokenizer = new StringTokenizer(str); List<Object> primitives = new ArrayList<Object>(); while (attrValueTokenizer.hasMoreTokens()) { String tokenValue = attrValueTokenizer.nextToken(); if (MarshalFramework.isPrimitive(descriptor.getFieldType())) { primitives.add( _unmarshalHandler.toPrimitiveObject(type, tokenValue, state.getFieldDescriptor())); } else { Class<?> valueType = descriptor.getFieldType(); // -- handle base64/hexBinary if (valueType.isArray() && (valueType.getComponentType() == Byte.TYPE)) { primitives.add(_unmarshalHandler.decodeBinaryData(descriptor, tokenValue)); } } } state.setObject(primitives); } else { if (state.isNil()) { state.setObject(null); } else { state.setObject(_unmarshalHandler.toPrimitiveObject(type, str, state.getFieldDescriptor())); } } } else if (ArrayHandler.class.isAssignableFrom(state.getType())) { state.setObject(((ArrayHandler) state.getObject()).getObject()); state.setType(state.getObject().getClass()); } // -- check for character content if ((state.getBuffer() != null) && (state.getBuffer().length() > 0) && (state.getClassDescriptor() != null)) { XMLFieldDescriptor cdesc = state.getClassDescriptor().getContentDescriptor(); if (cdesc != null) { Object value = state.getBuffer().toString(); if (MarshalFramework.isPrimitive(cdesc.getFieldType())) value = _unmarshalHandler.toPrimitiveObject(cdesc.getFieldType(), (String) value, state.getFieldDescriptor()); else { Class<?> valueType = cdesc.getFieldType(); // -- handle base64/hexBinary if (valueType.isArray() && (valueType.getComponentType() == Byte.TYPE)) { value = _unmarshalHandler.decodeBinaryData(descriptor, (String) value); } } try { FieldHandler handler = cdesc.getHandler(); boolean addObject = true; if (_unmarshalHandler.isReuseObjects()) { // -- check to see if we need to // -- add the object or not Object tmp = handler.getValue(state.getObject()); if (tmp != null) { // -- Do not add object if values // -- are equal addObject = (!tmp.equals(value)); } } if (addObject) handler.setValue(state.getObject(), value); } catch (java.lang.IllegalStateException ise) { String err = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.unable.add.text"), new Object[] { descriptor.getXMLName(), ise.toString() }); throw new SAXException(err, ise); } } // -- Handle references else if (descriptor.isReference()) { UnmarshalState pState = _unmarshalHandler.getStateStack().getLastState(); _unmarshalHandler.processIDREF(state.getBuffer().toString(), descriptor, pState.getObject()); _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance(); return; } else { // -- check for non-whitespace...and report error if (!UnmarshalHandler.isWhitespace(state.getBuffer())) { String err = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.illegal.text"), new Object[] { name, state.getBuffer() }); throw new SAXException(err); } } } // -- We're finished processing the object, so notify the // -- Listener (if any). Object stateObject = state.getObject(); Object parentObject = (state.getParent() == null) ? null : state.getParent().getObject(); _unmarshalHandler.getDelegateUnmarshalListener().unmarshalled(stateObject, parentObject); // -- if we are at root....just validate and we are done if (_unmarshalHandler.getStateStack().isEmpty()) { if (_unmarshalHandler.isValidating()) { ValidationException first = null; ValidationException last = null; // -- check unresolved references if (_unmarshalHandler.getResolveTable() != null && !_unmarshalHandler.getInternalContext().getLenientIdValidation()) { Enumeration enumeration = _unmarshalHandler.getResolveTable().keys(); while (enumeration.hasMoreElements()) { Object ref = enumeration.nextElement(); // if // (ref.toString().startsWith(MapItem.class.getName())) // continue; String msg = "unable to resolve reference: " + ref; if (first == null) { first = new ValidationException(msg); last = first; } else { last.setNext(new ValidationException(msg)); last = last.getNext(); } } } try { Validator validator = new Validator(); ValidationContext context = new ValidationContext(); context.setInternalContext(_unmarshalHandler.getInternalContext()); validator.validate(state.getObject(), context); if (!_unmarshalHandler.getInternalContext().getLenientIdValidation()) { validator.checkUnresolvedIdrefs(context); } context.cleanup(); } catch (ValidationException vEx) { if (first == null) first = vEx; else last.setNext(vEx); } if (first != null) { throw new SAXException(first); } } return; } // -- Add object to parent if necessary if (descriptor.isIncremental()) { // -- remove current namespace scoping _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance(); return; // -- already added } Object val = state.getObject(); // --special code for AnyNode handling if (_unmarshalHandler.getAnyNode() != null) { val = _unmarshalHandler.getAnyNode(); _unmarshalHandler.setAnyNode(null); } // -- save fieldState UnmarshalState fieldState = state; // -- have we seen this object before? boolean firstOccurance = false; // -- get target object state = _unmarshalHandler.getStateStack().getLastState(); if (state.isWrapper()) { state = fieldState.getTargetState(); } // -- check to see if we have already read in // -- an element of this type. // -- (Q: if we have a container, do we possibly need to // -- also check the container's multivalued status?) if (!descriptor.isMultivalued()) { if (state.isUsed(descriptor)) { String location = name; while (!_unmarshalHandler.getStateStack().isEmpty()) { UnmarshalState tmpState = _unmarshalHandler.getStateStack().removeLastState(); if (!tmpState.isWrapper()) { if (tmpState.getFieldDescriptor().isContainer()) continue; } location = state.getElementName() + "/" + location; } String err = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.element.occurs.more.than.once"), new Object[] { name, state.getType().getName(), location }); ValidationException vx = new ValidationException(err); throw new SAXException(vx); } state.markAsUsed(descriptor); // -- if this is the identity then save id if (state.getClassDescriptor().getIdentity() == descriptor) { state.setKey(val); } } else { // -- check occurance of descriptor if (!state.isUsed(descriptor)) { firstOccurance = true; } // -- record usage of descriptor state.markAsUsed(descriptor); } try { FieldHandler handler = descriptor.getHandler(); // check if the value is a QName that needs to // be resolved (ns:value -> {URI}value) String valueType = descriptor.getSchemaType(); if ((valueType != null) && (valueType.equals(MarshalFramework.QNAME_NAME))) { val = _unmarshalHandler.getNamespaceHandling().resolveNamespace(val); } boolean addObject = true; if (_unmarshalHandler.isReuseObjects() && fieldState.isPrimitiveOrImmutable()) { // -- check to see if we need to // -- add the object or not Object tmp = handler.getValue(state.getObject()); if (tmp != null) { // -- Do not add object if values // -- are equal addObject = (!tmp.equals(val)); } } // -- special handling for mapped objects if (descriptor.isMapped()) { if (!(val instanceof MapItem)) { MapItem mapItem = new MapItem(fieldState.getKey(), val); val = mapItem; } else { // -- make sure value exists (could be a reference) MapItem mapItem = (MapItem) val; if (mapItem.getValue() == null) { // -- save for later... addObject = false; _unmarshalHandler.addReference(mapItem.toString(), state.getObject(), descriptor); } } } if (addObject) { // -- clear any collections if necessary if (firstOccurance && _unmarshalHandler.isClearCollections()) { handler.resetValue(state.getObject()); } if (descriptor.isMultivalued() && descriptor.getSchemaType() != null && descriptor.getSchemaType().equals("list") && ((XMLFieldDescriptorImpl) descriptor).isDerivedFromXSList()) { List<Object> values = (List<Object>) val; for (Object value : values) { // -- finally set the value!! handler.setValue(state.getObject(), value); // If there is a parent for this object, pass along // a notification that we've finished adding a child _unmarshalHandler.getDelegateUnmarshalListener().fieldAdded(descriptor.getFieldName(), state.getObject(), fieldState.getObject()); } } else { // -- finally set the value!! handler.setValue(state.getObject(), val); // If there is a parent for this object, pass along // a notification that we've finished adding a child _unmarshalHandler.getDelegateUnmarshalListener().fieldAdded(descriptor.getFieldName(), state.getObject(), fieldState.getObject()); } } } /* * catch(java.lang.reflect.InvocationTargetException itx) { * * Throwable toss = itx.getTargetException(); if (toss == null) toss = itx; * * String err = "unable to add '" + name + "' to <"; err += state.descriptor.getXMLName(); err * += "> due to the following exception: " + toss; throw new SAXException(err); } */ catch (Exception ex) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); pw.flush(); String err = MessageFormat.format(resourceBundle.getString("unmarshalHandler.error.unable.add.element"), new Object[] { name, state.getFieldDescriptor().getXMLName(), sw.toString() }); throw new SAXException(err, ex); } // -- remove current namespace scoping _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance(); // remove additional (artifical aka container) state introduced for // single-valued (iow maxOccurs="1") choices. if (state.getFieldDescriptor().isContainer() && state.getClassDescriptor().isChoice() && !state.getFieldDescriptor().isMultivalued()) { _unmarshalHandler.endElement(state.getElementName()); } }
From source file:org.exolab.castor.xml.parsing.AttributeSetBuilder.java
/** * Processes the attributes and XML name space declarations found in the given SAX v1 * AttributeList. The global AttributeSet is cleared and updated with the attribute data. XML name * space declarations are added to the set of XML name spaces in scope. * // ww w . ja v a 2s .c o m * @deprecated * @param atts the {@link AttributeList} to process (can be null) **/ private AttributeSet processAttributeList(AttributeList atts, AttributeSetImpl attributeSet) throws SAXException { if (atts == null || atts.getLength() == 0) return attributeSet; // -- process all namespaces first int attCount = 0; boolean[] validAtts = new boolean[atts.getLength()]; for (int i = 0; i < validAtts.length; i++) { String attName = atts.getName(i); if (attName.equals(XMLNS)) { _namespaceHandling.addDefaultNamespace(atts.getValue(i)); } else if (attName.startsWith(XMLNS_PREFIX)) { String prefix = attName.substring(XMLNS_PREFIX_LENGTH); _namespaceHandling.addNamespace(prefix, atts.getValue(i)); } else { validAtts[i] = true; ++attCount; } } // -- process validAtts...if any exist for (int i = 0; i < validAtts.length; i++) { if (!validAtts[i]) continue; String namespace = null; String attName = atts.getName(i); int idx = attName.indexOf(':'); if (idx > 0) { String prefix = attName.substring(0, idx); if (!prefix.equals(XML_PREFIX)) { attName = attName.substring(idx + 1); namespace = _namespaceHandling.getNamespaceURI(prefix); if (namespace == null) { String error = "The namespace associated with " + "the prefix '" + prefix + "' could not be resolved."; throw new SAXException(error); } } } attributeSet.setAttribute(attName, atts.getValue(i), namespace); } return attributeSet; }
From source file:org.exolab.castor.xml.StartElementProcessor.java
public void compute(String name, String namespace, AttributeSet atts) throws SAXException { UnmarshalState state = null;/*from ww w . ja v a2 s . co m*/ String xmlSpace = null; // -- handle special atts if (atts != null) { // -- xml:space xmlSpace = atts.getValue(UnmarshalHandler.XML_SPACE, Namespaces.XML_NAMESPACE); if (xmlSpace == null) { xmlSpace = atts.getValue(UnmarshalHandler.XML_SPACE_WITH_PREFIX, ""); } } if (_unmarshalHandler.getStateStack().isEmpty()) { // -- Initialize since this is the first element _unmarshalHandler.processFirstElement(name, namespace, atts, xmlSpace); return; } // --rootElement // -- get MarshalDescriptor for the given element UnmarshalState parentState = _unmarshalHandler.getStateStack().getLastState(); // Test if we can accept the field in the parentState // in case the parentState fieldDesc is a container // -- This following logic tests to see if we are in a // -- container and we need to close out the container // -- before proceeding: boolean canAccept = false; while ((parentState.getFieldDescriptor() != null) && (parentState.getFieldDescriptor().isContainer() && !canAccept)) { XMLClassDescriptor tempClassDesc = parentState.getClassDescriptor(); // -- Find ClassDescriptor for Parent if (tempClassDesc == null) { tempClassDesc = (XMLClassDescriptor) parentState.getFieldDescriptor().getClassDescriptor(); if (tempClassDesc == null) tempClassDesc = _unmarshalHandler.getClassDescriptor(parentState.getObject().getClass()); } canAccept = tempClassDesc.canAccept(name, namespace, parentState.getObject()); if (!canAccept) { // -- Does container class even handle this field? if (tempClassDesc.getFieldDescriptor(name, namespace, NodeType.Element) != null) { if (!parentState.getFieldDescriptor().isMultivalued()) { String error = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.container.full"), new Object[] { tempClassDesc.getJavaClass().getName(), name }); ValidationException vx = new ValidationException(error); throw new SAXException(vx); } } _unmarshalHandler.endElement(parentState.getElementName()); parentState = _unmarshalHandler.getStateStack().getLastState(); } tempClassDesc = null; } // -- create new state object state = new UnmarshalState(); state.setElementName(name); state.setParent(parentState); if (xmlSpace != null) { state.setWhitespacePreserving(UnmarshalHandler.PRESERVE.equals(xmlSpace)); } else { state.setWhitespacePreserving(parentState.isWhitespacePreserving()); } _unmarshalHandler.getStateStack().pushState(state); // -- make sure we should proceed if (parentState.getObject() == null) { if (!parentState.isWrapper()) { return; } } Class cls = null; // -- Find ClassDescriptor for Parent XMLClassDescriptor classDesc = parentState.getClassDescriptor(); if (classDesc == null) { classDesc = (XMLClassDescriptor) parentState.getFieldDescriptor().getClassDescriptor(); if (classDesc == null) classDesc = _unmarshalHandler.getClassDescriptor(parentState.getObject().getClass()); } else { // classDesc.resetElementCount(); } // ----------------------------------------------------/ // - Find FieldDescriptor associated with the element -/ // ----------------------------------------------------/ // -- A reference to the FieldDescriptor associated // -- the the "current" element XMLFieldDescriptor descriptor = null; // -- inherited class descriptor // -- (only needed if descriptor cannot be found directly) XMLClassDescriptor cdInherited = null; // -- loop through stack and find correct descriptor // int pIdx = _stateInfo.size() - 2; //-- index of parentState UnmarshalState targetState = parentState; String path = ""; int count = 0; boolean isWrapper = false; XMLClassDescriptor oldClassDesc = classDesc; while (descriptor == null) { // -- NOTE (kv 20050228): // -- we need to clean this code up, I made this // -- fix to make sure the correct descriptor which // -- matches the location path is used if (path.length() > 0) { String tmpName = path + "/" + name; descriptor = classDesc.getFieldDescriptor(tmpName, namespace, NodeType.Element); } // -- End Patch if (descriptor == null) { descriptor = classDesc.getFieldDescriptor(name, namespace, NodeType.Element); } // -- Namespace patch, should be moved to XMLClassDescriptor, but // -- this is the least intrusive patch at the moment. kv - 20030423 if ((descriptor != null) && (!descriptor.isContainer())) { if (StringUtils.isNotEmpty(namespace)) { if (!MarshalFramework.namespaceEquals(namespace, descriptor.getNameSpaceURI())) { // -- if descriptor namespace is not null, then we must // -- have a namespace match, so set descriptor to null, // -- or if descriptor is not a wildcard we can also // -- set to null. if ((descriptor.getNameSpaceURI() != null) || (!descriptor.matches("*"))) { descriptor = null; } } } } // -- end namespace patch /* * If descriptor is null, we need to handle possible inheritence, which might not be described * in the current ClassDescriptor. This can be a slow process...for speed use the match * attribute of the xml element in the mapping file. This logic might not be completely * necessary, and perhaps we should remove it. */ // handle multiple level locations (where count > 0) (CASTOR-1039) // if ((descriptor == null) && (count == 0) && // (!targetState.wrapper)) { if ((descriptor == null) && (!targetState.isWrapper())) { MarshalFramework.InheritanceMatch[] matches = null; try { matches = _unmarshalHandler.searchInheritance(name, namespace, classDesc); // TODO: // Joachim, // _cdResolver); } catch (MarshalException rx) { // -- TODO: } if (matches.length != 0) { InheritanceMatch match = null; // It may be the case that this class descriptor can // appear under multiple parent field descriptors. Look // for the first match whose parent file descriptor XML // name matches the name of the element we are under for (int i = 0; i < matches.length; i++) { if (parentState.getElementName().equals(matches[i].parentFieldDesc.getLocationPath())) { match = matches[i]; break; } } if (match == null) match = matches[0]; descriptor = match.parentFieldDesc; cdInherited = match.inheritedClassDesc; break; // -- found } /* */ // handle multiple level locations (where count > 0) // (CASTOR-1039) // isWrapper = (isWrapper || hasFieldsAtLocation(name, // classDesc)); StringBuilder tmpLocation = new StringBuilder(); if (count > 0) { tmpLocation.append(path).append('/'); } tmpLocation.append(name); isWrapper = (isWrapper || MarshalFramework.hasFieldsAtLocation(tmpLocation.toString(), classDesc)); } else if (descriptor != null) { String tmpPath = descriptor.getLocationPath(); if (path.equals(StringUtils.defaultString(tmpPath))) break; // -- found descriptor = null; // -- not found, try again } else { isWrapper = (isWrapper || MarshalFramework.hasFieldsAtLocation(path + '/' + name, classDesc)); } // -- Make sure there are more parent classes on stack // -- otherwise break, since there is nothing to do // if (pIdx == 0) break; if (targetState == _unmarshalHandler.getTopState()) break; // -- adjust name and try parent if (count == 0) path = targetState.getElementName(); else { path = targetState.getElementName() + '/' + path; } // -- get // --pIdx; // targetState = (UnmarshalState)_stateInfo.elementAt(pIdx); targetState = targetState.getParent(); classDesc = targetState.getClassDescriptor(); count++; } if (descriptor != null && _unmarshalHandler.isValidating() && !_unmarshalHandler.getInternalContext().getLenientSequenceOrder()) { try { classDesc.checkDescriptorForCorrectOrderWithinSequence(descriptor, parentState, name); } catch (ValidationException e) { throw new SAXException(e); } } // -- The field descriptor is still null, we face a problem if (descriptor == null) { // -- reset classDesc classDesc = oldClassDesc; // -- isWrapper? if (isWrapper) { state.setClassDescriptor(new XMLClassDescriptorImpl(ContainerElement.class, name)); state.setWrapper(true); if (LOG.isDebugEnabled()) { LOG.debug("wrapper-element: " + name); } // -- process attributes _unmarshalHandler.processWrapperAttributes(atts); return; } String error = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.find.field.descriptor"), new Object[] { name, classDesc.getXMLName() }); // -- unwrap classDesc, if necessary, for the check // -- Introspector.introspected done below if (classDesc instanceof InternalXMLClassDescriptor) { classDesc = ((InternalXMLClassDescriptor) classDesc).getClassDescriptor(); } // -- If we are skipping elements that have appeared in the XML but // for // -- which we have no mapping, increase the ignore depth counter // and return boolean lenientElementStrictnessForIntrospection = _unmarshalHandler.getInternalContext() .getBooleanProperty(XMLProperties.LENIENT_INTROSPECTED_ELEMENT_STRICTNESS).booleanValue(); // checks if the element could be skipped if (_unmarshalHandler.getStrictElementHandler().skipStartElementIgnoringDepth()) { // -- remove the StateInfo we just added _unmarshalHandler.getStateStack().removeLastState(); // drop Namespace instance as well _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance(); if (LOG.isDebugEnabled()) { String debug = MessageFormat.format( resourceBundle.getString("unmarshalHandler.log.debug.ignore.extra.element"), new Object[] { error }); LOG.debug(debug); } return; } // if we have no field descriptor and // the class descriptor was introspected // just log it else if (lenientElementStrictnessForIntrospection && Introspector.introspected(classDesc)) { LOG.warn(error); return; } // -- otherwise report error since we cannot find a suitable // -- descriptor else { throw new SAXException(error); } } // -- end null descriptor // / DEBUG: System.out.println("path: " + path); // -- Save targetState (used in endElement) if (targetState != parentState) { state.setTargetState(targetState); parentState = targetState; // -- reassign } Object object = parentState.getObject(); // --container support if (descriptor.isContainer()) { // create a new state to set the container as the object // don't save the current state, it will be recreated later if (LOG.isDebugEnabled()) { LOG.debug("#container: " + descriptor.getFieldName()); } // -- clear current state and re-use for the container state.clear(); // -- inherit whitespace preserving from the parentState state.setWhitespacePreserving(parentState.isWhitespacePreserving()); state.setParent(parentState); // here we can hard-code a name or take the field name state.setElementName(descriptor.getFieldName()); state.setFieldDescriptor(descriptor); state.setClassDescriptor((XMLClassDescriptor) descriptor.getClassDescriptor()); Object containerObject = null; // 1-- the container is not multivalued (not a collection) if (!descriptor.isMultivalued()) { // Check if the container object has already been instantiated FieldHandler handler = descriptor.getHandler(); containerObject = handler.getValue(object); if (containerObject != null) { if (state.getClassDescriptor() != null) { if (state.getClassDescriptor().canAccept(name, namespace, containerObject)) { // remove the descriptor from the used list parentState.markAsNotUsed(descriptor); } } else { // remove the descriptor from the used list parentState.markAsNotUsed(descriptor); } } else { containerObject = handler.newInstance(object); } } // 2-- the container is multivalued else { Class containerClass = descriptor.getFieldType(); try { containerObject = containerClass.newInstance(); } catch (Exception ex) { throw new SAXException(ex); } } state.setObject(containerObject); state.setType(containerObject.getClass()); // we need to recall startElement() // so that we can find a more appropriate descriptor in for the // given name _unmarshalHandler.getNamespaceHandling().createNamespace(); _unmarshalHandler.startElementProcessing(name, namespace, atts); return; } // --End of the container support // -- Find object type and create new Object of that type state.setFieldDescriptor(descriptor); /* * <update> we need to add this code back in, to make sure we have proper access rights. * * if (!descriptor.getAccessRights().isWritable()) { if (debug) { buf.setLength(0); buf.append( * "The field for element '"); buf.append(name); buf.append("' is read-only."); * message(buf.toString()); } return; } */ // -- Find class to instantiate // -- check xml names to see if we should look for a more specific // -- ClassDescriptor, otherwise just use the one found in the // -- descriptor classDesc = null; if (cdInherited != null) classDesc = cdInherited; else if (!name.equals(descriptor.getXMLName())) classDesc = _unmarshalHandler.resolveByXMLName(name, namespace, null); if (classDesc == null) classDesc = (XMLClassDescriptor) descriptor.getClassDescriptor(); FieldHandler handler = descriptor.getHandler(); boolean useHandler = true; try { // -- Get Class type...first use ClassDescriptor, // -- since it could be more specific than // -- the FieldDescriptor if (classDesc != null) { cls = classDesc.getJavaClass(); // -- XXXX This is a hack I know...but we // -- XXXX can't use the handler if the field // -- XXXX types are different if (descriptor.getFieldType() != cls) { state.setDerived(true); } } else { cls = descriptor.getFieldType(); } // -- This *shouldn't* happen, but a custom implementation // -- could return null in the XMLClassDesctiptor#getJavaClass // -- or XMLFieldDescriptor#getFieldType. If so, just replace // -- with java.lang.Object.class (basically "anyType"). if (cls == null) { cls = java.lang.Object.class; } // Retrieving the xsi:type attribute, if present String currentPackage = _unmarshalHandler.getJavaPackage(parentState.getType()); String instanceType = _unmarshalHandler.getInstanceType(atts, currentPackage); if (instanceType != null) { Class instanceClass = null; try { XMLClassDescriptor instanceDesc = _unmarshalHandler.getClassDescriptor(instanceType, _unmarshalHandler.getClassLoader()); boolean loadClass = true; if (instanceDesc != null) { instanceClass = instanceDesc.getJavaClass(); classDesc = instanceDesc; if (instanceClass != null) { loadClass = (!instanceClass.getName().equals(instanceType)); } } if (loadClass) { instanceClass = _unmarshalHandler.loadClass(instanceType, null); // the FieldHandler can be either an XMLFieldHandler // or a FieldHandlerImpl FieldHandler tempHandler = descriptor.getHandler(); boolean collection = false; if (tempHandler instanceof FieldHandlerImpl) { collection = ((FieldHandlerImpl) tempHandler).isCollection(); } else { collection = Introspector.isCollection(instanceClass); } if ((!collection) && !cls.isAssignableFrom(instanceClass)) { if (!MarshalFramework.isPrimitive(cls)) { String err = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.not.subclass"), new Object[] { instanceClass.getName(), cls.getName() }); throw new SAXException(err); } } } cls = instanceClass; useHandler = false; } catch (Exception ex) { String err = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.unable.instantiate.exception"), new Object[] { instanceType, ex.getMessage() }); throw new SAXException(err, ex); } } // -- Handle ArrayHandler if (cls == Object.class) { if (parentState.getObject() instanceof ArrayHandler) cls = ((ArrayHandler) parentState.getObject()).componentType(); } // -- Handle support for "Any" type if (cls == Object.class) { Class pClass = parentState.getType(); ClassLoader loader = pClass.getClassLoader(); // -- first look for a descriptor based // -- on the XML name classDesc = _unmarshalHandler.resolveByXMLName(name, namespace, loader); // -- if null, create classname, and try resolving String cname = null; if (classDesc == null) { // -- create class name cname = _unmarshalHandler.getJavaNaming().toJavaClassName(name); classDesc = _unmarshalHandler.getClassDescriptor(cname, loader); } // -- if still null, try using parents package if (classDesc == null) { // -- use parent to get package information String pkg = pClass.getName(); int idx = pkg.lastIndexOf('.'); if (idx > 0) { pkg = pkg.substring(0, idx + 1); cname = pkg + cname; classDesc = _unmarshalHandler.getClassDescriptor(cname, loader); } } if (classDesc != null) { cls = classDesc.getJavaClass(); useHandler = false; } else { // we are dealing with an AnyNode state.setObject(_unmarshalHandler.getAnyNodeHandler().commonStartElement(name, namespace, state.isWhitespacePreserving())); state.setType(cls); return; } } boolean byteArray = false; if (cls.isArray()) byteArray = (cls.getComponentType() == Byte.TYPE); // -- check for immutable if (MarshalFramework.isPrimitive(cls) || descriptor.isImmutable() || byteArray) { state.setObject(null); state.setPrimitiveOrImmutable(true); // -- handle immutable types, such as java.util.Locale if (descriptor.isImmutable()) { if (classDesc == null) classDesc = _unmarshalHandler.getClassDescriptor(cls); state.setClassDescriptor(classDesc); Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc); if (args != null && args.size() > 0) { state.setConstructorArguments(args); } } } else { if (classDesc == null) classDesc = _unmarshalHandler.getClassDescriptor(cls); // -- XXXX should remove this test once we can // -- XXXX come up with a better solution if ((!state.isDerived()) && useHandler) { boolean create = true; if (_unmarshalHandler.isReuseObjects()) { state.setObject(handler.getValue(parentState.getObject())); create = (state.getObject() == null); } if (create) { Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc); if ((args.getValues() != null) && (args.getValues().length > 0)) { if (handler instanceof ExtendedFieldHandler) { ExtendedFieldHandler efh = (ExtendedFieldHandler) handler; state.setObject(efh.newInstance(parentState.getObject(), args.getValues())); } else { String err = resourceBundle .getString("unmarshalHandler.error.constructor.arguments"); throw new SAXException(err); } } else { state.setObject(handler.newInstance(parentState.getObject())); } } } // -- reassign class in case there is a conflict // -- between descriptor#getFieldType and // -- handler#newInstance...I should hope not, but // -- who knows if (state.getObject() != null) { cls = state.getObject().getClass(); if (classDesc != null) { if (classDesc.getJavaClass() != cls) { classDesc = null; } } } else { try { if (cls.isArray()) { state.setObject(new ArrayHandler(cls.getComponentType())); cls = ArrayHandler.class; } else { Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc); state.setObject(_unmarshalHandler.createInstance(cls, args)); // state.object = _class.newInstance(); } } catch (java.lang.Exception ex) { String err = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.unable.instantiate.exception"), new Object[] { _unmarshalHandler.className(cls), ex.getMessage() }); throw new SAXException(err, ex); } } } state.setType(cls); } catch (java.lang.IllegalStateException ise) { LOG.error(ise.toString()); throw new SAXException(ise); } // -- At this point we should have a new object, unless // -- we are dealing with a primitive type, or a special // -- case such as byte[] if (classDesc == null) { classDesc = _unmarshalHandler.getClassDescriptor(cls); } state.setClassDescriptor(classDesc); if ((state.getObject() == null) && (!state.isPrimitiveOrImmutable())) { String err = MessageFormat.format(resourceBundle.getString("unmarshalHandler.error.unable.unmarshal"), new Object[] { name, _unmarshalHandler.className(cls) }); throw new SAXException(err); } // -- assign object, if incremental if (descriptor.isIncremental()) { if (LOG.isDebugEnabled()) { String debug = MessageFormat.format( resourceBundle.getString("unmarshalHandler.log.debug.process.incrementally"), new Object[] { name }); LOG.debug(debug); } try { handler.setValue(parentState.getObject(), state.getObject()); } catch (java.lang.IllegalStateException ise) { String err = MessageFormat.format( resourceBundle.getString("unmarshalHandler.error.unable.add.element"), new Object[] { name, parentState.getFieldDescriptor().getXMLName(), ise.getMessage() }); throw new SAXException(err, ise); } } if (state.getObject() != null) { // --The object has just been initialized // --notify the listener Object stateObject = state.getObject(); Object parentObject = (state.getParent() == null) ? null : state.getParent().getObject(); _unmarshalHandler.getDelegateUnmarshalListener().initialized(stateObject, parentObject); _unmarshalHandler.processAttributes(atts, classDesc); _unmarshalHandler.getDelegateUnmarshalListener().attributesProcessed(stateObject, parentObject); _unmarshalHandler.getNamespaceHandling().processNamespaces(classDesc, _unmarshalHandler.getStateStack().getLastState().getObject()); } else if ((state.getType() != null) && (!state.isPrimitiveOrImmutable())) { if (atts != null) { _unmarshalHandler.processWrapperAttributes(atts); String warn = MessageFormat.format( resourceBundle.getString("unmarshalHandler.log.warn.process.attribute.as.location"), new Object[] { name }); LOG.warn(warn); } } else { // -- check for special attributes, such as xsi:nil if (atts != null) { String nil = atts.getValue(MarshalFramework.NIL_ATTR, MarshalFramework.XSI_NAMESPACE); state.setNil("true".equals(nil)); _unmarshalHandler.processWrapperAttributes(atts); } } }
From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java
/** * Processes the given document and stores the events to db. *//* ww w .j a v a 2 s. c om*/ private void processEvents(Session session, Document document) throws DOMException, SAXException, InvalidFormatException { NodeList eventList = document.getElementsByTagName("EventList"); NodeList events = eventList.item(0).getChildNodes(); // walk through all supplied events int eventCount = 0; for (int i = 0; i < events.getLength(); i++) { Node eventNode = events.item(i); String nodeName = eventNode.getNodeName(); if (nodeName.equals(EpcisConstants.OBJECT_EVENT) || nodeName.equals(EpcisConstants.AGGREGATION_EVENT) || nodeName.equals(EpcisConstants.QUANTITY_EVENT) || nodeName.equals(EpcisConstants.TRANSACTION_EVENT)) { LOG.debug("processing event " + i + ": '" + nodeName + "'."); handleEvent(session, eventNode, nodeName); eventCount++; if (eventCount % 50 == 0) { session.flush(); session.clear(); } } else if (!nodeName.equals("#text") && !nodeName.equals("#comment")) { throw new SAXException("Encountered unknown event '" + nodeName + "'."); } } }
From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java
/** * Takes an XML document node, parses it as EPCIS event and inserts the data * into the database. The parse routine is generic for all event types; the * query generation part has some if/elses to take care of different event * parameters.//from ww w . ja v a 2 s .co m * * @param eventNode * The current event node. * @param eventType * The current event type. * @throws Exception * @throws DOMException */ private void handleEvent(Session session, final Node eventNode, final String eventType) throws DOMException, SAXException, InvalidFormatException { if (eventNode == null) { // nothing to do return; } else if (eventNode.getChildNodes().getLength() == 0) { throw new SAXException("Event element '" + eventNode.getNodeName() + "' has no children elements."); } Node curEventNode = null; // A lot of the initialized variables have type URI. This type isn't to // compare with the URI-Type of the standard. In fact, most of the // variables having type URI are declared as Vocabularies in the // Standard. Commonly, we use String for the Standard-Type URI. Calendar eventTime = null; Calendar recordTime = GregorianCalendar.getInstance(); String eventTimeZoneOffset = null; String action = null; String parentId = null; Long quantity = null; String bizStepUri = null; String dispositionUri = null; String readPointUri = null; String bizLocationUri = null; String epcClassUri = null; List<String> epcs = null; List<BusinessTransaction> bizTransList = null; List<EventFieldExtension> fieldNameExtList = new ArrayList<EventFieldExtension>(); for (int i = 0; i < eventNode.getChildNodes().getLength(); i++) { curEventNode = eventNode.getChildNodes().item(i); String nodeName = curEventNode.getNodeName(); if (nodeName.equals("#text") || nodeName.equals("#comment")) { // ignore text or comments LOG.debug(" ignoring text or comment: '" + curEventNode.getTextContent().trim() + "'"); continue; } LOG.debug(" handling event field: '" + nodeName + "'"); if (nodeName.equals("eventTime")) { String xmlTime = curEventNode.getTextContent(); LOG.debug(" eventTime in xml is '" + xmlTime + "'"); try { eventTime = TimeParser.parseAsCalendar(xmlTime); } catch (ParseException e) { throw new SAXException("Invalid date/time (must be ISO8601).", e); } LOG.debug(" eventTime parsed as '" + eventTime.getTime() + "'"); } else if (nodeName.equals("recordTime")) { // ignore recordTime } else if (nodeName.equals("eventTimeZoneOffset")) { eventTimeZoneOffset = checkEventTimeZoneOffset(curEventNode.getTextContent()); } else if (nodeName.equals("epcList") || nodeName.equals("childEPCs")) { epcs = handleEpcs(eventType, curEventNode); } else if (nodeName.equals("bizTransactionList")) { bizTransList = handleBizTransactions(session, curEventNode); } else if (nodeName.equals("action")) { action = curEventNode.getTextContent(); if (!action.equals("ADD") && !action.equals("OBSERVE") && !action.equals("DELETE")) { throw new SAXException("Encountered illegal 'action' value: " + action); } } else if (nodeName.equals("bizStep")) { bizStepUri = curEventNode.getTextContent(); } else if (nodeName.equals("disposition")) { dispositionUri = curEventNode.getTextContent(); } else if (nodeName.equals("readPoint")) { Element attrElem = (Element) curEventNode; Node id = attrElem.getElementsByTagName("id").item(0); readPointUri = id.getTextContent(); } else if (nodeName.equals("bizLocation")) { Element attrElem = (Element) curEventNode; Node id = attrElem.getElementsByTagName("id").item(0); bizLocationUri = id.getTextContent(); } else if (nodeName.equals("epcClass")) { epcClassUri = curEventNode.getTextContent(); } else if (nodeName.equals("quantity")) { quantity = Long.valueOf(curEventNode.getTextContent()); } else if (nodeName.equals("parentID")) { checkEpcOrUri(curEventNode.getTextContent(), false); parentId = curEventNode.getTextContent(); } else { String[] parts = nodeName.split(":"); if (parts.length == 2) { LOG.debug(" treating unknown event field as extension."); String prefix = parts[0]; String localname = parts[1]; // String namespace = // document.getDocumentElement().getAttribute("xmlns:" + // prefix); String namespace = curEventNode.lookupNamespaceURI(prefix); String value = curEventNode.getTextContent(); EventFieldExtension evf = new EventFieldExtension(prefix, namespace, localname, value); fieldNameExtList.add(evf); } else { // this is not a valid extension throw new SAXException(" encountered unknown event field: '" + nodeName + "'."); } } } if (eventType.equals(EpcisConstants.AGGREGATION_EVENT)) { // for AggregationEvents, the parentID is only optional for // action=OBSERVE if (parentId == null && ("ADD".equals(action) || "DELETE".equals(action))) { throw new InvalidFormatException("'parentID' is required if 'action' is ADD or DELETE"); } } // Changed by nkef (use "getOrEditVocabularyElement" instead of // "getOrInsertVocabularyElement") String nodeName = eventNode.getNodeName(); VocabularyElement bizStep = bizStepUri != null ? getOrEditVocabularyElement(session, EpcisConstants.BUSINESS_STEP_ID, String.valueOf(bizStepUri), "1") : null; VocabularyElement disposition = dispositionUri != null ? getOrEditVocabularyElement(session, EpcisConstants.DISPOSITION_ID, String.valueOf(dispositionUri), "1") : null; VocabularyElement readPoint = readPointUri != null ? getOrEditVocabularyElement(session, EpcisConstants.READ_POINT_ID, String.valueOf(readPointUri), "1") : null; VocabularyElement bizLocation = bizLocationUri != null ? getOrEditVocabularyElement(session, EpcisConstants.BUSINESS_LOCATION_ID, String.valueOf(bizLocationUri), "1") : null; VocabularyElement epcClass = epcClassUri != null ? getOrEditVocabularyElement(session, EpcisConstants.EPC_CLASS_ID, String.valueOf(epcClassUri), "1") : null; BaseEvent be; if (nodeName.equals(EpcisConstants.AGGREGATION_EVENT)) { AggregationEvent ae = new AggregationEvent(); ae.setParentId(parentId); ae.setChildEpcs(epcs); ae.setAction(Action.valueOf(action)); be = ae; } else if (nodeName.equals(EpcisConstants.OBJECT_EVENT)) { ObjectEvent oe = new ObjectEvent(); oe.setAction(Action.valueOf(action)); if (epcs != null && epcs.size() > 0) { oe.setEpcList(epcs); } be = oe; } else if (nodeName.equals(EpcisConstants.QUANTITY_EVENT)) { QuantityEvent qe = new QuantityEvent(); qe.setEpcClass((EPCClass) epcClass); if (quantity != null) { qe.setQuantity(quantity.longValue()); } be = qe; } else if (nodeName.equals(EpcisConstants.TRANSACTION_EVENT)) { TransactionEvent te = new TransactionEvent(); te.setParentId(parentId); te.setEpcList(epcs); te.setAction(Action.valueOf(action)); be = te; } else { throw new SAXException("Encountered unknown event element '" + nodeName + "'."); } be.setEventTime(eventTime); be.setRecordTime(recordTime); be.setEventTimeZoneOffset(eventTimeZoneOffset); be.setBizStep((BusinessStepId) bizStep); be.setDisposition((DispositionId) disposition); be.setBizLocation((BusinessLocationId) bizLocation); be.setReadPoint((ReadPointId) readPoint); if (bizTransList != null && bizTransList.size() > 0) { be.setBizTransList(bizTransList); } if (!fieldNameExtList.isEmpty()) { be.setExtensions(fieldNameExtList); } session.save(be); }
From source file:org.fosstrak.epcis.repository.capture.CaptureOperationsModule.java
/** * Processes the given document and stores the masterdata to db. *///from w w w.ja v a 2 s. c om private void processMasterData(Session session, Document document) throws DOMException, SAXException, InvalidFormatException { // Handle Vocabulary List NodeList vocabularyList = document.getElementsByTagName("VocabularyList"); if (vocabularyList.item(0).hasChildNodes()) { NodeList vocabularys = vocabularyList.item(0).getChildNodes(); // walk through all supplied vocabularies int vocabularyCount = 0; for (int i = 0; i < vocabularys.getLength(); i++) { Node vocabularyNode = vocabularys.item(i); String nodeName = vocabularyNode.getNodeName(); if (nodeName.equals("Vocabulary")) { String vocabularyType = vocabularyNode.getAttributes().getNamedItem("type").getNodeValue(); if (EpcisConstants.VOCABULARY_TYPES.contains(vocabularyType)) { LOG.debug("processing " + i + ": '" + nodeName + "':" + vocabularyType + "."); handleVocabulary(session, vocabularyNode, vocabularyType); vocabularyCount++; if (vocabularyCount % 50 == 0) { session.flush(); session.clear(); } } } else if (!nodeName.equals("#text") && !nodeName.equals("#comment")) { throw new SAXException("Encountered unknown vocabulary '" + nodeName + "'."); } } } }