Search in sources :

Example 41 with XMLStreamException

use of javax.xml.stream.XMLStreamException in project tdi-studio-se by Talend.

the class DeviceIdManager method createRegistrationEnvelope.

/**
     * This method helps to create a xml envelope needed for device registration request.
     * 
     * @param prefix Sets the required prefix for the device name.
     * @param applicationId app GUID
     * @param deviceName name of the device
     * @param password password for the device
     * @return xml envelope comprising device add request
     */
private static String createRegistrationEnvelope(String prefix, UUID applicationId, String deviceName, String password) {
    // The format of the envelope is the following:
    // <DeviceAddRequest>
    // <ClientInfo name="[app GUID]" version="1.0"/>
    // <Authentication>
    // <Membername>[prefix][device name]</Membername>
    // <Password>[device password]</Password>
    // </Authentication>
    // </DeviceAddRequest>
    // Instantiate the writer and write the envelope
    XMLOutputFactory factory = XMLOutputFactory.newInstance();
    StringWriter envelope = new StringWriter();
    XMLStreamWriter xml = null;
    try {
        xml = factory.createXMLStreamWriter(envelope);
        // Create the node
        xml.writeStartElement("DeviceAddRequest");
        // Write the ClientInfo node
        xml.writeStartElement("ClientInfo");
        xml.writeAttribute("name", applicationId.toString());
        xml.writeAttribute("version", "1.0");
        xml.writeEndElement();
        // Write the Authentication node
        xml.writeStartElement("Authentication");
        xml.writeStartElement("Membername");
        xml.writeCharacters(prefix + deviceName);
        xml.writeEndElement();
        xml.writeStartElement("Password");
        xml.writeCharacters(password);
        xml.writeEndElement();
        // </Authentication>
        xml.writeEndElement();
        // </DeviceAddRequest>
        xml.writeEndElement();
    } catch (XMLStreamException e) {
        Log.error(e.getMessage());
    } finally {
        if (xml != null) {
            try {
                xml.flush();
                xml.close();
            } catch (XMLStreamException e) {
                Log.error(e.getMessage());
            // Ignore if it is already closed
            }
        }
    }
    return envelope.toString();
}
Also used : XMLOutputFactory(javax.xml.stream.XMLOutputFactory) StringWriter(java.io.StringWriter) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter)

Example 42 with XMLStreamException

use of javax.xml.stream.XMLStreamException in project voltdb by VoltDB.

the class JDBCSQLXML method createStAXSource.

/**
     * Retrieves a new StAXSource for reading the XML value designated by this
     * SQLXML instance. <p>
     *
     * @param sourceClass The class of the source
     * @throws java.sql.SQLException if there is an error processing the XML
     *      value or if the given <tt>sourceClass</tt> is not supported.
     * @return a new StAXSource for reading the XML value designated by this
     *      SQLXML instance
     */
@SuppressWarnings("unchecked")
protected <T extends Source> T createStAXSource(Class<T> sourceClass) throws SQLException {
    StAXSource source = null;
    Constructor sourceCtor = null;
    Reader reader = null;
    XMLInputFactory factory = null;
    XMLEventReader eventReader = null;
    try {
        factory = XMLInputFactory.newInstance();
    } catch (FactoryConfigurationError ex) {
        throw Exceptions.sourceInstantiation(ex);
    }
    try {
        sourceCtor = (sourceClass == null) ? StAXSource.class.getConstructor(XMLEventReader.class) : sourceClass.getConstructor(XMLEventReader.class);
    } catch (SecurityException ex) {
        throw Exceptions.sourceInstantiation(ex);
    } catch (NoSuchMethodException ex) {
        throw Exceptions.sourceInstantiation(ex);
    }
    reader = getCharacterStreamImpl();
    try {
        eventReader = factory.createXMLEventReader(reader);
    } catch (XMLStreamException ex) {
        throw Exceptions.sourceInstantiation(ex);
    }
    try {
        source = (StAXSource) sourceCtor.newInstance(eventReader);
    } catch (SecurityException ex) {
        throw Exceptions.sourceInstantiation(ex);
    } catch (IllegalArgumentException ex) {
        throw Exceptions.sourceInstantiation(ex);
    } catch (IllegalAccessException ex) {
        throw Exceptions.sourceInstantiation(ex);
    } catch (InstantiationException ex) {
        throw Exceptions.sourceInstantiation(ex);
    } catch (InvocationTargetException ex) {
        throw Exceptions.sourceInstantiation(ex.getTargetException());
    } catch (ClassCastException ex) {
        throw Exceptions.sourceInstantiation(ex);
    }
    return (T) source;
}
Also used : Constructor(java.lang.reflect.Constructor) CharArrayReader(java.io.CharArrayReader) Reader(java.io.Reader) XMLEventReader(javax.xml.stream.XMLEventReader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) StAXSource(javax.xml.transform.stax.StAXSource) InvocationTargetException(java.lang.reflect.InvocationTargetException) XMLStreamException(javax.xml.stream.XMLStreamException) XMLEventReader(javax.xml.stream.XMLEventReader) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) FactoryConfigurationError(javax.xml.parsers.FactoryConfigurationError) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 43 with XMLStreamException

