Example usage for org.xml.sax SAXException SAXException

List of usage examples for org.xml.sax SAXException SAXException

Introduction

In this page you can find the example usage for org.xml.sax SAXException SAXException.

Prototype

public SAXException(Exception e) 

Source Link

Document

Create a new SAXException wrapping an existing exception.

Usage

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.WsConfigParserHandler.java

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    super.endElement(uri, localName, qName);

    try {/*from ww  w. ja v a 2s  .  c  o m*/
        if (SCENARIO_ELMT.equals(qName)) {
            if (currScenario.isEmpty()) {
                throw new SAXException(StreamsResources.getStringFormatted(
                        StreamsResources.RESOURCE_BUNDLE_NAME, "WsConfigParserHandler.element.must.have.one",
                        SCENARIO_ELMT, STEP_ELMT, getLocationInfo()));
            }

            ((AbstractWsStream) currStream).addScenario(currScenario);
            currScenario = null;
        } else if (STREAM_ELMT.equals(qName)) {
            if (currStream instanceof AbstractWsStream) {
                if (CollectionUtils.isEmpty(((AbstractWsStream) currStream).getScenarios())) {
                    throw new SAXException(
                            StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                                    "WsConfigParserHandler.element.must.have.one", STREAM_ELMT, SCENARIO_ELMT,
                                    getLocationInfo()));
                }
            }
        } else if (STEP_ELMT.equals(qName)) {
            if (StringUtils.isEmpty(currStep.getRequest()) && StringUtils.isEmpty(currStep.getUrlStr())) {
                throw new SAXParseException(
                        StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                                "ConfigParserHandler.must.contain", STEP_ELMT, URL_ATTR, REQ_ELMT),
                        currParseLocation);
            }

            currScenario.addStep(currStep);
            currStep = null;
        } else if (REQ_ELMT.equals(qName)) {
            if (elementData != null) {
                currStep.setRequest(getElementData());
                elementData = null;
            }
        }
    } catch (SAXException exc) {
        throw exc;
    } catch (Exception e) {
        throw new SAXException(e.getLocalizedMessage() + getLocationInfo(), e);
    }
}

From source file:fr.lip6.move.coloane.projects.its.io.ModelHandler.java

/**
 * Parse a parameter description/*from   ww  w  . j  a va 2 s  .c  o m*/
 * @param attributes the attributes of the concept in XML
 * @throws SAXException any parse error
 */
private void handleParameter(Attributes attributes) throws SAXException {
    String name = attributes.getValue("name"); //$NON-NLS-1$
    int value = Integer.parseInt(attributes.getValue("value")); //$NON-NLS-1$
    int idParent = Integer.parseInt(attributes.getValue("parent")); //$NON-NLS-1$

    // Get parent with maximum safeguards
    ITypeDeclaration parent;
    try {
        parent = (ITypeDeclaration) ids.get(idParent);
    } catch (ClassCastException e) {
        throw new SAXException("Corrupted XML file, id " + idParent + " should refer to a type declaration");
    }
    if (parent == null) {
        throw new SAXException(
                "Corrupted XML file, Dangling parent type id " + idParent + " in parameter " + name);
    }
    // get the evaluation context
    IEvaluationContext params = parent.getParameters();
    IVariable var = new Variable(name);
    if (!params.containsVariable(var)) {
        logger.warning("Concept effective definition which should belong to CompositeType " + parent
                + " does not exist in the actual model file. Ignoring Concept setting.");
    } else {
        params.setVariableValue(var, value);
    }
}

From source file:net.pandoragames.far.ui.MimeConfParser.java

