Java Code Examples for javax.xml.bind.JAXBContext#newInstance()

The following examples show how to use javax.xml.bind.JAXBContext#newInstance() . These examples are extracted from open source projects. 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 Project: cxf   File: LogicalMessageImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetPayloadOfJAXB() throws Exception {
    //using Dispatch
    JAXBContext ctx = JAXBContext.newInstance(ObjectFactory.class);
    Message message = new MessageImpl();
    Exchange e = new ExchangeImpl();
    message.setExchange(e);
    LogicalMessageContextImpl lmci = new LogicalMessageContextImpl(message);

    JAXBElement<AddNumbers> el = new ObjectFactory().createAddNumbers(req);

    LogicalMessageImpl lmi = new LogicalMessageImpl(lmci);
    lmi.setPayload(el, ctx);

    Object obj = lmi.getPayload(ctx);
    assertTrue(obj instanceof JAXBElement);
    JAXBElement<?> el2 = (JAXBElement<?>)obj;
    assertTrue(el2.getValue() instanceof AddNumbers);
    AddNumbers resp = (AddNumbers)el2.getValue();
    assertEquals(req.getArg0(), resp.getArg0());
    assertEquals(req.getArg1(), resp.getArg1());
}
 
Example 2
@Test
public void testInvokeWithJAXBPayloadModeXMLBinding() throws Exception {
    URL wsdl = getClass().getResource("/wsdl/addNumbers.wsdl");
    assertNotNull(wsdl);

    XMLService service = new XMLService();
    assertNotNull(service);

    JAXBContext jc = JAXBContext.newInstance("org.apache.hello_world_xml_http.wrapped.types");
    Dispatch<Object> disp = service.createDispatch(portNameXML, jc, Mode.PAYLOAD);
    setAddress(disp, greeterAddress);

    TestHandlerXMLBinding handler = new TestHandlerXMLBinding();
    addHandlersProgrammatically(disp, handler);

    org.apache.hello_world_xml_http.wrapped.types.GreetMe req =
        new org.apache.hello_world_xml_http.wrapped.types.GreetMe();
    req.setRequestType("tli");

    Object response = disp.invoke(req);
    assertNotNull(response);
    org.apache.hello_world_xml_http.wrapped.types.GreetMeResponse value =
        (org.apache.hello_world_xml_http.wrapped.types.GreetMeResponse)response;
    assertEquals("Hello tli", value.getResponseType());
}
 
Example 3
Source Project: juddi   File: AuthenticatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateJuddiUsers() throws Exception
{
           System.out.println("testCreateJuddiUsers");
	try {
		JuddiUsers juddiUsers = new JuddiUsers();
		juddiUsers.getUser().add(new User("anou_mana","password"));
		juddiUsers.getUser().add(new User("bozo","clown"));
		juddiUsers.getUser().add(new User("sviens","password"));
		
		StringWriter writer = new StringWriter();
		JAXBContext context = JAXBContext.newInstance(juddiUsers.getClass());
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		marshaller.marshal(juddiUsers, writer);
		logger.info("\n" +  writer.toString());
	} catch (Exception e) {
		logger.error(e.getMessage(),e);
		Assert.fail("unexpected");
	}
}
 
Example 4
@Override
public Map<String, List<String>> getMetadataMapping() {
    Map<String, List<String>> cachedMapping = this.getCacheWrapper().getMetadataMapping();
    if (null != cachedMapping) {
        return cachedMapping;
    }
    Map<String, List<String>> mapping = new HashMap<>();
    try {
        String xmlConfig = this.getConfigManager().getConfigItem(JacmsSystemConstants.CONFIG_ITEM_RESOURCE_METADATA_MAPPING);
        InputStream stream = new ByteArrayInputStream(xmlConfig.getBytes(StandardCharsets.UTF_8));
        JAXBContext context = JAXBContext.newInstance(JaxbMetadataMapping.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        JaxbMetadataMapping jaxbMapping = (JaxbMetadataMapping) unmarshaller.unmarshal(stream);
        jaxbMapping.getFields().stream().forEach(m -> {
            String key = m.getKey();
            String csv = m.getValue();
            List<String> metadatas = (!StringUtils.isBlank(csv)) ? Arrays.asList(csv.split(",")) : new ArrayList<>();
            mapping.put(key, metadatas);
        });
        this.getCacheWrapper().updateMetadataMapping(mapping);
    } catch (Exception e) {
        logger.error("Error Extracting resource metadata mapping", e);
        throw new RuntimeException("Error Extracting resource metadata mapping", e);
    }
    return mapping;
}
 
Example 5
Source Project: servicemix   File: Client.java    License: Apache License 2.0 6 votes vote down vote up
public void postPerson(Person person) throws Exception{
    System.out.println("\n### POST PERSON -> ");
    HttpURLConnection connection = connect(PERSON_SERVICE_URL + "person/post/");
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "application/xml");

    JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    // pretty xml output
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    jaxbMarshaller.marshal(person, System.out);
    jaxbMarshaller.marshal(person, connection.getOutputStream());

    System.out.println("\n### POST PERSON RESPONSE");
    System.out.println("Status: " + connection.getResponseCode() +  " " + 
            connection.getResponseMessage());
    System.out.println("Location: " + connection.getHeaderField("Location"));
}
 