use of javax.xml.stream.XMLStreamException in project voltdb by VoltDB.

the class JDBCSQLXML method createStAXResult.

/**
     *  Retrieves a new DOMResult for setting the XML value designated by this
     *  SQLXML instance.
     *
     *  @param resultClass The class of the result, or null.
     *  @throws java.sql.SQLException if there is an error processing the XML
     *          value
     *  @return for setting the XML value designated by this SQLXML instance.
     */
@SuppressWarnings("unchecked")
protected <T extends Result> T createStAXResult(Class<T> resultClass) throws SQLException {
    StAXResult result = null;
    OutputStream outputStream = this.setBinaryStreamImpl();
    Constructor ctor;
    XMLOutputFactory factory;
    XMLStreamWriter xmlStreamWriter;
    try {
        factory = XMLOutputFactory.newInstance();
        xmlStreamWriter = factory.createXMLStreamWriter(outputStream);
        if (resultClass == null) {
            result = new StAXResult(xmlStreamWriter);
        } else {
            ctor = resultClass.getConstructor(XMLStreamWriter.class);
            result = (StAXResult) ctor.newInstance(xmlStreamWriter);
        }
    } catch (SecurityException ex) {
        throw Exceptions.resultInstantiation(ex);
    } catch (IllegalArgumentException ex) {
        throw Exceptions.resultInstantiation(ex);
    } catch (IllegalAccessException ex) {
        throw Exceptions.resultInstantiation(ex);
    } catch (InvocationTargetException ex) {
        throw Exceptions.resultInstantiation(ex.getTargetException());
    } catch (FactoryConfigurationError ex) {
        throw Exceptions.resultInstantiation(ex);
    } catch (InstantiationException ex) {
        throw Exceptions.resultInstantiation(ex);
    } catch (NoSuchMethodException ex) {
        throw Exceptions.resultInstantiation(ex);
    } catch (XMLStreamException ex) {
        throw Exceptions.resultInstantiation(ex);
    }
    return (T) result;
}
Also used : StAXResult(javax.xml.transform.stax.StAXResult) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) Constructor(java.lang.reflect.Constructor) GZIPOutputStream(java.util.zip.GZIPOutputStream) ClosableByteArrayOutputStream(org.hsqldb_voltpatches.lib.ClosableByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) InvocationTargetException(java.lang.reflect.InvocationTargetException) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) FactoryConfigurationError(javax.xml.parsers.FactoryConfigurationError)

Example 44 with XMLStreamException

use of javax.xml.stream.XMLStreamException in project OpenAttestation by OpenAttestation.

the class TAHelper method verifyQuoteAndGetPcr.

