use of javax.xml.transform.dom.DOMSource in project midpoint by Evolveum.
the class ModelWebServiceRaw method invokeAllowingFaults.
public DOMSource invokeAllowingFaults(DOMSource request) throws FaultMessage {
Node rootNode = request.getNode();
Element rootElement;
if (rootNode instanceof Document) {
rootElement = ((Document) rootNode).getDocumentElement();
} else if (rootNode instanceof Element) {
rootElement = (Element) rootNode;
} else {
throw ws.createIllegalArgumentFault("Unexpected DOM node type: " + rootNode);
}
Object requestObject;
try {
requestObject = prismContext.parserFor(rootElement).parseRealValue();
} catch (SchemaException e) {
throw ws.createIllegalArgumentFault("Couldn't parse SOAP request body because of schema exception: " + e.getMessage());
}
Node response;
Holder<OperationResultType> operationResultTypeHolder = new Holder<>();
try {
PrismSerializer<Element> serializer = prismContext.domSerializer().options(SerializationOptions.createSerializeReferenceNames());
if (requestObject instanceof GetObjectType) {
GetObjectType g = (GetObjectType) requestObject;
Holder<ObjectType> objectTypeHolder = new Holder<>();
ws.getObject(g.getObjectType(), g.getOid(), g.getOptions(), objectTypeHolder, operationResultTypeHolder);
GetObjectResponseType gr = new GetObjectResponseType();
gr.setObject(objectTypeHolder.value);
gr.setResult(operationResultTypeHolder.value);
response = serializer.serializeAnyData(gr, ModelPort.GET_OBJECT_RESPONSE);
} else if (requestObject instanceof SearchObjectsType) {
SearchObjectsType s = (SearchObjectsType) requestObject;
Holder<ObjectListType> objectListTypeHolder = new Holder<>();
ws.searchObjects(s.getObjectType(), s.getQuery(), s.getOptions(), objectListTypeHolder, operationResultTypeHolder);
SearchObjectsResponseType sr = new SearchObjectsResponseType();
sr.setObjectList(objectListTypeHolder.value);
sr.setResult(operationResultTypeHolder.value);
response = serializer.serializeAnyData(sr, ModelPort.SEARCH_OBJECTS_RESPONSE);
} else if (requestObject instanceof ExecuteChangesType) {
ExecuteChangesType e = (ExecuteChangesType) requestObject;
ObjectDeltaOperationListType objectDeltaOperationListType = ws.executeChanges(e.getDeltaList(), e.getOptions());
ExecuteChangesResponseType er = new ExecuteChangesResponseType();
er.setDeltaOperationList(objectDeltaOperationListType);
response = serializer.serializeAnyData(er, ModelPort.EXECUTE_CHANGES_RESPONSE);
} else if (requestObject instanceof FindShadowOwnerType) {
FindShadowOwnerType f = (FindShadowOwnerType) requestObject;
Holder<UserType> userTypeHolder = new Holder<>();
ws.findShadowOwner(f.getShadowOid(), userTypeHolder, operationResultTypeHolder);
FindShadowOwnerResponseType fsr = new FindShadowOwnerResponseType();
fsr.setUser(userTypeHolder.value);
fsr.setResult(operationResultTypeHolder.value);
response = serializer.serializeAnyData(fsr, ModelPort.FIND_SHADOW_OWNER_RESPONSE);
} else if (requestObject instanceof TestResourceType) {
TestResourceType tr = (TestResourceType) requestObject;
OperationResultType operationResultType = ws.testResource(tr.getResourceOid());
TestResourceResponseType trr = new TestResourceResponseType();
trr.setResult(operationResultType);
response = serializer.serializeAnyData(trr, ModelPort.TEST_RESOURCE_RESPONSE);
} else if (requestObject instanceof ExecuteScriptsType) {
ExecuteScriptsType es = (ExecuteScriptsType) requestObject;
ExecuteScriptsResponseType esr = ws.executeScripts(es);
response = serializer.serializeAnyData(esr, ModelPort.EXECUTE_SCRIPTS_RESPONSE);
} else if (requestObject instanceof ImportFromResourceType) {
ImportFromResourceType ifr = (ImportFromResourceType) requestObject;
TaskType taskType = ws.importFromResource(ifr.getResourceOid(), ifr.getObjectClass());
ImportFromResourceResponseType ifrr = new ImportFromResourceResponseType();
ifrr.setTask(taskType);
response = serializer.serializeAnyData(ifrr, ModelPort.IMPORT_FROM_RESOURCE_RESPONSE);
} else if (requestObject instanceof NotifyChangeType) {
NotifyChangeType nc = (NotifyChangeType) requestObject;
TaskType taskType = ws.notifyChange(nc.getChangeDescription());
NotifyChangeResponseType ncr = new NotifyChangeResponseType();
ncr.setTask(taskType);
response = serializer.serializeAnyData(ncr, ModelPort.NOTIFY_CHANGE_RESPONSE);
} else {
throw ws.createIllegalArgumentFault("Unsupported request type: " + requestObject);
}
} catch (SchemaException e) {
throwFault(e, operationResultTypeHolder.value);
// not reached
return null;
}
return new DOMSource(response);
}
use of javax.xml.transform.dom.DOMSource in project midpoint by Evolveum.
the class TestExtraSchema method testUserExtensionSchemaParseUser.
@Test
public void testUserExtensionSchemaParseUser() throws SAXException, IOException, SchemaException {
System.out.println("===[ testUserExtensionSchemaParseUser ]===");
Document dataDoc = DOMUtil.parseFile(USER_JACK_FILE_XML);
PrismContext context = constructPrismContext();
SchemaRegistryImpl reg = (SchemaRegistryImpl) context.getSchemaRegistry();
reg.registerPrismSchemasFromDirectory(EXTRA_SCHEMA_DIR);
context.initialize();
// Parsing user
// items from user extension are not correctly defined in the schema
PrismObject<UserType> user = context.parserFor(DOMUtil.getFirstChildElement(dataDoc)).compat().parse();
assertNotNull("No definition for user", user.getDefinition());
System.out.println("Parsed root object:");
System.out.println(user.debugDump());
// TODO: assert user
// Try javax schemas by validating a XML file
Schema javaxSchema = reg.getJavaxSchema();
assertNotNull(javaxSchema);
Validator validator = javaxSchema.newValidator();
DOMResult validationResult = new DOMResult();
validator.validate(new DOMSource(dataDoc), validationResult);
// System.out.println("Validation result:");
// System.out.println(DOMUtil.serializeDOMToString(validationResult.getNode()));
}
use of javax.xml.transform.dom.DOMSource in project goci by EBISPOT.
the class ChromosomeRenderlet method render.
public void render(RenderletNexus nexus, C context, E entity) {
int position = getPosition();
int height = SVGCanvas.canvasHeight;
int width = SVGCanvas.canvasWidth;
double chromWidth = (double) width / 12;
double chromHeight = (double) height / 2;
double xCoordinate;
double yCoordinate = 0;
if (position < 12) {
xCoordinate = position * chromWidth;
} else {
xCoordinate = (position - 12) * chromWidth;
yCoordinate = (double) height / 2;
}
InputStream in = null;
try {
in = getSVGFile().openStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document chromSVG = db.parse(in);
Element root = chromSVG.getDocumentElement();
Element g = (Element) root.getElementsByTagName("g").item(0).cloneNode(true);
setChromBands(g, nexus);
StringBuilder builder = new StringBuilder();
builder.append("translate(");
builder.append(Double.toString(xCoordinate));
builder.append(",");
builder.append(Double.toString(yCoordinate));
builder.append(")");
g.setAttribute("transform", builder.toString());
g.setAttribute("gwasname", getName());
g.removeAttribute("title");
SVGArea currentArea = new SVGArea(xCoordinate, yCoordinate, chromWidth, chromHeight, 0);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
StringWriter buffer = new StringWriter();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(g), new StreamResult(buffer));
String str = buffer.toString();
RenderingEvent<E> event = new RenderingEvent<E>(entity, str, currentArea, this);
nexus.renderingEventOccurred(event);
} catch (ParserConfigurationException e) {
throw new RuntimeException("Failed to read in template chromosome SVG from original resource", e);
} catch (SAXException e) {
throw new RuntimeException("Failed to read in template chromosome SVG from original resource", e);
} catch (IOException e) {
throw new RuntimeException("Failed to render chromosome SVG", e);
} catch (TransformerConfigurationException e) {
throw new RuntimeException("Failed to render chromosome SVG", e);
} catch (TransformerException e) {
throw new RuntimeException("Failed to render chromosome SVG", e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// tried our best!
}
}
}
}
use of javax.xml.transform.dom.DOMSource in project midpoint by Evolveum.
the class TestSchemaRegistry method testBasic.
/**
* Test whether the midpoint prism context was constructed OK and if it can validate
* ordinary user object.
*/
@Test
public void testBasic() throws SAXException, IOException, SchemaException {
MidPointPrismContextFactory factory = getContextFactory();
PrismContext context = factory.createInitializedPrismContext();
SchemaRegistry reg = context.getSchemaRegistry();
Schema javaxSchema = reg.getJavaxSchema();
assertNotNull(javaxSchema);
// Try to use the schema to validate Jack
// PrismObject<UserType> user = context.parseObject(new File("src/test/resources/common/user-jack.xml"));
// Element document = context.serializeToDom(user);
Document document = DOMUtil.parseFile("src/test/resources/common/user-jack.xml");
Validator validator = javaxSchema.newValidator();
DOMResult validationResult = new DOMResult();
validator.validate(new DOMSource(document), validationResult);
// System.out.println("Validation result:");
// System.out.println(DOMUtil.serializeDOMToString(validationResult.getNode()));
}
use of javax.xml.transform.dom.DOMSource in project jdk8u_jdk by JetBrains.
the class GenerationTests method test_create_detached_signature.
static boolean test_create_detached_signature(String canonicalizationMethod, String signatureMethod, String digestMethod, String transform, KeyInfoType keyInfo, Content contentType, int port) throws Exception {
System.out.print("Sign ...");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);
// Create SignedInfo
DigestMethod dm = fac.newDigestMethod(digestMethod, null);
List transformList = null;
if (transform != null) {
TransformParameterSpec params = null;
switch(transform) {
case Transform.XPATH:
params = new XPathFilterParameterSpec("//.");
break;
case Transform.XPATH2:
params = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType("//.", XPathType.Filter.INTERSECT)));
break;
case Transform.XSLT:
Element element = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xslt.getBytes())).getDocumentElement();
DOMStructure stylesheet = new DOMStructure(element);
params = new XSLTTransformParameterSpec(stylesheet);
break;
}
transformList = Collections.singletonList(fac.newTransform(transform, params));
}
String url = String.format("http://localhost:%d/%s", port, contentType);
List refs = Collections.singletonList(fac.newReference(url, dm, transformList, null, null));
CanonicalizationMethod cm = fac.newCanonicalizationMethod(canonicalizationMethod, (C14NMethodParameterSpec) null);
SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);
Key signingKey;
Key validationKey;
switch(signatureMethod) {
case SignatureMethod.DSA_SHA1:
case SignatureMethod.RSA_SHA1:
KeyPair kp = generateKeyPair(sm);
validationKey = kp.getPublic();
signingKey = kp.getPrivate();
break;
case SignatureMethod.HMAC_SHA1:
KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
signingKey = kg.generateKey();
validationKey = signingKey;
break;
default:
throw new RuntimeException("Unsupported signature algorithm");
}
SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
// Create KeyInfo
KeyInfoFactory kif = fac.getKeyInfoFactory();
List list = null;
if (keyInfo == KeyInfoType.KeyValue) {
if (validationKey instanceof PublicKey) {
KeyValue kv = kif.newKeyValue((PublicKey) validationKey);
list = Collections.singletonList(kv);
}
} else if (keyInfo == KeyInfoType.x509data) {
list = Collections.singletonList(kif.newX509Data(Collections.singletonList("cn=Test")));
} else if (keyInfo == KeyInfoType.KeyName) {
list = Collections.singletonList(kif.newKeyName("Test"));
} else {
throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);
}
KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;
// Create an empty doc for detached signature
Document doc = dbf.newDocumentBuilder().newDocument();
DOMSignContext xsc = new DOMSignContext(signingKey, doc);
// Generate signature
XMLSignature signature = fac.newXMLSignature(si, ki);
signature.sign(xsc);
// Save signature
String signatureString;
try (StringWriter writer = new StringWriter()) {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
Node parent = xsc.getParent();
trans.transform(new DOMSource(parent), new StreamResult(writer));
signatureString = writer.toString();
}
System.out.print("Validate ... ");
try (ByteArrayInputStream bis = new ByteArrayInputStream(signatureString.getBytes())) {
doc = dbf.newDocumentBuilder().parse(bis);
}
NodeList nodeLst = doc.getElementsByTagName("Signature");
Node node = nodeLst.item(0);
if (node == null) {
throw new RuntimeException("Couldn't find Signature element");
}
if (!(node instanceof Element)) {
throw new RuntimeException("Unexpected node type");
}
Element sig = (Element) node;
// Validate signature
DOMValidateContext vc = new DOMValidateContext(validationKey, sig);
vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
signature = fac.unmarshalXMLSignature(vc);
boolean success = signature.validate(vc);
if (!success) {
System.out.println("Core signature validation failed");
return false;
}
success = signature.getSignatureValue().validate(vc);
if (!success) {
System.out.println("Cryptographic validation of signature failed");
return false;
}
return true;
}
Aggregations