javax.xml.bind.JAXBContext Java Examples

The following examples show how to use javax.xml.bind.JAXBContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JAXBManager.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
void initJaxbContext(final Method method) {
    Stream
            .concat(of(method.getGenericReturnType()),
                    of(method.getParameters())
                            .filter(p -> of(Path.class, Query.class, Header.class, QueryParams.class, Headers.class,
                                    HttpMethod.class, Url.class).noneMatch(p::isAnnotationPresent))
                            .map(Parameter::getParameterizedType))
            .map(RequestParser::toClassType)
            .filter(Objects::nonNull)
            .filter(cType -> cType.isAnnotationPresent(XmlRootElement.class)
                    || cType.isAnnotationPresent(XmlType.class))
            .forEach(rootElemType -> jaxbContexts.computeIfAbsent(rootElemType, k -> {
                try {
                    return JAXBContext.newInstance(k);
                } catch (final JAXBException e) {
                    throw new IllegalStateException(e);
                }
            }));
}
 
Example #2
Source File: DataForASchool.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
public void printInterchangeStudentProgram(PrintStream ps) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(InterchangeStudentProgram.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);

    InterchangeStudentProgram interchangeStudentProgram = new InterchangeStudentProgram();

    List<Object> list = interchangeStudentProgram
            .getStudentProgramAssociationOrStudentSpecialEdProgramAssociationOrRestraintEvent();

    // StudentProgramAssociation
    // StudentSpecialEdProgramAssociation
    // RestraintEvent
    // StudentCTEProgramAssociation
    // StudentTitleIPartAProgramAssociation
    // ServiceDescriptor

    marshaller.marshal(interchangeStudentProgram, ps);
}
 
Example #3
Source File: ConverterImpl.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public String toXML(T obj) {

    try {
        JAXBContext context = JAXBContext.newInstance(type);

        Marshaller m = context.createMarshaller();
        if(schemaLocation != null) {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            StreamSource source = new StreamSource(getClass().getResourceAsStream(schemaLocation));
            Schema schema = schemaFactory.newSchema(source);
            m.setSchema(schema);
        }

        StringWriter writer = new StringWriter();

        m.marshal(obj, writer);
        String xml = writer.toString();

        return xml;
    } catch (Exception e) {
        System.out.println("ERROR: "+e.toString());
        return null;
    }
}
 
Example #4
Source File: JAXBMarshaller.java    From juddi with Apache License 2.0 6 votes vote down vote up
public static String marshallToString(Object object, String thePackage) {
	String rawObject = null;

	try {
		JAXBContext jc = getContext(thePackage);
		Marshaller marshaller = jc.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
		marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
		marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		marshaller.marshal(object, baos);
		rawObject = baos.toString();
	} catch (JAXBException e) {
		logger.error(e.getMessage(),e);
	}
	
	return rawObject;
}
 
Example #5
Source File: Error.java    From authy-java with MIT License 6 votes vote down vote up
/**
 * Map a Token instance to its XML representation.
 *
 * @return a String with the description of this object in XML.
 */