// BUG #497 need to rewrite this to return List<Pcr> ... the Pcr.equals()  does same as (actually more than) IManifest.verify() because Pcr ensures the index is the same and IManifest does not!  and also it is less redundant, because this method returns Map< pcr index as string, manifest object containing pcr index and value >  
private HashMap<String, PcrManifest> verifyQuoteAndGetPcr(String sessionId, String eventLog) {
    //Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    HashMap<String, PcrManifest> pcrMp = new HashMap<String, PcrManifest>();
    String setUpFile;
    log.info("verifyQuoteAndGetPcr for session {}", sessionId);
    //log.info( "Command: {}",command);
    //List<String> result = CommandUtil.runCommand(command,true,"VerifyQuote");
    String certFileName = aikverifyhome + File.separator + getCertFileName(sessionId);
    //2. verification
    try {
        setUpFile = ResourceFinder.getFile("attestation-service.properties").getAbsolutePath();
        String fileLocation = setUpFile.substring(0, setUpFile.indexOf("attestation-service.properties"));
        String PrivacyCaCertFileName = "PrivacyCA.cer";
        //X509Certificate machineCertificate = pemToX509Certificate(certFileName);
        //X509Certificate machineCertificate = certFromFile(certFileName);
        certFromFile(certFileName);
        //X509Certificate pcaCert = certFromFile(fileLocation + PrivacyCaCertFileName);
        certFromFile(fileLocation + PrivacyCaCertFileName);
        log.info("passed the verification");
    } catch (Exception e) {
        log.error("Machine certificate was not signed by the privacy CA." + e.toString());
        throw new RuntimeException(e);
    }
    String nonceFileName = aikverifyhome + File.separator + getNonceFileName(sessionId);
    String quoteFileName = aikverifyhome + File.separator + getQuoteFileName(sessionId);
    String rsaPubkeyFileName = aikverifyhome + File.separator + getRSAPubkeyFileName(sessionId);
    List<String> result = aikqverify(nonceFileName, rsaPubkeyFileName, quoteFileName);
    for (String pcrString : result) {
        String[] parts = pcrString.trim().split(" ");
        if (parts.length == 2) {
            String pcrNumber = parts[0].trim().replaceAll(pcrNumberUntaint, "").replaceAll("\n", "");
            String pcrValue = parts[1].trim().replaceAll(pcrValueUntaint, "").replaceAll("\n", "");
            boolean validPcrNumber = pcrNumberPattern.matcher(pcrNumber).matches();
            boolean validPcrValue = pcrValuePattern.matcher(pcrValue).matches();
            if (validPcrNumber && validPcrValue) {
                log.info("Result PCR " + pcrNumber + ": " + pcrValue);
                pcrMp.put(pcrNumber, new PcrManifest(Integer.parseInt(pcrNumber), pcrValue));
            }
        } else {
            log.warn("Result PCR invalid");
        }
    }
    //</modules>
    if (eventLog != null) {
        log.debug("About to start processing eventLog");
        try {
            XMLInputFactory xif = XMLInputFactory.newInstance();
            StringReader sr = new StringReader(eventLog);
            XMLStreamReader reader = xif.createXMLStreamReader(sr);
            int extendedToPCR = -1;
            String digestValue = "";
            String componentName = "";
            while (reader.hasNext()) {
                if (reader.getEventType() == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equalsIgnoreCase("module")) {
                    reader.next();
                    // Get the PCR Number to which the module is extended to
                    if (reader.getLocalName().equalsIgnoreCase("pcrNumber")) {
                        extendedToPCR = Integer.parseInt(reader.getElementText());
                    }
                    reader.next();
                    // Get the Module name 
                    if (reader.getLocalName().equalsIgnoreCase("name")) {
                        componentName = reader.getElementText();
                    }
                    reader.next();
                    // Get the Module hash value 
                    if (reader.getLocalName().equalsIgnoreCase("value")) {
                        digestValue = reader.getElementText();
                    }
                    boolean useHostSpecificDigest = false;
                    if (ArrayUtils.contains(openSourceHostSpecificModules, componentName)) {
                        useHostSpecificDigest = true;
                    }
                    // Attach the PcrEvent logs to the corresponding pcr indexes.
                    // Note: Since we will not be processing the even logs for 17 & 18, we will ignore them for now.
                    Measurement m = convertHostTpmEventLogEntryToMeasurement(extendedToPCR, componentName, digestValue, useHostSpecificDigest);
                    if (pcrMp.containsKey(String.valueOf(extendedToPCR))) {
                        if (pcrMp.get(String.valueOf(extendedToPCR)).containsPcrEventLog(extendedToPCR)) {
                            pcrMp.get(String.valueOf(extendedToPCR)).getPcrEventLog(extendedToPCR).getEventLog().add(m);
                        } else {
                            PcrIndex pcrIndex = new PcrIndex(extendedToPCR);
                            ArrayList<Measurement> list = new ArrayList<Measurement>();
                            list.add(m);
                            PcrEventLog eventlog = new PcrEventLog(pcrIndex, list);
                            pcrMp.get(String.valueOf(extendedToPCR)).setPcrEventLog(eventlog);
                        //pcrMf.setPcrEventLog(new PcrEventLog(new PcrIndex(extendedToPCR), list));
                        }
                    }
                }
                reader.next();
            }
        } catch (FactoryConfigurationError | XMLStreamException | NumberFormatException ex) {
            //log.error(ex.getMessage(), ex); 
            throw new IllegalStateException("Invalid measurement log", ex);
        }
    }
    return pcrMp;
}
Also used : Measurement(com.intel.mtwilson.util.model.Measurement) XMLStreamReader(javax.xml.stream.XMLStreamReader) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PcrEventLog(com.intel.mtwilson.util.model.PcrEventLog) ASException(com.intel.mountwilson.as.common.ASException) KeyStoreException(java.security.KeyStoreException) XMLStreamException(javax.xml.stream.XMLStreamException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) CertificateException(java.security.cert.CertificateException) UnknownHostException(java.net.UnknownHostException) PcrIndex(com.intel.mtwilson.util.model.PcrIndex) XMLStreamException(javax.xml.stream.XMLStreamException) PcrManifest(com.intel.mountwilson.manifest.data.PcrManifest) FactoryConfigurationError(javax.xml.stream.FactoryConfigurationError) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 45 with XMLStreamException