public void startElement(String uri, String localName, String qname, Attributes atts) throws SAXException {
    if (skipCurrentBranch > 0) {
        skipCurrentBranch++;// ww  w. jav  a2 s.  com
        return;
    }
    String tagName = tagName(localName, qname);
    if (MimeConfParser.ROOT_NODE_NAME.equals(tagName)) {
        typeStack.add(FileType.FILE);
    } else if (typeStack.size() == 0) {
        throw new SAXException("Illegal root element '" + tagName + "'");
    } else if (MimeConfParser.MIME_NODE_NAME.equals(tagName)) {
        String typeName = atts.getValue("", "name");
        if (MimeType.isValidMimeIdentifier(typeName)) {
            MimeType oldMime = (MimeType) MimeType.getType(typeName);
            if (oldMime != null) {
                MimeType.MimeRegistry.remove(oldMime);
                currentMime = new MimeType(typeName, oldMime.getParentType(), MimeType.MimeRegistry);
                currentMime.setPredefined(oldMime.isPredefined());
            } else {
                currentMime = new MimeType(typeName, typeStack.get(typeStack.size() - 1),
                        MimeType.MimeRegistry);
            }
            typeStack.add(currentMime);
            String encoding = atts.getValue("", "encoding");
            if (encoding != null) {
                try {
                    if (Charset.isSupported(encoding)) {
                        currentMime.setCharacterset(Charset.forName(encoding));
                    } else {
                        logger.warn("Unsupported character set '" + encoding + "' specified for mime type "
                                + typeName);
                    }
                } catch (IllegalCharsetNameException icnx) {
                    logger.warn("Illegal character set '" + encoding + "' specified for mime type " + typeName);
                }
            }
            String extensionList = atts.getValue("", "extensions");
            if (extensionList != null) {
                String[] extensions = extensionList.split("\\s");
                for (String ext : extensions)
                    currentMime.addExtension(ext);
            }
        } else {
            skipCurrentBranch = 1;
            logger.warn("Invalid mime type name: '" + typeName + "': skipping");
            return;
        }
    } else {
        String typeName = tagName.toUpperCase();
        FileType type = FileType.getType(typeName);
        if (type == null) {
            skipCurrentBranch = 1;
            logger.warn("Unknown tag name '" + tagName + "' encountered: skipping");
            return;
        }
        typeStack.add(type);
    }
}

From source file:com.netspective.commons.xdm.XdmHandler.java