public String toXML() {
    StringWriter sw = new StringWriter();
    String xml = "";

    try {
        JAXBContext context = JAXBContext.newInstance(this.getClass());
        Marshaller marshaller = context.createMarshaller();

        marshaller.marshal(this, sw);
        xml = sw.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return xml;
}
 
Example #6
Source File: QueryResultsParser.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Marshals the given QueryResults object to its XML representations and
 * returns it as a String.
 * 
 * @param results
 *            The QueryResults object to marshal into XML.
 * @param out
 *            The OutputStream to which the XML representation will be
 *            written to.
 * @throws IOException
 *             If an error marshaling the QueryResults object occurred.
 */
public static String queryResultsToXml(final QueryResults results) throws IOException {
    // serialize the response
    try {
        StringWriter writer = new StringWriter();
        JAXBElement<QueryResults> item = factory.createQueryResults(results);
        JAXBContext context = JAXBContext.newInstance(QueryResults.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.marshal(item, writer);
        return writer.toString();
    } catch (JAXBException e) {
        IOException ioe = new IOException(e.getMessage());
        ioe.setStackTrace(e.getStackTrace());
        throw ioe;
    }
}
 
Example #7
Source File: DispatchTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testSOAPPBindingNullMessage() throws Exception {
    d.setMessageObserver(new MessageReplayObserver("/org/apache/cxf/jaxws/sayHiResponse.xml"));

    URL wsdl = getClass().getResource("/wsdl/hello_world.wsdl");
    assertNotNull(wsdl);

    SOAPService service = new SOAPService(wsdl, SERVICE_NAME);
    assertNotNull(service);

    JAXBContext jc = JAXBContext.newInstance("org.apache.hello_world_soap_http.types");
    Dispatch<Object> disp = service.createDispatch(PORT_NAME, jc, Service.Mode.PAYLOAD);
    try {
        // Send a null message
        disp.invoke(null);
    } catch (SOAPFaultException e) {
        //Passed
        return;
    }

    fail("SOAPFaultException was not thrown");
}
 
Example #8
Source File: Jaxb.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Marshal an object to a file, using provided JAXB context.
 *
 * @param object      instance to marshal
 * @param path        target file
 * @param jaxbContext proper context
 * @throws IOException        on IO error
 * @throws JAXBException      on JAXB error
 * @throws XMLStreamException on XML error
 */
public static void marshal (Object object,
                            Path path,
                            JAXBContext jaxbContext)
        throws IOException,
               JAXBException,
               XMLStreamException
{

    try (OutputStream os = Files.newOutputStream(path, CREATE);) {
        Marshaller m = jaxbContext.createMarshaller();
        XMLStreamWriter writer = new IndentingXMLStreamWriter(
                XMLOutputFactory.newInstance().createXMLStreamWriter(os, "UTF-8"));
        m.marshal(object, writer);
        os.flush();
    }
}
 
Example #9
Source File: TypeTypeRelationGenTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
public void assertXmlMarshaling(Object typeTypeRelation, String expectedXml)
        throws Exception
    {
        JAXBContext jc = JAXBContext.newInstance(TypeTypeRelation.class);

        Marshaller marshaller = jc.createMarshaller();
        StringWriter stringWriter = new StringWriter();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        // marshaller.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new CustomNamespacePrefixMapper());
        marshaller.marshal(typeTypeRelation, stringWriter);
        String xml = stringWriter.toString();

//        System.out.println(xml); // run test, paste xml output into XML, comment out this line.

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Object actual = unmarshaller.unmarshal(new StringReader(xml));
        Object expected = unmarshaller.unmarshal(new StringReader(expectedXml));
        Assert.assertEquals(expected, actual);
    }
 
Example #10
Source File: WorkflowProfiles.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
private Unmarshaller getUnmarshaller() throws JAXBException {
    JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
    Unmarshaller unmarshaller = jctx.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd");
    Schema schema = null;
    try {
        schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm()));
    } catch (SAXException ex) {
        throw new JAXBException("Missing schema workflow.xsd!", ex);
    }
    unmarshaller.setSchema(schema);
    ValidationEventCollector errors = new ValidationEventCollector() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            super.handleEvent(event);
            return true;
        }

    };
    unmarshaller.setEventHandler(errors);
    return unmarshaller;
}
 
Example #11
Source File: ErrorFacadeImpl.java    From zstack with Apache License 2.0 6 votes vote down vote up
void init() {
    try {
        JAXBContext context = JAXBContext.newInstance("org.zstack.core.errorcode.schema");
        List<String> paths = PathUtil.scanFolderOnClassPath("errorCodes");
        for (String p : paths) {
            if (!p.endsWith(".xml")) {
                logger.warn(String.format("ignore %s which is not ending with .xml", p));
                continue;
            }

            File cfg = new File(p);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            org.zstack.core.errorcode.schema.Error error =
                    (org.zstack.core.errorcode.schema.Error) unmarshaller.unmarshal(cfg);
            createErrorCode(error, p);
        }
    } catch (Exception e) {
        throw new CloudRuntimeException(e);
    }
}
 
Example #12
Source File: ModelMigration.java    From ameba with MIT License 6 votes vote down vote up
/**
 * <p>writeMigration.</p>
 *
 * @param dbMigration a {@link io.ebeaninternal.dbmigration.migration.Migration} object.
 * @param version     a {@link java.lang.String} object.
 * @return a boolean.
 */