use of javax.xml.stream.XMLStreamException in project midpoint by Evolveum.

the class Validator method validate.

public void validate(InputStream inputStream, OperationResult validatorResult, String objectResultOperationName) {
    XMLStreamReader stream = null;
    try {
        Map<String, String> rootNamespaceDeclarations = new HashMap<String, String>();
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        stream = xmlInputFactory.createXMLStreamReader(inputStream);
        int eventType = stream.nextTag();
        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (!QNameUtil.match(stream.getName(), SchemaConstants.C_OBJECTS)) {
                // This has to be an import file with a single objects. Try
                // to process it.
                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);
                EventResult cont = null;
                try {
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations, validatorResult);
                } catch (RuntimeException e) {
                    // Make sure that unexpected error is recorded.
                    objectResult.recordFatalError(e);
                    throw e;
                }
                if (!cont.isCont()) {
                    String message = null;
                    if (cont.getReason() != null) {
                        message = cont.getReason();
                    } else {
                        message = "Object validation failed (no reason given)";
                    }
                    if (objectResult.isUnknown()) {
                        objectResult.recordFatalError(message);
                    }
                    validatorResult.recordFatalError(message);
                    return;
                }
                // return to avoid processing objects in loop
                validatorResult.computeStatus("Validation failed", "Validation warnings");
                return;
            }
            // Extract root namespace declarations
            for (int i = 0; i < stream.getNamespaceCount(); i++) {
                rootNamespaceDeclarations.put(stream.getNamespacePrefix(i), stream.getNamespaceURI(i));
            }
        } else {
            throw new SystemException("StAX Malfunction?");
        }
        while (stream.hasNext()) {
            eventType = stream.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                OperationResult objectResult = validatorResult.createSubresult(objectResultOperationName);
                progress++;
                objectResult.addContext(OperationResult.CONTEXT_PROGRESS, progress);
                EventResult cont = null;
                try {
                    // Read and validate individual object from the stream
                    cont = readFromStreamAndValidate(stream, objectResult, rootNamespaceDeclarations, validatorResult);
                } catch (RuntimeException e) {
                    if (objectResult.isUnknown()) {
                        // Make sure that unexpected error is recorded.
                        objectResult.recordFatalError(e);
                    }
                    throw e;
                }
                if (objectResult.isError()) {
                    errors++;
                }
                objectResult.cleanupResult();
                validatorResult.summarize();
                if (cont.isStop()) {
                    if (cont.getReason() != null) {
                        validatorResult.recordFatalError("Processing has been stopped: " + cont.getReason());
                    } else {
                        validatorResult.recordFatalError("Processing has been stopped");
                    }
                    // processed
                    return;
                }
                if (!cont.isCont()) {
                    if (stopAfterErrors > 0 && errors >= stopAfterErrors) {
                        validatorResult.recordFatalError("Too many errors (" + errors + ")");
                        return;
                    }
                }
            }
        }
    } catch (XMLStreamException ex) {
        // validatorResult.recordFatalError("XML parsing error: " +
        // ex.getMessage()+" on line "+stream.getLocation().getLineNumber(),ex);
        validatorResult.recordFatalError("XML parsing error: " + ex.getMessage(), ex);
        if (handler != null) {
            handler.handleGlobalError(validatorResult);
        }
        return;
    }
    // Error count is sufficient. Detailed messages are in subresults
    validatorResult.computeStatus(errors + " errors, " + (progress - errors) + " passed");
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) SystemException(com.evolveum.midpoint.util.exception.SystemException) XMLStreamException(javax.xml.stream.XMLStreamException) HashMap(java.util.HashMap) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Aggregations

XMLStreamException (javax.xml.stream.XMLStreamException)442 XMLStreamReader (javax.xml.stream.XMLStreamReader)137 IOException (java.io.IOException)126 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)75 XMLInputFactory (javax.xml.stream.XMLInputFactory)69 InputStream (java.io.InputStream)66 Document (org.w3c.dom.Document)36 JAXBException (javax.xml.bind.JAXBException)35 Fault (org.apache.cxf.interceptor.Fault)34 Element (org.w3c.dom.Element)32 StringReader (java.io.StringReader)30 XMLEvent (javax.xml.stream.events.XMLEvent)28 DOMSource (javax.xml.transform.dom.DOMSource)27 ByteArrayInputStream (java.io.ByteArrayInputStream)25 ArrayList (java.util.ArrayList)23 QName (javax.xml.namespace.QName)23 XMLOutputFactory (javax.xml.stream.XMLOutputFactory)23 Node (org.w3c.dom.Node)22 StringWriter (java.io.StringWriter)21 XMLEventReader (javax.xml.stream.XMLEventReader)20