Example usage for org.xml.sax SAXParseException SAXParseException

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

Introduction

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

Prototype

public SAXParseException(String message, Locator locator, Exception e) 

Source Link

Document

Wrap an existing exception in a SAXParseException.

Usage

From source file:com.moviejukebox.tools.DOMHelper.java

/**
 * Get a DOM document from the supplied file
 *
 * @param xmlFile/*  w w  w  . j  a  va2  s  .c om*/
 * @return
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public static Document getDocFromFile(File xmlFile)
        throws ParserConfigurationException, SAXException, IOException {
    URL url = xmlFile.toURI().toURL();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc;

    // Custom error handler
    db.setErrorHandler(new SaxErrorHandler());

    try (InputStream in = url.openStream()) {
        doc = db.parse(in);
    } catch (SAXParseException ex) {
        if (FilenameUtils.isExtension(xmlFile.getName().toLowerCase(), "xml")) {
            throw new SAXParseException("Failed to process file as XML", null, ex);
        }
        // Try processing the file a different way
        doc = null;
    }

    if (doc == null) {
        try (
                // try wrapping the file in a root
                StringReader sr = new StringReader(wrapInXml(FileTools.readFileToString(xmlFile)))) {
            doc = db.parse(new InputSource(sr));
        }
    }

    if (doc != null) {
        doc.getDocumentElement().normalize();
    }

    return doc;
}

From source file:jcurl.core.io.SetupSaxDeSer.java

public void endElement(String uri, String localName, String qName) throws SAXException {
    final String elem = qName;
    elems.pop();//from w  w w . j  a  v a  2s. co m
    final String txt = buf.toString().trim();
    switch (elems.size() + 1) {
    case 1:
        if ("jcurl".equals(elem))
            ;
        else
            break;
        return;
    case 2:
        if ("setup".equals(elem))
            setup.freeze();
        else
            break;
        return;
    case 3:
        if ("model".equals(elem))
            try {
                setup.addModel(modelClass, modelProps);
            } catch (InstantiationException e) {
                log.warn("error in [" + elems + "]", e);
                error(new SAXParseException("error in [" + elems + "]", locator, e));
            } catch (IllegalAccessException e) {
                log.warn("error in [" + elems + "]", e);
                error(new SAXParseException("error in [" + elems + "]", locator, e));
            }
        else
            break;
        return;
    case 4:
        if ("rock".equals(elem))
            currRock = null;
        else
            break;
        return;
    }
}

From source file:io.fares.bind.xjc.plugins.substitution.SubstitutionPlugin.java