public void startElement(String url, String localName, String qName, Attributes attributes)
        throws SAXException {
    //System.out.println(getStackDepthPrefix() + qName + " " + getAttributeNames(attributes));

    if (handleDefaultStartElement(url, localName, qName, attributes))
        return;/*from  w w  w . j a va 2  s  .c  om*/

    String elementName = qName.toLowerCase();
    XdmHandlerNodeStackEntry activeEntry = (XdmHandlerNodeStackEntry) getNodeStack().peek();

    if (!unmarshallingTemplate && handleTemplateStartElement(activeEntry, url, localName, qName, attributes))
        return;

    if (elementName.equals(getNodeIdentifiers().getIncludeElementName())) {
        try {
            includeInputSource(activeEntry, attributes);
            setInInclude(true);
            return;
        } catch (Exception e) {
            throw new SAXException(e);
        }
    }

    if (activeEntry.getInstance() instanceof XmlDataModelSchema.InputSourceTrackerListener) {
        try {
            ((XmlDataModelSchema.InputSourceTrackerListener) activeEntry.getInstance())
                    .setInputSourceTracker(getParseContext().getInputSrcTracker());
        } catch (Exception e) {
            throw new SAXException(e.getMessage() + " " + getStateText(), e);
        }
    }

    if (!getIgnoreStack().isEmpty() || activeEntry.getOptions().ignoreNestedElement(elementName)) {
        getIgnoreStack().push(elementName);
    } else {
        Object childInstance = null;
        XmlDataModelSchema activeSchema = activeEntry.getSchema();
        TemplateConsumerDefn templateConsumer = null;
        List templatesToConsume = null;

        try {
            String alternateClassName = attributes.getValue(NodeIdentifiers.ATTRNAME_ALTERNATE_CLASS_NAME);
            childInstance = activeSchema.createElement(((XdmParseContext) getParseContext()),
                    alternateClassName, activeEntry.getInstance(), elementName, false);

            boolean inAttrSetterText = childInstance == activeEntry.getInstance();

            if (childInstance != null && !inAttrSetterText) {
                // see if we have any templates that need to be applied
                if (childInstance instanceof TemplateConsumer) {
                    // check to see if we don't have our own alternate class but one of our the templates we're about to apply want to override our class
                    templateConsumer = ((TemplateConsumer) childInstance).getTemplateConsumerDefn();
                    templatesToConsume = templateConsumer.getTemplatesToApply(this, elementName, attributes);
                    if (alternateClassName == null) {
                        alternateClassName = templateConsumer.getAlternateClassName(this, templatesToConsume,
                                elementName, attributes);
                        if (alternateClassName != null)
                            childInstance = activeSchema.createElement(((XdmParseContext) getParseContext()),
                                    alternateClassName, activeEntry.getInstance(), elementName, false);
                    }
                }
            }

            if (childInstance == null) {
                getIgnoreStack().push(elementName);
                return;
            }

            if (inAttrSetterText) {
                inAttrSetterTextEntry = new XdmHandlerNodeStackEntry(elementName, attributes, childInstance);
                return;
            }
        } catch (DataModelException e) {
            log.error(e.getMessage() + " " + getStateText(), e);
            throw new SAXException(e.getMessage() + " " + getStateText(), e);
        }

        if (childInstance != null) {
            if (childInstance instanceof XmlDataModelSchema.InputSourceLocatorListener) {
                final Locator locator = getParseContext().getLocator();
                ((XmlDataModelSchema.InputSourceLocatorListener) childInstance)
                        .setInputSourceLocator(new InputSourceLocator(getParseContext().getInputSrcTracker(),
                                locator.getLineNumber(), locator.getColumnNumber()));
            }

            XdmHandlerNodeStackEntry childEntry = null;
            try {
                childEntry = new XdmHandlerNodeStackEntry(elementName, attributes, childInstance);
                getNodeStack().push(childEntry);

                // if we're already inside a template, then check to see if we have any attributes that need their
                // expressions replaced
                TemplateApplyContext activeApplyTemplateContext = activeEntry.getActiveApplyContext();
                if (activeApplyTemplateContext != null) {
                    TemplateApplyContext.StackEntry atcEntry = activeApplyTemplateContext.getActiveEntry();
                    if (atcEntry != null && atcEntry.isReplacementExprsFoundInAttrs())
                        attributes = atcEntry.getActiveTemplate()
                                .replaceAttributeExpressions(activeApplyTemplateContext);
                }

                // if the current element indicates the start of a template, apply it now
                if (templateConsumer != null && templatesToConsume != null) {
                    String[] attrNamesToSet = templateConsumer.getAttrNamesToApplyBeforeConsuming();
                    if (attrNamesToSet != null) {
                        for (int i = 0; i < attrNamesToSet.length; i++) {
                            String attrValue = attributes.getValue(attrNamesToSet[i]);
                            String lowerCaseAttrName = attrNamesToSet[i].toLowerCase();
                            childEntry.getSchema().setAttribute(((XdmParseContext) getParseContext()),
                                    childEntry.getInstance(), lowerCaseAttrName, attrValue, false);
                        }
                    }

                    templateConsumer.consume(this, templatesToConsume, elementName, attributes);
                }

                for (int i = 0; i < attributes.getLength(); i++) {
                    String origAttrName = attributes.getQName(i);
                    String lowerCaseAttrName = origAttrName.toLowerCase();
                    if (!childEntry.getOptions().ignoreAttribute(lowerCaseAttrName)
                            && !lowerCaseAttrName.equals(NodeIdentifiers.ATTRNAME_ALTERNATE_CLASS_NAME)
                            && !(getNodeStack().size() < 3 && lowerCaseAttrName
                                    .startsWith(NodeIdentifiers.ATTRNAMEPREFIX_NAMESPACE_BINDING))
                            && !(templateConsumer != null && templateConsumer.isTemplateAttribute(origAttrName))
                            && !(origAttrName.startsWith(getNodeIdentifiers().getXmlNameSpacePrefix())))

                        childEntry.getSchema().setAttribute(((XdmParseContext) getParseContext()),
                                childEntry.getInstance(), lowerCaseAttrName, attributes.getValue(i), false);
                }
            } catch (Exception e) {
                log.error(e.getMessage() + " " + getStateText(), e);
                throw new SAXException(e.getMessage() + " " + getStateText(), e);
            }

            try {
                activeEntry.getSchema().storeElement(((XdmParseContext) getParseContext()),
                        activeEntry.getInstance(), childEntry.getInstance(), elementName, false);
            } catch (DataModelException e) {
                log.error(e.getMessage() + " " + getStateText(), e);
                throw new SAXException(e.getMessage() + " " + getStateText(), e);
            }
        }
    }
}

