List of usage examples for javax.xml.bind JAXBContext createUnmarshaller
public abstract Unmarshaller createUnmarshaller() throws JAXBException;
From source file:org.psikeds.knowledgebase.xml.impl.XMLParser.java
/** * Helper for parsing big XML files using JAXB in combination with StAX.<br> * All classes in the specified package can be parsed.<br> * <b>Note:</b> The XML reader will not be closed. This must be invoked by * the caller afterwards!<br>//from w ww . j a va2s.c om * * @param xml * Reader for XML-Data * @param packageName * Name of the package containing the JAXB-Classes, * e.g. org.psikeds.knowledgebase.jaxb * @param handler * Callback handler used to process every single found * XML-Element (@see * org.psikeds.knowledgebase.xml.KBParserCallback#handleElement * (java.lang.Object)) * @param filter * EventFilter used for StAX-Parsing * @param numSkipped * Number of Elements to be skipped, * e.g. numSkipped = 1 for skipping the XML-Root-Element. * @return Total number of unmarshalled XML-Elements * @throws XMLStreamException * @throws JAXBException */ public static long parseXmlElements(final Reader xml, final String packageName, final KBParserCallback handler, final EventFilter filter, final int numSkipped) throws XMLStreamException, JAXBException { // init stream reader final XMLInputFactory staxFactory = XMLInputFactory.newInstance(); final XMLEventReader staxReader = staxFactory.createXMLEventReader(xml); final XMLEventReader filteredReader = filter == null ? staxReader : staxFactory.createFilteredReader(staxReader, filter); skipXmlElements(filteredReader, numSkipped); // JAXB with specific package final JAXBContext jaxbCtx = JAXBContext.newInstance(packageName); final Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); // parsing und unmarshalling long counter = 0; while (filteredReader.peek() != null) { final Object element = unmarshaller.unmarshal(staxReader); handleElement(handler, element); counter++; } return counter; }
From source file:be.e_contract.dssp.client.SignResponseVerifier.java
/** * Checks the signature on the SignResponse browser POST message. * /* ww w . j a v a 2s. c o m*/ * @param signResponseMessage * the SignResponse message. * @param session * the session object. * @return the verification result object. * @throws JAXBException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws MarshalException * @throws XMLSignatureException * @throws Base64DecodingException * @throws UserCancelException * @throws ClientRuntimeException * @throws SubjectNotAuthorizedException */ public static SignResponseVerificationResult checkSignResponse(String signResponseMessage, DigitalSignatureServiceSession session) throws JAXBException, ParserConfigurationException, SAXException, IOException, MarshalException, XMLSignatureException, Base64DecodingException, UserCancelException, ClientRuntimeException, SubjectNotAuthorizedException { if (null == session) { throw new IllegalArgumentException("missing session"); } byte[] decodedSignResponseMessage; try { decodedSignResponseMessage = Base64.decode(signResponseMessage); } catch (Base64DecodingException e) { throw new SecurityException("no Base64"); } // JAXB parsing JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class, be.e_contract.dssp.ws.jaxb.dss.async.ObjectFactory.class, be.e_contract.dssp.ws.jaxb.wsa.ObjectFactory.class, be.e_contract.dssp.ws.jaxb.wsu.ObjectFactory.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); SignResponse signResponse; try { signResponse = (SignResponse) unmarshaller .unmarshal(new ByteArrayInputStream(decodedSignResponseMessage)); } catch (UnmarshalException e) { throw new SecurityException("no valid SignResponse XML"); } // DOM parsing DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream signResponseInputStream = new ByteArrayInputStream(decodedSignResponseMessage); Document signResponseDocument = documentBuilder.parse(signResponseInputStream); // signature verification NodeList signatureNodeList = signResponseDocument .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); if (signatureNodeList.getLength() != 1) { throw new SecurityException("requires 1 ds:Signature element"); } Element signatureElement = (Element) signatureNodeList.item(0); SecurityTokenKeySelector keySelector = new SecurityTokenKeySelector(session.getKey()); DOMValidateContext domValidateContext = new DOMValidateContext(keySelector, signatureElement); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignature xmlSignature = xmlSignatureFactory.unmarshalXMLSignature(domValidateContext); boolean validSignature = xmlSignature.validate(domValidateContext); if (false == validSignature) { throw new SecurityException("invalid ds:Signature"); } // verify content String responseId = null; RelatesToType relatesTo = null; AttributedURIType to = null; TimestampType timestamp = null; String signerIdentity = null; AnyType optionalOutputs = signResponse.getOptionalOutputs(); List<Object> optionalOutputsList = optionalOutputs.getAny(); for (Object optionalOutputObject : optionalOutputsList) { LOG.debug("optional output object type: " + optionalOutputObject.getClass().getName()); if (optionalOutputObject instanceof JAXBElement) { JAXBElement optionalOutputElement = (JAXBElement) optionalOutputObject; LOG.debug("optional output name: " + optionalOutputElement.getName()); LOG.debug("optional output value type: " + optionalOutputElement.getValue().getClass().getName()); if (RESPONSE_ID_QNAME.equals(optionalOutputElement.getName())) { responseId = (String) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof RelatesToType) { relatesTo = (RelatesToType) optionalOutputElement.getValue(); } else if (TO_QNAME.equals(optionalOutputElement.getName())) { to = (AttributedURIType) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof TimestampType) { timestamp = (TimestampType) optionalOutputElement.getValue(); } else if (optionalOutputElement.getValue() instanceof NameIdentifierType) { NameIdentifierType nameIdentifier = (NameIdentifierType) optionalOutputElement.getValue(); signerIdentity = nameIdentifier.getValue(); } } } Result result = signResponse.getResult(); LOG.debug("result major: " + result.getResultMajor()); LOG.debug("result minor: " + result.getResultMinor()); if (DigitalSignatureServiceConstants.REQUESTER_ERROR_RESULT_MAJOR.equals(result.getResultMajor())) { if (DigitalSignatureServiceConstants.USER_CANCEL_RESULT_MINOR.equals(result.getResultMinor())) { throw new UserCancelException(); } if (DigitalSignatureServiceConstants.CLIENT_RUNTIME_RESULT_MINOR.equals(result.getResultMinor())) { throw new ClientRuntimeException(); } if (DigitalSignatureServiceConstants.SUBJECT_NOT_AUTHORIZED_RESULT_MINOR .equals(result.getResultMinor())) { throw new SubjectNotAuthorizedException(signerIdentity); } } if (false == DigitalSignatureServiceConstants.PENDING_RESULT_MAJOR.equals(result.getResultMajor())) { throw new SecurityException("invalid dss:ResultMajor"); } if (null == responseId) { throw new SecurityException("missing async:ResponseID"); } if (false == responseId.equals(session.getResponseId())) { throw new SecurityException("invalid async:ResponseID"); } if (null == relatesTo) { throw new SecurityException("missing wsa:RelatesTo"); } if (false == session.getInResponseTo().equals(relatesTo.getValue())) { throw new SecurityException("invalid wsa:RelatesTo"); } if (null == to) { throw new SecurityException("missing wsa:To"); } if (false == session.getDestination().equals(to.getValue())) { throw new SecurityException("invalid wsa:To"); } if (null == timestamp) { throw new SecurityException("missing wsu:Timestamp"); } AttributedDateTime expires = timestamp.getExpires(); if (null == expires) { throw new SecurityException("missing wsu:Timestamp/wsu:Expires"); } DateTime expiresDateTime = new DateTime(expires.getValue()); DateTime now = new DateTime(); if (now.isAfter(expiresDateTime)) { throw new SecurityException("wsu:Timestamp expired"); } session.setSignResponseVerified(true); SignResponseVerificationResult signResponseVerificationResult = new SignResponseVerificationResult( signerIdentity); return signResponseVerificationResult; }
From source file:cz.lbenda.dataman.db.DbStructureFactory.java
public static void loadDatabaseStructureFromXML(InputStream dbStructure, DbConfig dbConfig) { try {/*from w w w . j a v a 2 s . c o m*/ JAXBContext jc = JAXBContext.newInstance(cz.lbenda.dataman.schema.dbstructure.ObjectFactory.class); Unmarshaller um = jc.createUnmarshaller(); Object ob = um.unmarshal(dbStructure); if (ob instanceof JAXBElement && ((JAXBElement) ob).getValue() instanceof DatabaseStructureType) { //noinspection unchecked loadDatabaseStructureFromXML(((JAXBElement<DatabaseStructureType>) ob).getValue(), dbConfig); } else { throw new RuntimeException( "The file with database structure not contains XML with cached database structure."); } } catch (JAXBException e) { LOG.error("Problem with read cached database structure configuration: " + e.toString(), e); throw new RuntimeException("Problem with read cached database structure configuration: " + e.toString(), e); } }
From source file:br.ufpb.dicomflow.integrationAPI.tools.SendService.java
private static void configureService(ServiceIF service, CommandLine cl) throws ParseException, JAXBException, ClassNotFoundException { Logger.v(rb.getString("start-service-config")); if (!cl.hasOption(SERVICE_OPTION)) throw new MissingArgumentException(rb.getString("missing-content-opt")); JAXBContext jaxbContext; if (cl.hasOption(SERVICE_CLASS_OPTION)) { String serviceClass = cl.getOptionValue(SERVICE_CLASS_OPTION); jaxbContext = JAXBContext.newInstance(Class.forName(serviceClass)); Logger.v(rb.getString("jaxb-context") + Class.forName(serviceClass)); } else {/*from w ww .j a v a2 s . c o m*/ jaxbContext = JAXBContext.newInstance(CONTEXT_PATH); Logger.v(rb.getString("jaxb-context") + CONTEXT_PATH); } Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); service = (ServiceIF) jaxbUnmarshaller.unmarshal(new File(cl.getOptionValue(SERVICE_OPTION))); Logger.v(rb.getString("loaded-service") + service.getName() + " - " + service.getAction() + " - " + service.getMessageID()); Logger.v(rb.getString("finish-service-config")); }
From source file:com.inamik.template.util.TemplateConfigUtil.java
/** * readTemplateLibConfig w/InputStream - Read a template library * xml configuration from an InputStream. * * @param stream The InputStream to read. * @return A template library configuration suitable for adding to a * template engine configuration. * @throws TemplateException This method uses JAXB to parse the xml * configuration. If JAXB throws an exception, this method catches * it and re-throws it as a wrapped TemplateException. * @throws NullPointerException if <code>stream == null</code> * * @see TemplateEngineConfig/*from w ww. j a v a 2 s .c o m*/ */ public static TemplateLibConfig readTemplateLibConfig(final InputStream stream) throws TemplateException { TemplateLibConfig libConfig = new TemplateLibConfig(); try { JAXBContext jc = JAXBContext.newInstance(JAXB_LIB_PACKAGE); // create an Unmarshaller Unmarshaller u = jc.createUnmarshaller(); TemplateLib tl; tl = (TemplateLib) u.unmarshal(stream); List<Object> list = tl.getActionOrFunctionOrFilter(); for (Object o : list) { // TemplateActionTag if (o instanceof TemplateLib.Action) { TemplateLib.Action a = (TemplateLib.Action) o; String name = a.getName(); String clazz = a.getClazz(); TemplateActionConfig.ParmType parmType = TemplateActionConfig.ParmType .findByName(a.getParmType()); TemplateActionConfig.BlockType blockType = TemplateActionConfig.BlockType .findByName(a.getBlockType()); TemplateActionConfig.BodyContent bodyType = TemplateActionConfig.BodyContent .findByName(a.getBodyContent()); TemplateActionConfig actionConfig = new TemplateActionConfig(name, clazz, parmType, blockType, bodyType); libConfig.addAction(actionConfig); } else // TemplateFunctionTag if (o instanceof TemplateLib.Function) { TemplateLib.Function function = (TemplateLib.Function) o; String name = function.getName(); String clazz = function.getClazz(); TemplateFunctionConfig functionConfig = new TemplateFunctionConfig(name, clazz); libConfig.addFunction(functionConfig); } else // TemplateFilterTag if (o instanceof TemplateLib.Filter) { TemplateLib.Filter filter = (TemplateLib.Filter) o; String name = filter.getName(); String clazz = filter.getClazz(); TemplateFilterConfig filterConfig = new TemplateFilterConfig(name, clazz); libConfig.addFilter(filterConfig); } else { throw new RuntimeException("Unknown type" + o.getClass().getCanonicalName()); } } } catch (JAXBException e) { throw new TemplateException(e); } return libConfig; }
From source file:scott.barleydb.test.TestBase.java
private static DefinitionsSpec loadDefinitions(String path, String namespace) throws Exception { JAXBContext jc = JAXBContext.newInstance(SpecRegistry.class, StructureType.class, SyntaxType.class, EtlSpec.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); SpecRegistry registry = (SpecRegistry) unmarshaller.unmarshal(new File(path)); DefinitionsSpec spec = registry.getDefinitionsSpec(namespace); if (spec == null) { throw new IllegalStateException("Could not load definitions " + namespace); }//from w ww . ja v a 2 s .c o m if (db instanceof MySqlDbTest) { spec = MySqlSpecConverter.convertSpec(spec); } return spec; }
From source file:org.apache.lens.regression.util.Util.java
@SuppressWarnings("unchecked") public static <T> Object getObject(String queryString, Class<T> c) throws IllegalAccessException { JAXBContext jaxbContext = null; Unmarshaller unmarshaller = null; StringReader reader = new StringReader(queryString); try {/*from w w w.j av a 2 s .c om*/ jaxbContext = new LensJAXBContext(c); unmarshaller = jaxbContext.createUnmarshaller(); return (T) unmarshaller.unmarshal(reader); } catch (JAXBException e) { System.out.println("Exception : " + e); return null; } }
From source file:com.jkoolcloud.tnt4j.streams.utils.StreamsCache.java
private static void loadPersisted() { try {//from ww w.j a v a 2 s . co m JAXBContext jc = JAXBContext.newInstance(CacheRoot.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File persistedFile = new File(DEFAULT_FILE_NAME); LOGGER.log(OpLevel.DEBUG, StreamsResources.getBundle(StreamsResources.RESOURCE_BUNDLE_NAME), "StreamsCache.loading.file", persistedFile.getAbsolutePath()); if (!persistedFile.exists()) { LOGGER.log(OpLevel.DEBUG, StreamsResources.getBundle(StreamsResources.RESOURCE_BUNDLE_NAME), "StreamsCache.loading.file.not.found"); return; } CacheRoot root = (CacheRoot) unmarshaller.unmarshal(persistedFile); Map<String, CacheValue> mapProperty = root.getEntriesMap(); if (MapUtils.isNotEmpty(mapProperty)) { for (Map.Entry<String, CacheValue> entry : mapProperty.entrySet()) { valuesCache.put(entry.getKey(), entry.getValue()); } } LOGGER.log(OpLevel.DEBUG, StreamsResources.getBundle(StreamsResources.RESOURCE_BUNDLE_NAME), "StreamsCache.loading.done", mapProperty == null ? 0 : mapProperty.size(), persistedFile.getAbsolutePath()); } catch (JAXBException exc) { Utils.logThrowable(LOGGER, OpLevel.ERROR, StreamsResources.getBundle(StreamsResources.RESOURCE_BUNDLE_NAME), "StreamsCache.loading.failed", exc); } }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java
/** * This method unmarshals an XML file into a JAXB object element. * <p/>//from ww w .jav a2s .co m * <p/> * The underlying type of the JAXB object element returned by this method will correspond * to the JAXB object(s) referenced by the package namespace provided in the parameter list. * <p/> * <p/> * If the <code>filterMetaDataNamespaces</code> parameter is set to true, this method will use * the {@link MetaDataXMLNamespaceFilter} to filter the namespace URI of specific meta-data * elements during unmarshalling that correspond to the TCGA_BCR.Metadata XSD. * <p/> * <p/> * If the <code>validate</code> parameter is set to true, schema validation will be performed. * <p/> * <p/> * If both <code>filterMetaDataNamespaces</code> and <code>validate</code> are set to true, * only the meta-data elements will go through schema validation. * * @param xmlFile - a {@link File} object representing the XML file to unmarshalled * @param jaxbPackageName - a string that represents package namespace of the JAXB context objects * @param filterMetaDataNamespaces - boolean that specifies whether or not to filter meta-data * namespace URIs using the {@link MetaDataXMLNamespaceFilter} * @param validate - boolean indicating weather or not the XML should be validated against a schema * @return - an instance of {@link UnmarshalResult} representing the result of the unmarhsalling * @throws UnmarshalException if an error occurs during unmarshalling */ public static UnmarshalResult unmarshal(final File xmlFile, final String jaxbPackageName, final boolean filterMetaDataNamespaces, final boolean validate) throws UnmarshalException { Object jaxbObject = null; ValidationEventCollector validationEventCollector = (validate ? new ValidationEventCollector() : null); JAXBContext jaxbContext; Unmarshaller unmarshaller; if (xmlFile != null && jaxbPackageName != null) { FileReader xmlFileReader = null; try { // Get the JAXB context using the package name and create an unmarshaller jaxbContext = JAXBContext.newInstance(jaxbPackageName); unmarshaller = jaxbContext.createUnmarshaller(); xmlFileReader = new FileReader(xmlFile); // Unmarshal the XML file if (filterMetaDataNamespaces) { final SAXSource source = applyMetaDataNamespaceFilter(unmarshaller, xmlFileReader); jaxbObject = unmarshaller.unmarshal(source); // Perform schema validation meta-data elements only if (validate) { final String metaDataXML = getMetaDataXMLAsString(jaxbContext, jaxbObject); jaxbObject = validate(unmarshaller, validationEventCollector, new StringReader(metaDataXML), true); } } else { // Perform schema validation of all XML elements if (validate) { jaxbObject = validate(unmarshaller, validationEventCollector, xmlFileReader, false); } else { jaxbObject = unmarshaller.unmarshal(xmlFile); } } } catch (Exception e) { throw new UnmarshalException(e); } finally { IOUtils.closeQuietly(xmlFileReader); } } else { throw new UnmarshalException(new StringBuilder() .append("Unmarshalling failed because either the XML file '").append(xmlFile) .append("' or package namespace '").append(jaxbPackageName).append("' was null").toString()); } // Return the result of the unmarshalling if (validationEventCollector != null) { return new UnmarshalResult(jaxbObject, Arrays.asList(validationEventCollector.getEvents())); } else { return new UnmarshalResult(jaxbObject, new ArrayList<ValidationEvent>()); } }
From source file:com.hello2morrow.sonarplugin.SonargraphSensor.java
protected static ReportContext readSonargraphReport(String fileName, String packaging) { ReportContext result = null;//from www . ja v a 2s . co m InputStream input = null; ClassLoader defaultClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(SonargraphSensor.class.getClassLoader()); JAXBContext context = JAXBContext.newInstance("com.hello2morrow.sonarplugin.xsd"); Unmarshaller u = context.createUnmarshaller(); input = new FileInputStream(fileName); result = (ReportContext) u.unmarshal(input); } catch (JAXBException e) { LOG.error("JAXB Problem in " + fileName, e); } catch (FileNotFoundException e) { if (!packaging.equalsIgnoreCase("pom")) { LOG.warn("Cannot open Sonargraph report: " + fileName + "."); LOG.warn( " Did you run the maven sonargraph goal before with the POM option <prepareForSonar>true</prepareForSonar> " + "or with the commandline option -Dsonargraph.prepareForSonar=true?"); LOG.warn(" Is the project part of the Sonargraph architecture description?"); LOG.warn(" Did you set the 'aggregate' to true (must be false)?"); } } finally { Thread.currentThread().setContextClassLoader(defaultClassLoader); if (input != null) { try { input.close(); } catch (IOException e) { LOG.error("Cannot close " + fileName, e); } } } return result; }