@Override
public boolean run(Outline outline, Options opt, ErrorHandler errorHandler) throws SAXException {

    for (ClassOutline classOutline : outline.getClasses()) {
        // now in part 2 of the transformation we need to traverse the generated field declarations
        // find our plugin customization and swap @XmlElement for @XmlElementRef
        for (FieldOutline fieldOutline : classOutline.getDeclaredFields()) {

            // REVIEW AV: This does not feel quite right. You create a CElementPropertyInfo property
            // but then hack it to use another annotation. This is not good since your generated code does
            // not represent your model anymore. This may cause problem to other tools/plugins.
            CPropertyInfo propertyInfo = fieldOutline.getPropertyInfo();

            // check field property customization
            boolean hasHeadRef = Customisation.hasCustomizationsInProperty(propertyInfo,
                    SUBSTITUTION_HEAD_REF_NAME);
            // FIXME should not need to do this here but customization gets mixed up when we replace the Ref with
            //       Element field in the model transformation.
            hasHeadRef = Customisation.hasCustomizationsInProperty(propertyInfo, SUBSTITUTION_HEAD_NAME)
                    || hasHeadRef;/*w w w.  j  av a 2s  . c  o  m*/

            // check if the referenced type is the subsctitution head
            // FIXME currently only able to add the customization on the complexType and not the element
            boolean hasHead = false;

            for (CTypeInfo typeInfo : propertyInfo.ref()) {
                hasHead = hasHead || Customisation.hasCustomizationsInType(typeInfo, SUBSTITUTION_HEAD_NAME);
            }

            if (hasHeadRef || hasHead) {

                // can be changed to containsKey and getKey
                for (JFieldVar field : classOutline.ref.fields().values()) {

                    if (propertyInfo.getName(false).equals(field.name())) {

                        JFieldVar jFieldVar = classOutline.ref.fields().get(propertyInfo.getName(false));

                        for (JAnnotationUse annotation : jFieldVar.annotations()) {
                            JClass acl = annotation.getAnnotationClass();
                            if (XmlElement.class.getName().equals(acl.fullName())) {
                                try {
                                    // swap XmlElement for XmlElementRef
                                    FieldUtils.writeField(annotation, "clazz",
                                            outline.getCodeModel().ref(XmlElementRef.class), true);
                                    // TODO inspect params to make sure we don't transfer [nillable|defaultValue]
                                } catch (IllegalAccessException e) {
                                    errorHandler.error(new SAXParseException(
                                            "The substitution plugin is prevented from modifying an inaccessible field in the XJC model (generation time only). Please ensure your security manager is configured correctly.",
                                            propertyInfo.getLocator(), e));
                                    return false;
                                } catch (IllegalArgumentException e) {
                                    errorHandler.error(new SAXParseException(
                                            "The substitution plugin encountered an internal error extracting the generated field details.",
                                            propertyInfo.getLocator(), e));
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    return true;
}

From source file:org.esco.grouper.parsing.SGSParsingUtil.java

/**
 * Recieves the notification of the start of an element.
 * @param uri the Namespace URI, or the empty string if the
 * element has no Namespace URI or if Namespace
 * processing is not being performed./*  ww w.  j av  a  2  s.c om*/
 * @param localName the local name (without prefix), or the
 * empty string if Namespace processing is not being
 * performed.
 * @param qName the qualified name (with prefix), or the
 * empty string if qualified names are not available.
 * @param atts the attributes attached to the element.  If
 * there are no attributes, it shall be an empty
 * Attributes object.  The value of this object after
 * startElement returns is undefined.
 * @throws org.xml.sax.SAXException any SAX exception, possibly
 * wrapping another exception.
 * @see org.xml.sax.ContentHandler
 * #startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
 */
@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes atts)
        throws SAXException {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Opening TAG = " + localName);
    }

    attributeHandler.reset();
    attributeHandler.handleAttributes(locator, atts);
    try {
        if (USER_TAG.equals(localName)) {
            // User for the Grouper sessions.
            LOGGER.debug("The user " + attributeHandler.getUid() + " will be used for the Groupers sessions.");
            grouperSessionUtil.setSubjectId(attributeHandler.getUid());

        } else if (DEL_EMPTY_FOLD_TAG.equals(localName)) {

            // Deletion of the empty folders.
            LOGGER.debug("Setting delete empty folders to: " + attributeHandler.getValue());
            grouperDAO.setDeleteEmptyFolders(attributeHandler.getValue());

        } else if (DEL_EMPTY_GROUPS_TAG.equals(localName)) {

            // Deletion of the empty groups.
            LOGGER.debug("Setting delete empty groups to: " + attributeHandler.getValue());
            grouperDAO.setDeleteEmptyGroups(attributeHandler.getValue());

        } else if (FORCE_PRIV_TAG.equals(localName)) {

            // Force privileges flag.
            LOGGER.debug("Setting force privileges to: " + attributeHandler.getValue());
            grouperDAO.setForcePrivileges(attributeHandler.getValue());

        } else if (TEMPLATE_ELT_TAG.equals(localName)) {

            // Definition of a template element.
            handleTemplateElement();

        } else if (PRIVILEGE_TAG.equals(localName)) {

            // Definition of an administration privilege.
            handlePrivileges();

        } else if (MEMBERS_TAG.equalsIgnoreCase(localName)) {
            // Definition of the members of a group.
            handleMembersRule();
        } else if (MEMBER_OF_TAG.equals(localName)) {

            // Definition of a membership of a group.
            handleMembership();
        } else if (FOLDER_TAG.equals(localName) || FOLDER_TEMPL_TAG.equals(localName)
                || GROUP_TAG.equals(localName) || GROUP_TEMPL_TAG.equals(localName)) {

            // Definition of a group, a template group, a folder or a template folder.
            handleGroupOrFolder(localName);
        }
    } catch (UnknownTemplateElementTempateElement e) {

        // Error on a template element.
        final String msg = "Error while parsing a string with template element - Tag: " + localName
                + " - line: " + locator.getLineNumber();
        LOGGER.fatal(msg);
        throw new SAXParseException(msg, locator, e);
    }
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java

private Property processPropertyValue(String name, String type, String value, String valType)
        throws SAXParseException {
    Object propValue = value;/*  w w w .j av  a2s. com*/

    if ("INTEGER".equalsIgnoreCase(type)) {
        Integer num = Integer.parseInt(generateFromRange(type, value));
        propValue = (int) TNT4JSimulator.varyValue(num.intValue());
    } else if ("LONG".equalsIgnoreCase(type)) {
        Long num = Long.parseLong(generateFromRange(type, value));
        propValue = (long) TNT4JSimulator.varyValue(num.longValue());
    } else if ("DECIMAL".equalsIgnoreCase(type)) {
        Double num = Double.parseDouble(generateFromRange(type, value));
        propValue = TNT4JSimulator.varyValue(num.doubleValue());
    } else if ("BOOLEAN".equalsIgnoreCase(type)) {
        if (StringUtils.isEmpty(valType))
            valType = "boolean";
        propValue = Boolean.parseBoolean(value);
    } else if ("TIMESTAMP".equalsIgnoreCase(type)) {
        try {
            try {
                propValue = new UsecTimestamp((long) TNT4JSimulator.varyValue(Long.parseLong(value)));
            } catch (NumberFormatException e) {
                propValue = new UsecTimestamp(value, "yyyy-MM-dd HH:mm:ss.SSSSSS", (String) null);
            }
        } catch (Exception e) {
            throw new SAXParseException("Failed parsing timestamp", saxLocator, e);
        }
        if (StringUtils.isEmpty(valType))
            valType = ValueTypes.VALUE_TYPE_TIMESTAMP;
    } else if ("STRING".equalsIgnoreCase(type)) {
        propValue = value.toString();
    } else if (!StringUtils.isEmpty(type)) {
        throw new SAXParseException("<" + SIM_XML_PROP + ">: invalid type: " + type, saxLocator);
    }
    return new Property(name, propValue, valType);
}

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

/**
 * Process parser {@code <reference>} element, e.g., pre-parser.
 *
 * @param attrs//  w w  w  . j  a  v  a  2 s  . co  m
 *            List of element attributes
 *
 * @throws SAXParseException
 *             if error occurs parsing element
 */
private void processParserReference(Attributes attrs) throws SAXParseException {
    String refObjName = getRefObjectNameFromAttr(attrs);
    notEmpty(refObjName, REF_ELMT, NAME_ATTR);
    Object refObject = findReference(refObjName);
    try {
        currParser.addReference(refObject);
    } catch (IllegalStateException exc) {
        throw new SAXParseException(
                StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "ConfigParserHandler.could.not.add.stream.reference", currStream.getName(), refObjName),
                currParseLocation, exc);
    }

}

From source file:nl.nn.adapterframework.validation.xerces_2_11.XMLSchemaFactory.java

public Schema newSchema(Source[] schemas) throws SAXException {

    // this will let the loader store parsed Grammars into the pool.
    XMLGrammarPoolImplExtension pool = new XMLGrammarPoolImplExtension();
    fXMLGrammarPoolWrapper.setGrammarPool(pool);

    XMLInputSource[] xmlInputSources = new XMLInputSource[schemas.length];
    InputStream inputStream;//from  ww w .  j a v a 2s. c o m
    Reader reader;
    for (int i = 0; i < schemas.length; ++i) {
        Source source = schemas[i];
        if (source instanceof StreamSource) {
            StreamSource streamSource = (StreamSource) source;
            String publicId = streamSource.getPublicId();
            String systemId = streamSource.getSystemId();
            inputStream = streamSource.getInputStream();
            reader = streamSource.getReader();
            XMLInputSource xmlInputSource = new XMLInputSource(publicId, systemId, null);
            xmlInputSource.setByteStream(inputStream);
            xmlInputSource.setCharacterStream(reader);
            xmlInputSources[i] = xmlInputSource;
        } else if (source instanceof SAXSource) {
            SAXSource saxSource = (SAXSource) source;
            InputSource inputSource = saxSource.getInputSource();
            if (inputSource == null) {
                throw new SAXException(JAXPValidationMessageFormatter
                        .formatMessage(fXMLSchemaLoader.getLocale(), "SAXSourceNullInputSource", null));
            }
            xmlInputSources[i] = new SAXInputSource(saxSource.getXMLReader(), inputSource);
        } else if (source instanceof DOMSource) {
            DOMSource domSource = (DOMSource) source;
            Node node = domSource.getNode();
            String systemID = domSource.getSystemId();
            xmlInputSources[i] = new DOMInputSource(node, systemID);
        }
        //            else if (source instanceof StAXSource) {
        //                StAXSource staxSource = (StAXSource) source;
        //                XMLEventReader eventReader = staxSource.getXMLEventReader();
        //                if (eventReader != null) {
        //                    xmlInputSources[i] = new StAXInputSource(eventReader);
        //                }
        //                else {
        //                    xmlInputSources[i] = new StAXInputSource(staxSource.getXMLStreamReader());
        //                }
        //            }
        else if (source == null) {
            throw new NullPointerException(JAXPValidationMessageFormatter
                    .formatMessage(fXMLSchemaLoader.getLocale(), "SchemaSourceArrayMemberNull", null));
        } else {
            throw new IllegalArgumentException(
                    JAXPValidationMessageFormatter.formatMessage(fXMLSchemaLoader.getLocale(),
                            "SchemaFactorySourceUnrecognized", new Object[] { source.getClass().getName() }));
        }
    }

    try {
        fXMLSchemaLoader.loadGrammar(xmlInputSources);
    } catch (XNIException e) {
        // this should have been reported to users already.
        throw Util.toSAXException(e);
    } catch (IOException e) {
        // this hasn't been reported, so do so now.
        SAXParseException se = new SAXParseException(e.getMessage(), null, e);
        if (fErrorHandler != null) {
            fErrorHandler.error(se);
        }
        throw se; // and we must throw it.
    }

    // Clear reference to grammar pool.
    fXMLGrammarPoolWrapper.setGrammarPool(null);

    // Select Schema implementation based on grammar count.
    final int grammarCount = pool.getGrammarCount();
    AbstractXMLSchema schema = null;
    if (fUseGrammarPoolOnly) {
        throw new NotImplementedException("fUseGrammarPoolOnly");
        //            if (grammarCount > 1) {
        //                schema = new XMLSchemaHack(new ReadOnlyGrammarPool(pool));
        //            }
        //            else if (grammarCount == 1) {
        //                Grammar[] grammars = pool.retrieveInitialGrammarSet(XMLGrammarDescription.XML_SCHEMA);
        //                schema = new XMLSchemaHack(grammars[0]);
        //            }
        //            else {
        //                schema = new XMLSchemaHack();
        //            }
    } else {
        schema = new XMLSchema(new ReadOnlyGrammarPool(pool), false);
    }
    propagateFeatures(schema);
    return schema;
}

From source file:org.apache.cocoon.template.instruction.Call.java

public Call(ParsingContext parsingContext, StartElement raw, Attributes attrs, Stack stack)
        throws SAXException {
    super(raw);/*from   w  w  w .  j  a va2s  . c  om*/
    this.parameters = new HashMap();
    Locator locator = getLocation();

    String name = attrs.getValue("macro");
    if (name == null) {
        throw new SAXParseException("if: \"test\" is required", locator, null);
    }
    this.macro = parsingContext.getStringTemplateParser().compileExpr(name, "call: \"macro\": ", locator);

    String namespace = StringUtils.defaultString(attrs.getValue("targetNamespace"));
    this.targetNamespace = parsingContext.getStringTemplateParser().compileExpr(namespace,
            "call: \"targetNamespace\": ", locator);
}

From source file:org.apache.cocoon.template.instruction.Call.java

public Event execute(XMLConsumer consumer, ExpressionContext expressionContext,
        ExecutionContext executionContext, MacroContext macroContext, Event startEvent, Event endEvent)
        throws SAXException {
    Map attributeMap = new HashMap();
    Iterator i = parameters.keySet().iterator();
    while (i.hasNext()) {
        String parameterName = (String) i.next();
        ParameterInstance parameter = (ParameterInstance) parameters.get(parameterName);
        Object parameterValue = parameter.getValue(expressionContext);
        attributeMap.put(parameterName, parameterValue);
    }/*from   w  w  w .j a  va  2  s  .  c  om*/
    ExpressionContext localExpressionContext = new ExpressionContext(expressionContext);
    HashMap macro = new HashMap();
    macro.put("body", this.body);
    macro.put("arguments", attributeMap);
    localExpressionContext.put("macro", macro);

    Define definition = resolveMacroDefinition(expressionContext, executionContext);
    Iterator iter = definition.getParameters().entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry e = (Map.Entry) iter.next();
        String key = (String) e.getKey();
        Parameter startParam = (Parameter) e.getValue();
        Object default_ = startParam.getDefaultValue();
        Object val = attributeMap.get(key);
        if (val == null) {
            val = default_;
        }
        localExpressionContext.put(key, val);
    }

    Event macroBodyStart = getNext();
    Event macroBodyEnd = null;

    if (getEndInstruction() != null)
        macroBodyEnd = getEndInstruction();
    else
        macroBodyEnd = getStartElement().getEndElement();

    MacroContext newMacroContext = new MacroContext(definition.getQname(), macroBodyStart, macroBodyEnd);
    try {
        Invoker.execute(consumer, localExpressionContext, executionContext, newMacroContext,
                definition.getBody(), definition.getEndInstruction());
    } catch (SAXParseException exc) {
        throw new SAXParseException(newMacroContext.getMacroQName() + ": " + exc.getMessage(), location, exc);
    }

    if (getEndInstruction() != null)
        return getEndInstruction().getNext();
    else
        return getStartElement().getEndElement().getNext();
}

From source file:org.apache.cocoon.template.instruction.Call.java

/**
 * @param executionContext/*from w  w w. j  ava 2  s .co  m*/
 * @throws SAXParseException
 */
private Define resolveMacroDefinition(ExpressionContext expressionContext, ExecutionContext executionContext)
        throws SAXParseException {
    if (this.macro instanceof Define)
        return (Define) macro;

    Object macroName;
    Object namespace;
    JXTExpression macroNameExpression = (JXTExpression) macro;
    try {
        macroName = macroNameExpression.getValue(expressionContext);
        namespace = targetNamespace.getValue(expressionContext);
        if (namespace == null)
            namespace = "";
    } catch (Exception e) {
        throw new SAXParseException(e.getMessage(), getLocation(), e);
    } catch (Error err) {
        throw new SAXParseException(err.getMessage(), getLocation(), new ErrorHolder(err));
    }
    Define definition = (Define) executionContext.getDefinitions()
            .get("{" + namespace.toString() + "}" + macroName.toString());
    if (definition == null)
        throw new SAXParseException("no macro definition: " + macroName, getLocation());
    return definition;
}