Example 6
@Override
public void setUp() {
    try {
        JAXBContext context = JAXBContext.newInstance(AtomFeed.class);
        // File file = new File("test/testatom.xml");
        File file = new File("test/flickr.atom");
        feed = (AtomFeed) context.createUnmarshaller().unmarshal(file);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}
 
Example 7
Source Project: juddi   File: AuthInfoTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test handling of utf8 characters
 */
@Test
public void unmarshallUTF8()
{
	try {
		JAXBContext jaxbContext=JAXBContext.newInstance("org.uddi.api_v3");
		Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
		StringReader reader = new StringReader(EXPECTED_UTF8_XML_FRAGMENT1);
		JAXBElement<AuthToken> utf8Element = unMarshaller.unmarshal(new StreamSource(reader),AuthToken.class);
		String infoString = utf8Element.getValue().getAuthInfo();
		assertEquals(UTF8_WORD, infoString);
	} catch (JAXBException jaxbe) {
		fail("No exception should be thrown");
	}
}
 
Example 8
private static JAXBContext getW3CJaxbContext() {
    try {
        return JAXBContext.newInstance(W3CEndpointReference.class);
    } catch (JAXBException e) {
        throw new WebServiceException("Error creating JAXBContext for W3CEndpointReference. ", e);
    }
}
 
Example 9
private static UserManagement convertXMLToUser(String xmlString) throws JAXBException {
	JAXBContext jaxbContext = null;

	jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
	Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
	StringReader reader = new StringReader(xmlString);
	UserManagement objectElement = (UserManagement) jaxbUnmarshaller.unmarshal(reader);
	return objectElement;
}
 
Example 10
private JAXBContext getJaxbContext ()
        throws JAXBException
{
    // Lazy creation
    if (jaxbContext == null) {
        jaxbContext = JAXBContext.newInstance(GlyphValue.class);
    }

    return jaxbContext;
}
 
Example 11
private void setConfigFromXML() {
    if (configurationFile.file().isPresent()) {
        final File configFile = configurationFile.file().get();
        log.debug("Reading configuration file {}", configFile);

        try {
            final Class<?>[] classes = ImmutableList.<Class<?>>builder().add(getConfigEntityClass())
                    .addAll(getInheritedEntityClasses())
                    .build()
                    .toArray(new Class<?>[0]);

            final JAXBContext context = JAXBContext.newInstance(classes);
            final Unmarshaller unmarshaller = context.createUnmarshaller();

            //replace environment variable placeholders
            String configFileContent = new String(Files.readAllBytes(configFile.toPath()), StandardCharsets.UTF_8);
            configFileContent = envVarUtil.replaceEnvironmentVariablePlaceholders(configFileContent);
            final ByteArrayInputStream is =
                    new ByteArrayInputStream(configFileContent.getBytes(StandardCharsets.UTF_8));
            final StreamSource streamSource = new StreamSource(is);

            setConfiguration(unmarshaller.unmarshal(streamSource, getConfigEntityClass()).getValue());

        } catch (final Exception e) {
            if (e.getCause() instanceof UnrecoverableException) {
                if (((UnrecoverableException) e.getCause()).isShowException()) {
                    log.error("An unrecoverable Exception occurred. Exiting HiveMQ", e);
                    log.debug("Original error message:", e);
                }
                System.exit(1);
            }
            log.error("Could not read the configuration file {}. Using default config", configFile.getAbsolutePath());
            log.debug("Original error message:", e);
            setConfiguration(getDefaultConfig());
        }
    } else {
        setConfiguration(getDefaultConfig());
    }
}
 
Example 12
Source Project: attic-apex-malhar   File: XmlParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void activate(Context context)
{
  try {
    JAXBContext ctx = JAXBContext.newInstance(getClazz());
    unmarshaller = ctx.createUnmarshaller();
    if (schemaXSDFile != null) {
      unmarshaller.setSchema(schema);
    }
  } catch (JAXBException e) {
    DTThrowable.wrapIfChecked(e);
  }
}
 
Example 13
public void saveData(String routeId) {
	Schema schema = null;
	SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

	try {
		schema = sf.newSchema(new File("./data/static_data/npc_walker/npc_walker.xsd"));
	}
	catch (SAXException e1) {
		log.error("Error while saving data: " + e1.getMessage(), e1.getCause());
		return;
	}

	File xml = new File("./data/static_data/npc_walker/generated_npc_walker_" + routeId + ".xml");
	JAXBContext jc;
	Marshaller marshaller;
	try {
		jc = JAXBContext.newInstance(WalkerData.class);
		marshaller = jc.createMarshaller();
		marshaller.setSchema(schema);
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.marshal(this, xml);
	}
	catch (JAXBException e) {
		log.error("Error while saving data: " + e.getMessage(), e.getCause());
		return;
	}
	finally {
		if (walkerlist != null) {
			walkerlist.clear();
			walkerlist = null;
		}
	}
}
 
Example 14
Source Project: proarc   File: NdkExport.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Info getInfo(File infoFile) throws JAXBException {
    if (infoFile == null) {
        return null;
    }
    JAXBContext jaxbContext = JAXBContext.newInstance(Info.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    return (Info) unmarshaller.unmarshal(infoFile);
}
 
Example 15
@Test
public void contextIsSuccessfullyCreated() throws JAXBException {
	final JAXBContext context = JAXBContext.newInstance(Gh1.class);
	final Gh1 value = new Gh1();
	value.getAs().add("a");
	value.getBs().add(2);
	value.getMixedContent().add("Test");

	final StringWriter sw = new StringWriter();
	context.createMarshaller().marshal(
			new JAXBElement<Gh1>(new QName("test"), Gh1.class, value), System.out);
	context.createMarshaller().marshal(
			new JAXBElement<Gh1>(new QName("test"), Gh1.class, value), sw);
	Assert.assertTrue(sw.toString().contains("Test"));
}
 
Example 16
public static MessageSchema unmarshall(InputStream inputStream) throws SchemaUnmarshallingException {
    try {
        final JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName());
        final Unmarshaller unmarshaller = jc.createUnmarshaller();
        final InputSource is = new InputSource(new InputStreamReader(inputStream));
        final XMLReader reader = XMLReaderFactory.createXMLReader();
        final NamespaceFilter filter = new NamespaceFilter(NAMESPACE, false);
        filter.setParent(reader);
        final SAXSource source = new SAXSource(filter, is);
        unmarshaller.setEventHandler(event -> false);
        return (MessageSchema) unmarshaller.unmarshal(source);
    } catch (Exception e) {
        throw new SchemaUnmarshallingException("Failed to parse MDP Schema: " + e.getMessage(), e);
    }
}
 
Example 17
@Before
public void setUp() throws Exception {
	context = JAXBContext.newInstance(getClass().getPackage().getName());
}
 
Example 18
Source Project: bluima   File: TestSuiteCorpusParser.java    License: Apache License 2.0 4 votes vote down vote up
private JAXBContext getSingleton() throws JAXBException {
if (jcSing == null)
    jcSing = JAXBContext.newInstance(TestSuiteCorpus.class.getPackage()
	    .getName());
return jcSing;
   }
 
Example 19
Source Project: fix-orchestra   File: StateGenerator.java    License: Apache License 2.0 4 votes vote down vote up
private Repository unmarshal(final InputStream inputStream) throws JAXBException {
  final JAXBContext jaxbContext = JAXBContext.newInstance(Repository.class);
  final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
  jaxbUnmarshaller.setEventHandler(unmarshallerErrorHandler);
  return (Repository) jaxbUnmarshaller.unmarshal(inputStream);
}
 
Example 20
Source Project: OpenEstate-IO   File: OpenImmoUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Initializes the {@link JAXBContext} for this format.
 *
 * @param classloader the classloader to load the generated JAXB classes with
 * @throws JAXBException if a problem with JAXB occurred
 */
public synchronized static void initContext(ClassLoader classloader) throws JAXBException {
    JAXB = JAXBContext.newInstance(PACKAGE, classloader);
}