Search in sources :

Example 6 with XMLStreamReader

use of javax.xml.stream.XMLStreamReader 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 7 with XMLStreamReader

use of javax.xml.stream.XMLStreamReader in project Activiti by Activiti.

the class ImportUploadReceiver method deployUploadedFile.

protected void deployUploadedFile() {
    try {
        try {
            if (fileName.endsWith(".bpmn20.xml") || fileName.endsWith(".bpmn")) {
                validFile = true;
                XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory();
                InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(outputStream.toByteArray()), "UTF-8");
                XMLStreamReader xtr = xif.createXMLStreamReader(in);
                BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);
                if (bpmnModel.getMainProcess() == null || bpmnModel.getMainProcess().getId() == null) {
                    notificationManager.showErrorNotification(Messages.MODEL_IMPORT_FAILED, i18nManager.getMessage(Messages.MODEL_IMPORT_INVALID_BPMN_EXPLANATION));
                } else {
                    if (bpmnModel.getLocationMap().isEmpty()) {
                        notificationManager.showErrorNotification(Messages.MODEL_IMPORT_INVALID_BPMNDI, i18nManager.getMessage(Messages.MODEL_IMPORT_INVALID_BPMNDI_EXPLANATION));
                    } else {
                        String processName = null;
                        if (StringUtils.isNotEmpty(bpmnModel.getMainProcess().getName())) {
                            processName = bpmnModel.getMainProcess().getName();
                        } else {
                            processName = bpmnModel.getMainProcess().getId();
                        }
                        modelData = repositoryService.newModel();
                        ObjectNode modelObjectNode = new ObjectMapper().createObjectNode();
                        modelObjectNode.put(MODEL_NAME, processName);
                        modelObjectNode.put(MODEL_REVISION, 1);
                        modelData.setMetaInfo(modelObjectNode.toString());
                        modelData.setName(processName);
                        repositoryService.saveModel(modelData);
                        BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
                        ObjectNode editorNode = jsonConverter.convertToJson(bpmnModel);
                        repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
                    }
                }
            } else {
                notificationManager.showErrorNotification(Messages.MODEL_IMPORT_INVALID_FILE, i18nManager.getMessage(Messages.MODEL_IMPORT_INVALID_FILE_EXPLANATION));
            }
        } catch (Exception e) {
            String errorMsg = e.getMessage().replace(System.getProperty("line.separator"), "<br/>");
            notificationManager.showErrorNotification(Messages.MODEL_IMPORT_FAILED, errorMsg);
        }
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                notificationManager.showErrorNotification("Server-side error", e.getMessage());
            }
        }
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) InputStreamReader(java.io.InputStreamReader) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) BpmnJsonConverter(org.activiti.editor.language.json.converter.BpmnJsonConverter) XMLInputFactory(javax.xml.stream.XMLInputFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) BpmnModel(org.activiti.bpmn.model.BpmnModel) BpmnXMLConverter(org.activiti.bpmn.converter.BpmnXMLConverter)

Example 8 with XMLStreamReader

use of javax.xml.stream.XMLStreamReader 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)

Example 9 with XMLStreamReader

use of javax.xml.stream.XMLStreamReader in project jdk8u_jdk by JetBrains.

the class SurrogatesTest method readXML.

// Reads generated XML data and check if it contains expected
// text in writeCharactersWithString and writeCharactersWithArray
// elements
private void readXML(byte[] xmlData, String expectedContent) throws Exception {
    InputStream stream = new ByteArrayInputStream(xmlData);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader xmlReader = factory.createXMLStreamReader(stream);
    boolean inTestElement = false;
    StringBuilder sb = new StringBuilder();
    while (xmlReader.hasNext()) {
        String ename;
        switch(xmlReader.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                ename = xmlReader.getLocalName();
                if (ename.equals("writeCharactersWithString") || ename.equals("writeCharactersWithArray")) {
                    inTestElement = true;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                ename = xmlReader.getLocalName();
                if (ename.equals("writeCharactersWithString") || ename.equals("writeCharactersWithArray")) {
                    inTestElement = false;
                    String content = sb.toString();
                    System.out.println(ename + " text:'" + content + "' expected:'" + expectedContent + "'");
                    Assert.assertEquals(content, expectedContent);
                    sb.setLength(0);
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                if (inTestElement) {
                    sb.append(xmlReader.getText());
                }
                break;
        }
        xmlReader.next();
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 10 with XMLStreamReader

use of javax.xml.stream.XMLStreamReader in project OpenRefine by OpenRefine.

the class XmlImporter method createParserUIInitializationData.

@Override
public JSONObject createParserUIInitializationData(ImportingJob job, List<JSONObject> fileRecords, String format) {
    JSONObject options = super.createParserUIInitializationData(job, fileRecords, format);
    try {
        if (fileRecords.size() > 0) {
            JSONObject firstFileRecord = fileRecords.get(0);
            File file = ImportingUtilities.getFile(job, firstFileRecord);
            InputStream is = new FileInputStream(file);
            try {
                XMLStreamReader parser = createXMLStreamReader(is);
                PreviewParsingState state = new PreviewParsingState();
                while (parser.hasNext() && state.tokenCount < PREVIEW_PARSING_LIMIT) {
                    int tokenType = parser.next();
                    state.tokenCount++;
                    if (tokenType == XMLStreamConstants.START_ELEMENT) {
                        JSONObject rootElement = descendElement(parser, state);
                        if (rootElement != null) {
                            JSONUtilities.safePut(options, "dom", rootElement);
                            break;
                        }
                    } else {
                    // ignore everything else
                    }
                }
            } catch (XMLStreamException e) {
                logger.warn("Error generating parser UI initialization data for XML file", e);
            } finally {
                is.close();
            }
        }
    } catch (IOException e) {
        logger.error("Error generating parser UI initialization data for XML file", e);
    }
    return options;
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) JSONObject(org.json.JSONObject) XMLStreamException(javax.xml.stream.XMLStreamException) PushbackInputStream(java.io.PushbackInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Aggregations

XMLStreamReader (javax.xml.stream.XMLStreamReader)1074 Test (org.junit.Test)486 InputStream (java.io.InputStream)451 ByteArrayInputStream (java.io.ByteArrayInputStream)379 ByteArrayOutputStream (java.io.ByteArrayOutputStream)334 Document (org.w3c.dom.Document)311 XMLStreamException (javax.xml.stream.XMLStreamException)288 ArrayList (java.util.ArrayList)270 XMLSecurityProperties (org.apache.xml.security.stax.ext.XMLSecurityProperties)242 XMLInputFactory (javax.xml.stream.XMLInputFactory)211 QName (javax.xml.namespace.QName)208 DOMSource (javax.xml.transform.dom.DOMSource)206 StringReader (java.io.StringReader)196 SecretKey (javax.crypto.SecretKey)188 StreamResult (javax.xml.transform.stream.StreamResult)183 DocumentBuilder (javax.xml.parsers.DocumentBuilder)178 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)160 InboundXMLSec (org.apache.xml.security.stax.ext.InboundXMLSec)155 IOException (java.io.IOException)144 Key (java.security.Key)103