List of usage examples for javax.xml.bind JAXBContext createMarshaller
public abstract Marshaller createMarshaller() throws JAXBException;
From source file:ddf.security.pdp.realm.xacml.processor.XacmlClientTest.java
@Test public void testWrapperpoliciesdirectorypolicyadded() throws Exception { LOGGER.debug("\n\n\n##### testXACMLWrapper_policies_directory_policy_added"); File policyDir = folder.newFolder("tempDir"); XacmlClient.defaultPollingIntervalInSeconds = 1; // Perform Test XacmlClient pdp = new XacmlClient(policyDir.getCanonicalPath(), new XmlParser()); File srcFile = new File( projectHome + File.separator + RELATIVE_POLICIES_DIR + File.separator + POLICY_FILE); FileUtils.copyFileToDirectory(srcFile, policyDir); Thread.sleep(2000);/*from ww w . j av a2 s .c om*/ RequestType xacmlRequestType = new RequestType(); xacmlRequestType.setCombinedDecision(false); xacmlRequestType.setReturnPolicyIdList(false); AttributesType actionAttributes = new AttributesType(); actionAttributes.setCategory(ACTION_CATEGORY); AttributeType actionAttribute = new AttributeType(); actionAttribute.setAttributeId(ACTION_ID); actionAttribute.setIncludeInResult(false); AttributeValueType actionValue = new AttributeValueType(); actionValue.setDataType(STRING_DATA_TYPE); actionValue.getContent().add(QUERY_ACTION); actionAttribute.getAttributeValue().add(actionValue); actionAttributes.getAttribute().add(actionAttribute); AttributesType subjectAttributes = new AttributesType(); subjectAttributes.setCategory(SUBJECT_CATEGORY); AttributeType subjectAttribute = new AttributeType(); subjectAttribute.setAttributeId(SUBJECT_ID); subjectAttribute.setIncludeInResult(false); AttributeValueType subjectValue = new AttributeValueType(); subjectValue.setDataType(STRING_DATA_TYPE); subjectValue.getContent().add(TEST_USER_1); subjectAttribute.getAttributeValue().add(subjectValue); subjectAttributes.getAttribute().add(subjectAttribute); AttributeType roleAttribute = new AttributeType(); roleAttribute.setAttributeId(ROLE_CLAIM); roleAttribute.setIncludeInResult(false); AttributeValueType roleValue = new AttributeValueType(); roleValue.setDataType(STRING_DATA_TYPE); roleValue.getContent().add(ROLE); roleAttribute.getAttributeValue().add(roleValue); subjectAttributes.getAttribute().add(roleAttribute); AttributesType categoryAttributes = new AttributesType(); categoryAttributes.setCategory(PERMISSIONS_CATEGORY); AttributeType citizenshipAttribute = new AttributeType(); citizenshipAttribute.setAttributeId(CITIZENSHIP_ATTRIBUTE); citizenshipAttribute.setIncludeInResult(false); AttributeValueType citizenshipValue = new AttributeValueType(); citizenshipValue.setDataType(STRING_DATA_TYPE); citizenshipValue.getContent().add(US_COUNTRY); citizenshipAttribute.getAttributeValue().add(citizenshipValue); categoryAttributes.getAttribute().add(citizenshipAttribute); xacmlRequestType.getAttributes().add(actionAttributes); xacmlRequestType.getAttributes().add(subjectAttributes); xacmlRequestType.getAttributes().add(categoryAttributes); // Perform Test ResponseType xacmlResponse = pdp.evaluate(xacmlRequestType); // Verify - The policy was loaded to allow a permit decision JAXBContext jaxbContext = JAXBContext.newInstance(ResponseType.class); Marshaller marshaller = jaxbContext.createMarshaller(); ObjectFactory objectFactory = new ObjectFactory(); Writer writer = new StringWriter(); marshaller.marshal(objectFactory.createResponse(xacmlResponse), writer); LOGGER.debug("\nXACML 3.0 Response:\n{}", writer.toString()); assertEquals(xacmlResponse.getResult().get(0).getDecision(), DecisionType.PERMIT); FileUtils.deleteDirectory(policyDir); }
From source file:net.ageto.gyrex.impex.console.internal.ImpexConsoleCommands.java
/** * * List process configurations.//from w w w.j a va 2 s. c om * * @param interpreter * @return */ public Object _impexListProcesses(final CommandInterpreter interpreter) { final String instanceShortcut = interpreter.nextArgument(); IRuntimeContext context = getContext(instanceShortcut); if (context == null) { interpreter.println(INSTANCE_MISSING); return null; } // determine process from database final IProcessConfigManager processManager = context.get(IProcessConfigManager.class); ArrayList<IProcessConfig> processes = (ArrayList<IProcessConfig>) processManager.findAllProcesses(); JAXBContext jaxbContext; try { for (IProcessConfig process : processes) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); jaxbContext = JAXBContext.newInstance(ProcessConfig.class); Marshaller m = jaxbContext.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.marshal(process, outputStream); final StringBuilder sb = new StringBuilder(); sb.append("=========== " + process.getId() + " ===========\n"); sb.append("\n"); sb.append(outputStream.toString() + "\n"); sb.append("\n"); sb.append("=========== " + process.getId() + " ===========\n"); interpreter.print(sb); } } catch (JAXBException e) { interpreter.printStackTrace(e); } return null; }
From source file:com.intuit.tank.tools.script.ScriptFilterRunner.java
private String toXml(ScriptTO turboScriptTO) { String ret = null;/* w w w .j a v a2 s .com*/ try { JAXBContext ctx = JAXBContext.newInstance(ScriptTO.class.getPackage().getName()); Marshaller marshaller = ctx.createMarshaller(); marshaller.setProperty("jaxb.formatted.output", true); StringWriter sw = new StringWriter(); marshaller.marshal(turboScriptTO, sw); ret = sw.toString(); } catch (JAXBException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Error reading file", JOptionPane.ERROR_MESSAGE); } return ret; }
From source file:ddf.security.pdp.realm.xacml.processor.BalanaClientTest.java
@Test public void testEvaluateroleuseractionquerycitizenshipUS() throws Exception { LOGGER.debug("\n\n\n##### testEvaluate_role_user_action_query_citizenship_US"); // Setup/* w w w .ja v a2 s . c om*/ File destDir = folder.newFolder(TEMP_DIR_NAME); LOGGER.debug("Making directory: {}", destDir.getPath()); if (destDir.mkdir()) { File srcFile = new File( projectHome + File.separator + RELATIVE_POLICIES_DIR + File.separator + POLICY_FILE); FileUtils.copyFileToDirectory(srcFile, destDir); RequestType xacmlRequestType = new RequestType(); xacmlRequestType.setCombinedDecision(false); xacmlRequestType.setReturnPolicyIdList(false); AttributesType actionAttributes = new AttributesType(); actionAttributes.setCategory(ACTION_CATEGORY); AttributeType actionAttribute = new AttributeType(); actionAttribute.setAttributeId(ACTION_ID); actionAttribute.setIncludeInResult(false); AttributeValueType actionValue = new AttributeValueType(); actionValue.setDataType(STRING_DATA_TYPE); actionValue.getContent().add(QUERY_ACTION); actionAttribute.getAttributeValue().add(actionValue); actionAttributes.getAttribute().add(actionAttribute); AttributesType subjectAttributes = new AttributesType(); subjectAttributes.setCategory(SUBJECT_CATEGORY); AttributeType subjectAttribute = new AttributeType(); subjectAttribute.setAttributeId(SUBJECT_ID); subjectAttribute.setIncludeInResult(false); AttributeValueType subjectValue = new AttributeValueType(); subjectValue.setDataType(STRING_DATA_TYPE); subjectValue.getContent().add(TEST_USER_1); subjectAttribute.getAttributeValue().add(subjectValue); subjectAttributes.getAttribute().add(subjectAttribute); AttributeType roleAttribute = new AttributeType(); roleAttribute.setAttributeId(ROLE_CLAIM); roleAttribute.setIncludeInResult(false); AttributeValueType roleValue = new AttributeValueType(); roleValue.setDataType(STRING_DATA_TYPE); roleValue.getContent().add(ROLE); roleAttribute.getAttributeValue().add(roleValue); subjectAttributes.getAttribute().add(roleAttribute); AttributesType categoryAttributes = new AttributesType(); categoryAttributes.setCategory(PERMISSIONS_CATEGORY); AttributeType citizenshipAttribute = new AttributeType(); citizenshipAttribute.setAttributeId(CITIZENSHIP_ATTRIBUTE); citizenshipAttribute.setIncludeInResult(false); AttributeValueType citizenshipValue = new AttributeValueType(); citizenshipValue.setDataType(STRING_DATA_TYPE); citizenshipValue.getContent().add(US_COUNTRY); citizenshipAttribute.getAttributeValue().add(citizenshipValue); categoryAttributes.getAttribute().add(citizenshipAttribute); xacmlRequestType.getAttributes().add(actionAttributes); xacmlRequestType.getAttributes().add(subjectAttributes); xacmlRequestType.getAttributes().add(categoryAttributes); BalanaClient pdp = new BalanaClient(destDir.getCanonicalPath(), new XmlParser()); // Perform Test ResponseType xacmlResponse = pdp.evaluate(xacmlRequestType); // Verify JAXBContext jaxbContext = JAXBContext.newInstance(ResponseType.class); Marshaller marshaller = jaxbContext.createMarshaller(); ObjectFactory objectFactory = new ObjectFactory(); Writer writer = new StringWriter(); marshaller.marshal(objectFactory.createResponse(xacmlResponse), writer); LOGGER.debug("\nXACML 3.0 Response:\n{}", writer.toString()); assertEquals(xacmlResponse.getResult().get(0).getDecision(), DecisionType.PERMIT); // Cleanup LOGGER.debug("Deleting directory: " + destDir); FileUtils.deleteDirectory(destDir); } else { LOGGER.debug("Could not create directory: " + destDir); } }
From source file:ddf.security.pdp.realm.xacml.processor.XacmlClientTest.java
@Test public void testEvaluateroleuseractionquerycitizenshipUS() throws Exception { LOGGER.debug("\n\n\n##### testEvaluate_role_user_action_query_citizenship_US"); // Setup/*from w ww .j a va 2s .com*/ File destDir = folder.newFolder(TEMP_DIR_NAME); LOGGER.debug("Making directory: {}", destDir.getPath()); if (destDir.mkdir()) { File srcFile = new File( projectHome + File.separator + RELATIVE_POLICIES_DIR + File.separator + POLICY_FILE); FileUtils.copyFileToDirectory(srcFile, destDir); RequestType xacmlRequestType = new RequestType(); xacmlRequestType.setCombinedDecision(false); xacmlRequestType.setReturnPolicyIdList(false); AttributesType actionAttributes = new AttributesType(); actionAttributes.setCategory(ACTION_CATEGORY); AttributeType actionAttribute = new AttributeType(); actionAttribute.setAttributeId(ACTION_ID); actionAttribute.setIncludeInResult(false); AttributeValueType actionValue = new AttributeValueType(); actionValue.setDataType(STRING_DATA_TYPE); actionValue.getContent().add(QUERY_ACTION); actionAttribute.getAttributeValue().add(actionValue); actionAttributes.getAttribute().add(actionAttribute); AttributesType subjectAttributes = new AttributesType(); subjectAttributes.setCategory(SUBJECT_CATEGORY); AttributeType subjectAttribute = new AttributeType(); subjectAttribute.setAttributeId(SUBJECT_ID); subjectAttribute.setIncludeInResult(false); AttributeValueType subjectValue = new AttributeValueType(); subjectValue.setDataType(STRING_DATA_TYPE); subjectValue.getContent().add(TEST_USER_1); subjectAttribute.getAttributeValue().add(subjectValue); subjectAttributes.getAttribute().add(subjectAttribute); AttributeType roleAttribute = new AttributeType(); roleAttribute.setAttributeId(ROLE_CLAIM); roleAttribute.setIncludeInResult(false); AttributeValueType roleValue = new AttributeValueType(); roleValue.setDataType(STRING_DATA_TYPE); roleValue.getContent().add(ROLE); roleAttribute.getAttributeValue().add(roleValue); subjectAttributes.getAttribute().add(roleAttribute); AttributesType categoryAttributes = new AttributesType(); categoryAttributes.setCategory(PERMISSIONS_CATEGORY); AttributeType citizenshipAttribute = new AttributeType(); citizenshipAttribute.setAttributeId(CITIZENSHIP_ATTRIBUTE); citizenshipAttribute.setIncludeInResult(false); AttributeValueType citizenshipValue = new AttributeValueType(); citizenshipValue.setDataType(STRING_DATA_TYPE); citizenshipValue.getContent().add(US_COUNTRY); citizenshipAttribute.getAttributeValue().add(citizenshipValue); categoryAttributes.getAttribute().add(citizenshipAttribute); xacmlRequestType.getAttributes().add(actionAttributes); xacmlRequestType.getAttributes().add(subjectAttributes); xacmlRequestType.getAttributes().add(categoryAttributes); XacmlClient pdp = new XacmlClient(destDir.getCanonicalPath(), new XmlParser()); // Perform Test ResponseType xacmlResponse = pdp.evaluate(xacmlRequestType); // Verify JAXBContext jaxbContext = JAXBContext.newInstance(ResponseType.class); Marshaller marshaller = jaxbContext.createMarshaller(); ObjectFactory objectFactory = new ObjectFactory(); Writer writer = new StringWriter(); marshaller.marshal(objectFactory.createResponse(xacmlResponse), writer); LOGGER.debug("\nXACML 3.0 Response:\n{}", writer.toString()); assertEquals(xacmlResponse.getResult().get(0).getDecision(), DecisionType.PERMIT); // Cleanup LOGGER.debug("Deleting directory: " + destDir); FileUtils.deleteDirectory(destDir); } else { LOGGER.debug("Could not create directory: " + destDir); } }
From source file:com.intuit.tank.tools.script.ScriptFilterRunner.java
/** * //from w w w.java2s . c o m */ protected void saveXml() { Writer fw = null; try { fw = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8"); // fw = new FileWriter(xmlFile); JAXBContext ctx = JAXBContext.newInstance(ScriptTO.class.getPackage().getName()); Marshaller marshaller = ctx.createMarshaller(); marshaller.setProperty("jaxb.formatted.output", true); marshaller.marshal(tankScript, fw); } catch (Exception e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Error writing file", JOptionPane.ERROR_MESSAGE); } finally { IOUtils.closeQuietly(fw); } }
From source file:broadwick.Broadwick.java
/** * Read the configuration file from the configuration file. * <p>//from w w w . j a v a2 s. c o m * @param logFacade the LoggingFacade object used to log any messages. * @param configFile the name of the configuration file. */ private void readConfigFile(final LoggingFacade logFacade, final String configFile) { if (!configFile.isEmpty()) { final File cfg = new File(configFile); if (!cfg.exists()) { throw new BroadwickException("Configuration file [" + configFile + "] does not exist."); } try { // read the configuration file final JAXBContext jaxbContext = JAXBContext.newInstance(Constants.GENERATED_CONFIG_CLASSES_DIR); final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); project = (Project) unmarshaller.unmarshal(cfg); // save the config file as a string for later use final StringWriter writer = new StringWriter(); jaxbContext.createMarshaller().marshal(project, writer); configXml = writer.toString(); // Validate the configuration file final ConfigValidator validator = new ConfigValidator(project); final ConfigValidationErrors validationErrors = validator.validate(); // now set up the logger as defined in the config file, we want to do this // BEFORE writing the results of validation final Logs.File file = project.getLogs().getFile(); if (file != null) { logFacade.addFileLogger(file.getName(), file.getLevel(), file.getPattern(), file.isOverwrite()); } final Logs.Console console = project.getLogs().getConsole(); if (console != null) { logFacade.addConsoleLogger(console.getLevel(), console.getPattern()); } // Log any validation errors. if (validationErrors.getNumErrors() > 0) { log.error("Invalid configuration file.\n{}Correct any errors before continuing.", validationErrors.getValidationErrors()); project = validator.getValidatedProject(); } } catch (JAXBException ex) { log.error("Could not read configuration file. {}", ex.toString()); log.trace(com.google.common.base.Throwables.getStackTraceAsString(ex)); } } else { throw new BroadwickException("No configuration file specified"); } }
From source file:com.cts.ptms.tracking.UPSTracking.java
@Override public CustomTrackingResponse getTrackingDetails(CustomTrackingRequest customTrackingRequest) throws TrackingException { CustomTrackingResponse customTrackingResponse = null; try {//from w w w . ja va2 s. com com.cts.ptms.model.gls.AccessRequest accessRequest = null; com.cts.ptms.model.ups.generated.trackrequest.TrackRequest trackRequest = null; com.cts.ptms.model.ups.generated.trackresponse.TrackResponse trackResponse = null; //Create JAXBContext and marshaller for AccessRequest object JAXBContext accessRequestJAXBC = JAXBContext.newInstance(AccessRequest.class.getPackage().getName()); Marshaller accessRequestMarshaller = accessRequestJAXBC.createMarshaller(); com.cts.ptms.model.gls.ObjectFactory accessRequestObjectFactory = new com.cts.ptms.model.gls.ObjectFactory(); accessRequest = accessRequestObjectFactory.createAccessRequest(); AccessRequest receivedAccessReq = customTrackingRequest.getAccessRequest(); //Populate the access request accessRequest.setAccessLicenseNumber(receivedAccessReq.getAccessLicenseNumber()); accessRequest.setUserId(receivedAccessReq.getUserId()); accessRequest.setPassword(receivedAccessReq.getPassword()); TrackRequestDetails inputRequestDtls = customTrackingRequest.getTrackRequestDetails(); if (inputRequestDtls == null || inputRequestDtls.getTrackingNumber() == null) { throw new TrackingException("No Tracking Tracking number found in the request."); } //Create JAXBContext and marshaller for TrackRequest object JAXBContext trackRequestJAXBC = JAXBContext.newInstance( com.cts.ptms.model.ups.generated.trackrequest.TrackRequest.class.getPackage().getName()); Marshaller trackRequestMarshaller = trackRequestJAXBC.createMarshaller(); com.cts.ptms.model.ups.generated.trackrequest.ObjectFactory requestObjectFactory = new com.cts.ptms.model.ups.generated.trackrequest.ObjectFactory(); trackRequest = requestObjectFactory.createTrackRequest(); //Populate the Track request com.cts.ptms.model.ups.generated.trackrequest.Request request = new com.cts.ptms.model.ups.generated.trackrequest.Request(); com.cts.ptms.model.ups.generated.trackrequest.TransactionReference transReference = new com.cts.ptms.model.ups.generated.trackrequest.TransactionReference(); transReference.setCustomerContext("Tracking customer shipment Details"); request.setTransactionReference(transReference); request.setRequestAction("Track"); request.getRequestOption().addAll(inputRequestDtls.getRequestOptions()); trackRequest.setRequest(request); trackRequest.setTrackingNumber(inputRequestDtls.getTrackingNumber()); //Get String out of access request and track request objects. StringWriter strWriter = new StringWriter(); accessRequestMarshaller.marshal(accessRequest, strWriter); trackRequestMarshaller.marshal(trackRequest, strWriter); strWriter.flush(); strWriter.close(); System.out.println("Request: " + strWriter.getBuffer().toString()); if (properties == null) { throw new TrackingException("Error while loading the ups properties."); } URLConnection httpUrlConnection = ShipmentCommonUtilities.contactService( strWriter.getBuffer().toString(), new URL(properties.getProperty("INTEGRATION_URL"))); String strResults = null; if (httpUrlConnection != null) { strResults = ShipmentCommonUtilities.readURLConnection(httpUrlConnection); } else throw new TrackingException("Exception occured while contacting the service.."); //Parse response object JAXBContext trackResponseJAXBC = JAXBContext.newInstance(TrackResponse.class.getPackage().getName()); Unmarshaller trackUnmarshaller = trackResponseJAXBC.createUnmarshaller(); ByteArrayInputStream input = new ByteArrayInputStream(strResults.getBytes()); Object objResponse = trackUnmarshaller.unmarshal(input); trackResponse = (com.cts.ptms.model.ups.generated.trackresponse.TrackResponse) objResponse; List<TrackingError> trackingErrors = null; if (trackResponse.getResponse() != null) { String responseCode = trackResponse.getResponse().getResponseStatusCode(); customTrackingResponse = populateResponse(trackResponse); if (responseCode != null && responseCode.equals("1")) { System.out.println("Response Status: " + trackResponse.getResponse().getResponseStatusCode()); System.out.println("Response Status Description: " + trackResponse.getResponse().getResponseStatusDescription()); } else if (responseCode != null && responseCode.equals("0")) { trackingErrors = new ArrayList<TrackingError>(0); List<com.cts.ptms.model.ups.generated.trackresponse.Error> resErrors = trackResponse .getResponse().getError(); if (resErrors != null && !resErrors.isEmpty()) { for (com.cts.ptms.model.ups.generated.trackresponse.Error resError : resErrors) { TrackingError trackingError = new TrackingError(); trackingError.setErrorSeverity(resError.getErrorSeverity()); trackingError.setErrorCode(resError.getErrorCode()); trackingError.setErrorDescription(resError.getErrorDescription()); trackingErrors.add(trackingError); } } customTrackingResponse.setError(trackingErrors); } } } catch (TrackingException e) { System.out.println("Exception occurred at : " + e.getMessage()); } catch (Exception e) { System.out.println("Exception occurred at : " + e.getMessage()); throw new TrackingException(e.getMessage()); } return customTrackingResponse; }
From source file:com.esri.geoevent.test.performance.ui.OrchestratorController.java
/** * Saves the current fixtures file to disk. * * @param file File where to save the configuration file. * @throws JAXBException//from w w w . jav a 2s. co m * @throws XMLStreamException * @throws IOException */ private void saveFile(File file) throws JAXBException, XMLStreamException, IOException { JAXBContext jaxbContext = JAXBContext.newInstance(Fixtures.class); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); FileWriter fileWriter = new FileWriter(file); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter xmlWritter = factory.createXMLStreamWriter(fileWriter); marshaller.marshal(fixtures, xmlWritter); fileWriter.flush(); fileWriter.close(); }