From source file:com.trailmagic.image.util.ImagesParserImpl.java

private void processCharacterData(String characterData, String currentElt) throws SAXException {
    if (m_inImage) {
        if (m_inManifestation) {
            if ("name".equals(currentElt)) {
                m_manifestation.setName(characterData);
            } else if ("height".equals(currentElt)) {
                m_manifestation.setHeight(Integer.parseInt(characterData));
            } else if ("width".equals(currentElt)) {
                m_manifestation.setWidth(Integer.parseInt(characterData));
            } else if ("format".equals(currentElt)) {
                m_manifestation.setFormat(characterData);
            } else if ("original".equals(currentElt)) {
                m_manifestation.setOriginal(new Boolean(characterData).booleanValue());
            }//from  www  . j  a va  2  s  . c om
        } else if (m_inPhotoData) {
            Photo photo = (Photo) m_image;
            if ("roll-name".equals(currentElt)) {
                //                    photo.setRoll(getRollByName(characterData));
                // XXX: we should just use ImageGroup for this normally
                // so make sure the roll exists as an IG, then
                // XXX: borked if we don't have owner yet
                synchronized (hibernateTemplate) {
                    hibernateTemplate.flush();
                }

                m_photoRoll = imageGroupRepository.getRollByOwnerAndName(m_image.getOwner(),
                        characterData.trim());
                if (m_photoRoll == null) {
                    s_logger.info("No roll by the given name and owner "
                            + "found processing photo data, throwing" + " exception.");
                    throw new SAXException("Invalid or no roll name " + "specified: " + characterData
                            + " (for owner " + m_image.getOwner() + ")");
                }

            } else if ("frame-number".equals(currentElt)) {
                m_photoFrameNum = characterData;
            } else if ("notes".equals(currentElt)) {
                photo.setNotes(characterData);
            } else if ("capture-date".equals(currentElt)) {
                // XXX: use DateFormat
                SimpleDateFormat format = new SimpleDateFormat(DATE_PATTERN);
                try {
                    photo.setCaptureDate(format.parse(characterData));
                } catch (ParseException e) {
                    s_logger.warn("Error parsing capture-date: " + e.getMessage());
                }
            }
        } else {
            if ("name".equals(currentElt)) {
                m_image.setName(characterData);
            } else if ("display-name".equals(currentElt)) {
                m_image.setDisplayName(characterData);
            } else if ("caption".equals(currentElt)) {
                m_image.setCaption(characterData);
            } else if ("copyright".equals(currentElt)) {
                m_image.setCopyright(characterData);
            } else if ("creator".equals(currentElt)) {
                m_image.setCreator(characterData);
            } else if ("owner".equals(currentElt)) {
                String ownerName = characterData;
                m_image.setOwner(userRepository.getByScreenName(ownerName));
            } else if ("number".equals(currentElt)) {
                m_image.setNumber(new Integer(characterData));
            }
        }
    } else if (m_inRoll) {
        if ("name".equals(currentElt)) {
            m_roll.setName(characterData);
        } else if ("display-name".equals(currentElt)) {
            m_roll.setDisplayName(characterData);
        } else if ("description".equals(currentElt)) {
            m_roll.setDescription(characterData);
        } else if ("owner".equals(currentElt)) {
            String ownerName = characterData;
            m_roll.setOwner(userRepository.getByScreenName(ownerName));
            s_logger.debug("set roll " + m_roll.getName() + " owner to: " + m_roll.getOwner());
        }
    }
}