protected boolean writeMigration(Migration dbMigration, String version) {
    if (migrationModel.isMigrationTableExist()) {
        scriptInfo = server.find(ScriptInfo.class, version);
        if (scriptInfo != null) {
            return false;
        }
    }
    scriptInfo = new ScriptInfo();
    scriptInfo.setRevision(version);
    try (StringWriter writer = new StringWriter()) {
        JAXBContext jaxbContext = JAXBContext.newInstance(Migration.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(dbMigration, writer);
        writer.flush();
        scriptInfo.setModelDiff(writer.toString());
    } catch (JAXBException | IOException e) {
        throw new RuntimeException(e);
    }
    return true;
}
 
Example #13
Source File: UndertowSpringTypesFactory.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <V> List<V> parseListElement(Element parent,
                                       QName name,
                                       Class<?> c,
                                       JAXBContext context) throws JAXBException {
    List<V> list = new ArrayList<>();
    Node data = null;

    Unmarshaller u = context.createUnmarshaller();
    Node node = parent.getFirstChild();
    while (node != null) {
        if (node.getNodeType() == Node.ELEMENT_NODE && name.getLocalPart().equals(node.getLocalName())
            && name.getNamespaceURI().equals(node.getNamespaceURI())) {
            data = node;
            Object obj = unmarshal(u, data, c);
            if (obj != null) {
                list.add((V) obj);
            }
        }
        node = node.getNextSibling();
    }
    return list;
}
 
Example #14
Source File: EntityMarshallingUtils.java    From alm-rest-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param <T> the type we want to convert the XML into
 * @param c the class of the parameterized type
 * @param xml the instance XML description
 * @return a deserialization of the XML into an object of type T of class class <T>
 * @throws JAXBException
 */
public static <T> T marshal(Class<T> c, String xml) throws JAXBException
{
    T res;

    if (c == xml.getClass())
    {
        res = (T) xml;
    }
    else
    {
        JAXBContext ctx = JAXBContext.newInstance(c);
        Unmarshaller marshaller = ctx.createUnmarshaller();
        res = (T) marshaller.unmarshal(new StringReader(xml));
    }

    return res;
}
 
Example #15
Source File: JAXBContextFactory.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The JAXB API will invoke this method via reflection
 */
public static JAXBContext createContext( String contextPath,
                                         ClassLoader classLoader, Map properties ) throws JAXBException {

    List<Class> classes = new ArrayList<Class>();
    StringTokenizer tokens = new StringTokenizer(contextPath,":");

    // each package should be pointing to a JAXB RI generated
    // content interface package.
    //
    // translate them into a list of private ObjectFactories.
    try {
        while(tokens.hasMoreTokens()) {
            String pkg = tokens.nextToken();
            classes.add(classLoader.loadClass(pkg+IMPL_DOT_OBJECT_FACTORY));
        }
    } catch (ClassNotFoundException e) {
        throw new JAXBException(e);
    }

    // delegate to the JAXB provider in the system
    return JAXBContext.newInstance(classes.toArray(new Class[classes.size()]),properties);
}
 
Example #16
Source File: CustomFuelsHandler.java    From NewHorizonsCoreMod with GNU General Public License v3.0 6 votes vote down vote up
public boolean ReloadCustomFuels()
{
    boolean tResult = false;

    _mLogger.debug("CustomFuelsHandler will now try to load it's configuration");
    try
    {
        JAXBContext tJaxbCtx = JAXBContext.newInstance(CustomFuels.class);
        File tConfigFile = new File(_mConfigFileName);
        Unmarshaller jaxUnmarsh = tJaxbCtx.createUnmarshaller();
        CustomFuels tNewItemCollection = (CustomFuels) jaxUnmarsh.unmarshal(tConfigFile);
        _mLogger.debug("Config file has been loaded. Entering Verify state");

        _mCustomFuels = tNewItemCollection;
        tResult = true;

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return tResult;
}
 
Example #17
Source File: PersistenceXmlTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception
 */
public void testPersistenceVersion1() throws Exception {
    final JAXBContext ctx = JAXBContextFactory.newInstance(Persistence.class);
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();

    final URL resource = this.getClass().getClassLoader().getResource("persistence-example.xml");
    final InputStream in = resource.openStream();
    final java.lang.String expected = readContent(in);

    final Persistence element = (Persistence) unmarshaller.unmarshal(new ByteArrayInputStream(expected.getBytes()));
    unmarshaller.setEventHandler(new TestValidationEventHandler());
    System.out.println("unmarshalled");

    final Marshaller marshaller = ctx.createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", true);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    marshaller.marshal(element, baos);

    final String actual = new String(baos.toByteArray());

    final Diff myDiff = new Diff(expected, actual);
    myDiff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
    assertTrue("Files are similar " + myDiff, myDiff.similar());
}
 
Example #18
Source File: FedizConfigurationTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void verifyConfigFederation() throws JAXBException {

    final JAXBContext jaxbContext = JAXBContext
            .newInstance(FedizConfig.class);

    FedizConfigurator configurator = new FedizConfigurator();
    FedizConfig configOut = createConfiguration(true);
    StringWriter writer = new StringWriter();
    jaxbContext.createMarshaller().marshal(configOut, writer);
    StringReader reader = new StringReader(writer.toString());
    configurator.loadConfig(reader);

    ContextConfig config = configurator.getContextConfig(CONFIG_NAME);
    Assert.assertNotNull(config);
    AudienceUris audience = config.getAudienceUris();
    Assert.assertEquals(3, audience.getAudienceItem().size());
    Assert.assertTrue(config.getProtocol() instanceof FederationProtocolType);
    FederationProtocolType fp = (FederationProtocolType) config
            .getProtocol();

    Assert.assertEquals(HOME_REALM_CLASS, fp.getHomeRealm().getValue());

}
 
Example #19
Source File: RegisterPrecompiledJSPInitializer.java    From airsonic with GNU General Public License v3.0 6 votes vote down vote up
private static WebApp parseXmlFragment() {
    InputStream precompiledJspWebXml = RegisterPrecompiledJSPInitializer.class.getResourceAsStream("/precompiled-jsp-web.xml");
    InputStream webXmlIS = new SequenceInputStream(
            new SequenceInputStream(
                    IOUtils.toInputStream("<web-app>", Charset.defaultCharset()),
                    precompiledJspWebXml),
            IOUtils.toInputStream("</web-app>", Charset.defaultCharset()));

    try {
        JAXBContext jaxbContext = new JAXBDataBinding(WebApp.class).getContext();
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        WebApp webapp = (WebApp) unmarshaller.unmarshal(webXmlIS);
        try {
            webXmlIS.close();
        } catch (java.io.IOException ignored) {}
        return webapp;
    } catch (JAXBException e) {
        throw new RuntimeException("Could not parse precompiled-jsp-web.xml", e);
    }
}
 
Example #20
Source File: AbstractJAXBProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public JAXBContext getJAXBContext(Class<?> type, Type genericType) throws JAXBException {
    if (mc != null) {
        ContextResolver<JAXBContext> resolver =
            mc.getResolver(ContextResolver.class, JAXBContext.class);
        if (resolver != null) {
            JAXBContext customContext = resolver.getContext(type);
            if (customContext != null) {
                return customContext;
            }
        }
    }

    JAXBContext context = classContexts.get(type);
    if (context != null) {
        return context;
    }

    context = getPackageContext(type, genericType);

    return context != null ? context : getClassContext(type, genericType);
}
 
Example #21
Source File: FedizConfigurationTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testClaimProcessor() throws JAXBException, IOException {
    final JAXBContext jaxbContext = JAXBContext.newInstance(FedizConfig.class);
    FedizConfigurator configurator = new FedizConfigurator();
    FedizConfig configOut = createConfiguration(true);
    StringWriter writer = new StringWriter();
    jaxbContext.createMarshaller().marshal(configOut, writer);
    StringReader reader = new StringReader(writer.toString());
    configurator.loadConfig(reader);
    
    FedizContext fedContext = configurator.getFedizContext(CONFIG_NAME);
    List<ClaimsProcessor> claimsProcessor = fedContext.getClaimsProcessor();
    Assert.assertNotNull(claimsProcessor);
    Assert.assertEquals(1, claimsProcessor.size());
    
    List<org.apache.cxf.fediz.core.Claim> inputClaims = new ArrayList<>();
    org.apache.cxf.fediz.core.Claim claim = new org.apache.cxf.fediz.core.Claim();
    claim.setClaimType(URI.create(CLAIM_TYPE_1));
    claim.setValue("Alice");
    inputClaims.add(claim);
    List<org.apache.cxf.fediz.core.Claim> processedClaims = claimsProcessor.get(0).processClaims(inputClaims);
    Assert.assertEquals(inputClaims, processedClaims);
}
 
Example #22
Source File: ObjectSerializer.java    From peer-os with Apache License 2.0 6 votes vote down vote up
/**
 * Deserializes binary data representing a xml-fragment to an object of
 * given class.
 *
 * @param data the binary data, representing a xml-fragment
 * @param clazz the class of the resulting object
 *
 * @return the deserialized object
 */
@SuppressWarnings( "unchecked" )
@Override
public <T> T deserialize( byte[] data, Class<T> clazz )
{
    try
    {

        JAXBContext context = JAXBContext.newInstance( clazz );
        Unmarshaller m = context.createUnmarshaller();
        Object o = m.unmarshal( new ByteArrayInputStream( data ) );
        return ( T ) o;
    }
    catch ( JAXBException e )
    {
        LOG.warn( e.getMessage() );
    }

    return null;
}
 
Example #23
Source File: TCPIPProxy.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
public void reinit(IServiceSettings serviceSettings) {
	TCPIPProxySettings newSettings;
	if (serviceSettings instanceof TCPIPProxySettings) {
		newSettings = (TCPIPProxySettings) serviceSettings;
	} else {
		throw new ServiceException("Incorrect class of settings has been passed to init " + serviceSettings.getClass());
	}

       if(newSettings.isChangeTags() && (newSettings.getRulesAlias() != null)) {
		try {
			JAXBContext jc = JAXBContext.newInstance(new Class[]{Rules.class});
			Unmarshaller u = jc.createUnmarshaller();
			InputStream rulesAliasIS = dataManager.getDataInputStream(newSettings.getRulesAlias());
			JAXBElement<Rules> root = u.unmarshal(new StreamSource(rulesAliasIS),Rules.class);
			this.rules = root.getValue();
		} catch (Exception e) {
			disconnect();
			dispose();
			changeStatus(ServiceStatus.ERROR, "Error while reiniting", e);
			throw new EPSCommonException(e);
		}
	}
}
 
Example #24
Source File: JaxbMapper.java    From frpMgr with MIT License 6 votes vote down vote up
protected static JAXBContext getJaxbContext(Class clazz) {
		if (clazz == null){
			throw new RuntimeException("'clazz' must not be null");
		}
		JAXBContext jaxbContext = jaxbContexts.get(clazz);
		if (jaxbContext == null) {
			try {
				jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
				jaxbContexts.putIfAbsent(clazz, jaxbContext);
			} catch (JAXBException ex) {
//				throw new HttpMessageConversionException("Could not instantiate JAXBContext for class [" + clazz
//						+ "]: " + ex.getMessage(), ex);
				throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz
						+ "]: " + ex.getMessage(), ex);
			}
		}
		return jaxbContext;
	}
 
Example #25
Source File: JaxbReadTest286Gen.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {

   try {
      JAXBContext cntxt = JAXBContext.newInstance(JAXB_CONTEXT);
      InputStream in = this.getClass().getClassLoader().getResourceAsStream(XML_FILE);
      Unmarshaller um = cntxt.createUnmarshaller();
      JAXBElement<?> jel = (JAXBElement<?>) um.unmarshal(in);
      assertNotNull(jel.getValue());
      assertTrue(jel.getValue() instanceof PortletAppType);
      portletApp = (PortletAppType) jel.getValue();
   } catch (Exception e) {
      System.out.println("\nException during setup: " + e.getMessage()
            + "\n");
      throw e;
   }
}
 
Example #26
Source File: AbstractJaxb2HttpMessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Return a {@link JAXBContext} for the given class.
 * @param clazz the class to return the context for
 * @return the {@code JAXBContext}
 * @throws HttpMessageConversionException in case of JAXB errors
 */
protected final JAXBContext getJaxbContext(Class<?> clazz) {
	Assert.notNull(clazz, "Class must not be null");
	JAXBContext jaxbContext = this.jaxbContexts.get(clazz);
	if (jaxbContext == null) {
		try {
			jaxbContext = JAXBContext.newInstance(clazz);
			this.jaxbContexts.putIfAbsent(clazz, jaxbContext);
		}
		catch (JAXBException ex) {
			throw new HttpMessageConversionException(
					"Could not instantiate JAXBContext for class [" + clazz + "]: " + ex.getMessage(), ex);
		}
	}
	return jaxbContext;
}
 
Example #27
Source File: JAXBContextWithSubclassedFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void test(Class<?> factoryClass) throws JAXBException {
    System.clearProperty(JAXBContext.JAXB_CONTEXT_FACTORY);
    System.out.println("** Testing  with Factory Class: " + factoryClass.getName());
    System.out.println(JAXBContext.JAXB_CONTEXT_FACTORY + " = "
            + System.getProperty(JAXBContext.JAXB_CONTEXT_FACTORY, ""));
    System.out.println("Calling "
            + "JAXBContext.newInstance(JAXBContextWithSubclassedFactory.class)");
    tmp = JAXBContext.newInstance(JAXBContextWithSubclassedFactory.class);
    System.setProperty(JAXBContext.JAXB_CONTEXT_FACTORY,
            factoryClass.getName());
    System.out.println(JAXBContext.JAXB_CONTEXT_FACTORY + " = "
            + System.getProperty(JAXBContext.JAXB_CONTEXT_FACTORY));
    System.out.println("Calling "
            + "JAXBContext.newInstance(JAXBContextWithSubclassedFactory.class)");
    JAXBContext ctxt = JAXBContext.newInstance(JAXBContextWithSubclassedFactory.class);
    System.out.println("Successfully loaded JAXBcontext: " +
            System.identityHashCode(ctxt) + "@" + ctxt.getClass().getName());
    if (ctxt.getClass() != JAXBContextImpl.class) {
        throw new RuntimeException("Wrong JAXBContext class"
            + "\n\texpected: "
            + System.identityHashCode(tmp) + "@" + JAXBContextImpl.class.getName()
            + "\n\tactual:   "
            + System.identityHashCode(ctxt) + "@" + ctxt.getClass().getName());
    }
    if (((JAXBContextImpl)ctxt).creator != factoryClass) {
        throw new RuntimeException("Wrong Factory class"
            + "\n\texpected: "
            + System.identityHashCode(tmp) + "@" + factoryClass.getName()
            + "\n\tactual:   "
            + System.identityHashCode(ctxt) + "@" + ((JAXBContextImpl)ctxt).creator.getName());
    }
}
 
Example #28
Source File: LogicalMessageImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void setPayload(Object payload, JAXBContext context) {
    if (context == null) {
            setPayload(payload, defaultJaxbContext);
    }
    if (payload == null) {
        lm = new EmptyLogicalMessageImpl();
    } else {
        lm = new JAXBLogicalMessageImpl(context, payload);
    }
}
 
Example #29
Source File: Generator.java    From DataDefender with Apache License 2.0 5 votes vote down vote up
/**
 * Write requirement to file.
 * @param requirement
 * @param outFile
 * @throws DatabaseException
 */
public static void write(final Requirement requirement, final File outFile) throws DatabaseException, JAXBException, SAXException {
    log.info("Requirement.write() to file: " + outFile.getName());

    final JAXBContext jc = JAXBContext.newInstance(Requirement.class);
    final Marshaller  marshaller = jc.createMarshaller();
    final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final Schema schema = schemaFactory.newSchema(Generator.class.getResource("requirement.xsd"));

    marshaller.setSchema(schema);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(requirement, outFile);
}
 
Example #30
Source File: DataHolder.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Return the handled data.
 *
 * @return the data, ready to use
 */
public T getData ()
{
    if (data == null) {
        final Book book = sheet.getStub().getBook();

        try {
            book.getLock().lock();

            if (data == null) {
                JAXBContext jaxbContext = JAXBContext.newInstance(classe);
                Unmarshaller um = jaxbContext.createUnmarshaller();

                // Open book file system
                Path dataFile = book.openSheetFolder(sheet.getStub().getNumber()).resolve(
                        pathString);
                logger.debug("path: {}", dataFile);

                try (InputStream is = Files.newInputStream(dataFile, StandardOpenOption.READ)) {
                    data = (T) um.unmarshal(is);
                }

                logger.info("Loaded {}", dataFile);
                dataFile.getFileSystem().close(); // Close book file system
            }
        } catch (IOException |
                 JAXBException ex) {
            logger.warn("Error unmarshalling from {}", pathString, ex);
        } finally {
            book.getLock().unlock();
        }
    }

    return data;
}