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;
}
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());
}
}
}
}
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");
}
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();
}
}
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;
}
Aggregations