From source file:net.sf.ehcache.config.BeanHandler.java

/**
 * Attaches a child element to its parent.
 *///from  w  w  w  .j a  v  a  2s  . c o  m
private void addChild(final Object parent, final Object child, final String name) throws SAXException {
    try {
        // Look for an add<name> method on the parent
        final Method method = findSetMethod(parent.getClass(), "add", name);
        if (method != null) {
            method.invoke(parent, new Object[] { child });
        }
    } catch (final InvocationTargetException e) {
        final SAXException exc = new SAXException(getLocation() + ": Could not finish element <" + name + ">."
                + " Message was: " + e.getTargetException());
        throw exc;
    } catch (final Exception e) {
        throw new SAXException(getLocation() + ": Could not finish element <" + name + ">.");
    }
}

From source file:eu.annocultor.converter.Analyser.java

private void computeAndExportStatistics(SortedMap<String, Map<String, ValueCount>> statistics, File tmpDir)
        throws SAXException {

    Graph trg = new RdfGraph(null, task.getEnvironment(), "analyse", "", "");
    Namespaces namespaces = new Namespaces();

    /*//from  w  w  w .ja  va 2  s . co  m
     * Header
     */
    try {
        // top how many
        trg.add(new Triple(Namespaces.ANNOCULTOR_REPORT + "Summary",
                new Property(Namespaces.ANNOCULTOR_REPORT + "topCount"), new LiteralValue(MAX_VALUES + ""),
                null));
    } catch (Exception e) {
        throw new SAXException(e);
    }
    /*
     * Here we find top ten and form an RDF report
     */
    for (String propertyName : statistics.keySet()) {
        StringBuffer message = new StringBuffer(propertyName + " has ");
        Map<String, ValueCount> values = statistics.get(propertyName);

        // find top ten
        int totalRecords = 0;
        List<ValueCount> topTen = new LinkedList<ValueCount>();
        for (String value : values.keySet()) {
            ValueCount vc = values.get(value);
            topTen.add(vc);
            totalRecords += vc.count;
        }
        Collections.sort(topTen);

        // print
        String propertyUrl = Namespaces.ANNOCULTOR_REPORT + "__"
                + propertyName.replace('@', 'a').replaceAll(";", "/");

        int totalValues = values.size();
        message.append(totalValues + " values: ");
        int i = 0;
        boolean allUnique = false;
        try {
            for (Iterator<ValueCount> it = topTen.iterator(); it.hasNext() && i < MAX_VALUES;) {
                ValueCount count = it.next();
                if (i == 0) {
                    allUnique = (count.count == 1);
                    message.append(allUnique ? " ALL UNIQUE \n" : "\n");
                    // RDF report on tag
                    trg.add(new Triple(propertyUrl, Concepts.REPORTER.REPORT_NAME,
                            new LiteralValue(propertyName), null));
                    trg.add(new Triple(propertyUrl, Concepts.REPORTER.REPORT_LABEL,
                            new LiteralValue(
                                    Path.formatPath(new Path(propertyName.replace("*", "/")), namespaces)),
                            null));

                    trg.add(new Triple(propertyUrl, Concepts.REPORTER.REPORT_TOTAL_VALUES,
                            new LiteralValue("" + totalValues), null));

                    trg.add(new Triple(propertyUrl, Concepts.REPORTER.REPORT_ALL_UNIQUE,
                            new LiteralValue("" + allUnique), null));
                }
                message.append(count.value
                        + (allUnique ? "" : (" (" + count.count + ", " + count.percent(totalRecords) + "%)"))
                        + " \n");

                // RDF report on topTen
                trg.add(new Triple(
                        propertyUrl, Concepts.REPORTER.REPORT_VALUE, new LiteralValue(String.format("%07d", i)
                                + "," + count.count + "," + count.percent(totalRecords) + "," + count.value),
                        null));

                i++;
            }
        } catch (Exception e) {
            throw new SAXException(e);
        }
    }
    try {
        trg.endRdf();
        System.out.println("Statistic saved to " + trg.getFinalFile(1).getCanonicalPath());
        // transform results
        Helper.xsl(trg.getFinalFile(1),
                new File(trg.getFinalFile(1).getCanonicalPath().replaceFirst("\\.rdf", ".html")),
                this.getClass().getResourceAsStream("/AnalyserReportRDF2HTML.xsl"));
    } catch (Exception e) {
        System.out.println(e.getMessage());
        throw new SAXException(e);
    }

}

From source file:com.avalara.avatax.services.base.ser.BeanDeserializer.java

/**
 * Deserializer interface called on each child element encountered in
 * the XML stream.//from   ww w . jav a 2 s .  c  o  m
 * @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 {
    handleMixedContent();

    BeanPropertyDescriptor propDesc = null;
    FieldDesc fieldDesc = null;

    SOAPConstants soapConstants = context.getSOAPConstants();
    String encodingStyle = context.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;
    }

    boolean isArray = false;
    QName itemQName = null;
    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 (fieldDesc != null) {
            ElementDesc element = (ElementDesc) fieldDesc;
            isArray = element.isMaxOccursUnbounded();
            itemQName = element.getItemQName();
        }
    }

    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 || (((prevQName != null) && prevQName.equals(elemQName)
            && !(propDesc.isIndexed() || isArray) && getAnyPropertyDesc() != null))) {
        // try to put unknown elements into a SOAPElement property, if
        // appropriate
        prevQName = elemQName;
        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) {
        // The exception was changed to return null so deserialization doesn't fail if it gets an unexpected element.
        // This allows extending the api without breaking existing clients.  It's normal .Net behavior.
        return null;
        // No such field
        //            throw new SAXException(
        //                    Messages.getMessage("badElem00", javaType.getName(),
        //                                         localName));
    }

    prevQName = elemQName;
    // Get the child's xsi:type if available
    QName childXMLType = context.getTypeFromAttributes(namespace, localName, attributes);

    String href = attributes.getValue(soapConstants.getAttrHref());
    Class fieldType = propDesc.getType();

    // If no xsi:type or href, check the meta-data for the field
    if (childXMLType == null && fieldDesc != null && href == null) {
        childXMLType = fieldDesc.getXmlType();
        if (itemQName != null) {
            // This is actually a wrapped literal array and should be
            // deserialized with the ArrayDeserializer
            childXMLType = Constants.SOAP_ARRAY;
            fieldType = propDesc.getActualType();
        } else {
            childXMLType = fieldDesc.getXmlType();
        }
    }

    // Get Deserializer for child, default to using DeserializerImpl
    Deserializer dSer = getDeserializer(childXMLType, fieldType, 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() || isArray)) {
            if (!((dSer != null) && (dSer instanceof ArrayDeserializer))) {
                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()));
    }

    if (constructorToUse != null) {
        if (constructorTarget == null) {
            constructorTarget = new ConstructorTarget(constructorToUse, this);
        }
        dSer.registerValueTarget(constructorTarget);
    } else 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.

        // Register value target
        if ((itemQName != null || propDesc.isIndexed() || isArray) && !(dSer instanceof ArrayDeserializer)) {
            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:com.polarion.alm.ws.client.internal.encoding.BeanDeserializer.java

/**
 * Deserializer interface called on each child element encountered in the
 * XML stream.//from  w w  w.  ja  v  a 2  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 {
    handleMixedContent();

    BeanPropertyDescriptor propDesc = null;
    FieldDesc fieldDesc = null;

    SOAPConstants soapConstants = context.getSOAPConstants();
    String encodingStyle = context.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;
    }

    boolean isArray = false;
    QName itemQName = null;
    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 (fieldDesc != null) {
            ElementDesc element = (ElementDesc) fieldDesc;
            isArray = element.isMaxOccursUnbounded();
            itemQName = element.getItemQName();
        }
    }

    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 || (((prevQName != null) && prevQName.equals(elemQName)
            && !(propDesc.isIndexed() || isArray) && getAnyPropertyDesc() != null))) {
        // try to put unknown elements into a SOAPElement property, if
        // appropriate
        prevQName = elemQName;
        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) {
        log.warn(Messages.getMessage("badElem00", javaType.getName(), localName));
        return null;
    }

    prevQName = elemQName;
    // Get the child's xsi:type if available
    QName childXMLType = context.getTypeFromAttributes(namespace, localName, attributes);

    String href = attributes.getValue(soapConstants.getAttrHref());
    Class fieldType = propDesc.getType();

    // If no xsi:type or href, check the meta-data for the field
    if (childXMLType == null && fieldDesc != null && href == null) {
        childXMLType = fieldDesc.getXmlType();
        if (itemQName != null) {
            // This is actually a wrapped literal array and should be
            // deserialized with the ArrayDeserializer
            childXMLType = Constants.SOAP_ARRAY;
            fieldType = propDesc.getActualType();
        } else {
            childXMLType = fieldDesc.getXmlType();
        }
    }

    // Get Deserializer for child, default to using DeserializerImpl
    Deserializer dSer = getDeserializer(childXMLType, fieldType, 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() || isArray)) {
            if (!((dSer != null) && (dSer instanceof ArrayDeserializer))) {
                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()));
    }

    if (constructorToUse != null) {
        if (constructorTarget == null) {
            constructorTarget = new ConstructorTarget(constructorToUse, this);
        }
        dSer.registerValueTarget(constructorTarget);
    } else 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.

        // Register value target
        if ((itemQName != null || propDesc.isIndexed() || isArray) && !(dSer instanceof ArrayDeserializer)) {
            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:com.sshtools.daemon.configuration.ServerConfiguration.java

/**
 *
 *
 * @param uri//ww w.  j a v a 2 s .  c o  m
 * @param localName
 * @param qname
 *
 * @throws SAXException
 */
public void endElement(String uri, String localName, String qname) throws SAXException {
    if (currentElement != null) {
        if (!currentElement.equals(qname)) {
            throw new SAXException("Unexpected end element found <" + qname + ">");
        } else if (currentElement.equals("ServerConfiguration")) {
            currentElement = null;
        } else if (currentElement.equals("AuthenticationBanner") || currentElement.equals("ServerHostKey")
                || currentElement.equals("Subsystem") || currentElement.equals("MaxConnections")
                || currentElement.equals("MaxAuthentications") || currentElement.equals("ListenAddress")
                || currentElement.equals("Port") || currentElement.equals("CommandPort")
                || currentElement.equals("TerminalProvider") || currentElement.equals("AllowedAuthentication")
                || currentElement.equals("RequiredAuthentication") || currentElement.equals("AuthorizationFile")
                || currentElement.equals("UserConfigDirectory")
                || currentElement.equals("AllowTcpForwarding")) {
            currentElement = "ServerConfiguration";
        }
    } else {
        throw new SAXException("Unexpected end element <" + qname + "> found");
    }
}