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

The following examples show how to use javax.xml.bind.JAXBContext#createMarshaller() . 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
public boolean SaveCustomDrops()
{
    try
    {
        JAXBContext tJaxbCtx = JAXBContext.newInstance(CustomDrops.class);
        Marshaller jaxMarsh = tJaxbCtx.createMarshaller();
        jaxMarsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxMarsh.marshal(_mCustomDrops, new FileOutputStream(_mConfigFileName, false));

        _mLogger.debug("Config file written");
        return true;
    }
    catch (Exception e)
    {
        _mLogger.error("Unable to create new CustomDrops.xml. What did you do??");
        e.printStackTrace();
        return false;
    }
}
 
Example 2
protected String marshall(Object result, MediaType mediaType) throws Throwable {
	if (null != mediaType && mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
		JSONProvider jsonProvider = (JSONProvider) super.getApplicationContext().getBean("jsonProvider");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		jsonProvider.writeTo(result, result.getClass().getGenericSuperclass(), 
				result.getClass().getAnnotations(), mediaType, null, baos);
		return new String(baos.toByteArray(), "UTF-8");
	} else {
		JAXBContext context = JAXBContext.newInstance(result.getClass());
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.setProperty("com.sun.xml.bind.marshaller.CharacterEscapeHandler", new CDataCharacterEscapeHandler());
		StringWriter writer = new StringWriter();
		marshaller.marshal(result, writer);
		return writer.toString();
	}
}
 
Example 3
Source Project: arcusplatform   File: BehaviorCatalog.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized void init() {
   try{
      URL url = Resources.getResource("com/iris/common/subsystem/care/behavior/behavior_catalog.xml");
      JAXBContext context = JAXBContext.newInstance(BehaviorCatalog.class);
      Marshaller m = context.createMarshaller();
      BehaviorCatalog catalog = (BehaviorCatalog) context.createUnmarshaller().unmarshal(url);
      behavior = catalog.getBehavior();
      behaviorMap = new HashMap<String, BehaviorCatalog.BehaviorCatalogTemplate>(behavior.size());
      for (BehaviorCatalogTemplate catTemplate : behavior){
         behaviorMap.put(catTemplate.id, catTemplate);
      }

   }catch (Exception e){
      throw new RuntimeException(e);
   }
}
 
Example 4
Source Project: secure-data-service   File: JaxbUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Marshal the provided object using the OutputStream specified
 *
 * @param objectToMarshal
 * @param outputStream
 * @throws JAXBException
 */
public static void marshal(Object objectToMarshal, OutputStream outputStream) throws JAXBException {
    if (objectToMarshal != null) {
        long startTime = System.currentTimeMillis();
        
        JAXBContext context = JAXBContext.newInstance(objectToMarshal.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
        marshaller.marshal(objectToMarshal, outputStream);

        System.out.println("marshaled " + objectToMarshal.getClass() + " in: "
                + (System.currentTimeMillis() - startTime));
    } else {
        throw new IllegalArgumentException("Cannot marshal null object");
    }
}
 
Example 5
/**
 * This operation insures that IReader interface is implemented as described
 * by the XML persistence provider and that the operations function.
 * 
 * @throws JAXBException
 *             JAXB could not load
 * @throws CoreException
 *             Eclispe Resources could not read the file
 */
@Test
public void checkIReaderOperations() throws JAXBException, CoreException {

	// Create a Form
	Form form = new Form();
	form.setName("The artist formerly known as Prince");
	IFile file = project.getFile("ireader_test_form.xml");

	// Create a context and write the Form to a stream
	JAXBContext jaxbContext = JAXBContext.newInstance(Form.class);
	Marshaller marshaller = jaxbContext.createMarshaller();
	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	marshaller.marshal(form, outputStream);
	// Convert it to an input stream so it can be pushed to file
	ByteArrayInputStream inputStream = new ByteArrayInputStream(
			outputStream.toByteArray());
	// Update the output file if it already exists
	if (file.exists()) {
		file.setContents(inputStream, IResource.FORCE, null);
	} else {
		// Or create it from scratch
		file.create(inputStream, IResource.FORCE, null);
	}

	// Read the Form back in with the provider
	Form loadedForm = xmlpp.read(file);
	assertNotNull(loadedForm);
	assertEquals(loadedForm, form);

	return;
}
 
Example 6
Source Project: rice   File: JAXBAssert.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Performs the following steps and assertions:
 * 
 * <ol>
 *   <li>Creates a new JAXBContext with the given list of classesToBeBound.</li>
 *   <li>Marshals the provided objectToMarshall to XML.</li>
 *   <li>Unmarshals the marshaled XML to recreate the original object.<li>
 *   <li>Asserts that the newly unmarhsaled object and the original provided object are equal by invoking {@link Object#equals(Object)}.</li>
 *   <li>Unmarshals the given expectedXml to an object and asserts that it is equal with the original unmarshaled object by invoking {@link Object#equals(Object)}.</li>
 * </ol>  
 *  
 * @param objectToMarshal the object to marshal to XML using JAXB
 * @param expectedXml an XML string that will be unmarshaled to an Object and compared with objectToMarshal using {@link Object#equals(Object)}
 * @param classesToBeBound - list of java classes to be recognized by the created JAXBContext
 * 
 */
public static void assertEqualXmlMarshalUnmarshal(Object objectToMarshal, String expectedXml, Class<?> ... classesToBeBound) {
	String marshaledXml = null;
	try {
	  JAXBContext jaxbContext = JAXBContext.newInstance(classesToBeBound);
	  Marshaller marshaller = jaxbContext.createMarshaller();
	  
	  StringWriter stringWriter = new StringWriter();
	  
	  marshaller.marshal(objectToMarshal, stringWriter);

	  marshaledXml = stringWriter.toString();
	  
	  Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
	  
	  Object actual = unmarshaller.unmarshal(new StringReader(stringWriter.toString()));
	  assertEquals("Unmarshalled object should be equal to original objectToMarshall.", objectToMarshal, actual);
	  
	  Object expected = unmarshaller.unmarshal(new StringReader(expectedXml.trim()));
	  assertEquals("Unmarshalled objects should be equal.", expected, actual);
	} catch (Throwable e) {
		System.err.println("Outputting marshaled XML from failed assertion:\n" + marshaledXml);
		if (e instanceof RuntimeException) {
			throw (RuntimeException)e;
		} else if (e instanceof Error) {
			throw (Error)e;
		}
		throw new RuntimeException("Failed to marshall/unmarshall with JAXB.  See the nested exception for details.", e);
	}
}
 
Example 7
public static void generate(SpecRegistry registry , String javaBasePath, String resourcesBasePath, boolean mysql) throws Exception {
    for (DefinitionsSpec playSpec: registry.getDefinitions()) {

        int i = playSpec.getNamespace().lastIndexOf('.');
        final String name = playSpec.getNamespace().substring(i+1, playSpec.getNamespace().length());

        if (mysql) {
            playSpec = MySqlSpecConverter.convertSpec(playSpec);
        }

        JAXBContext jc = JAXBContext.newInstance(SpecRegistry.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        String basePackagePath = playSpec.getNamespace().replace('.', '/');

        File file = new File(resourcesBasePath + "/" + basePackagePath + "/schema/" + name + "-spec.xml");
        file.getParentFile().mkdirs();
        try (FileOutputStream fout = new FileOutputStream(file); ) {
            marshaller.marshal(registry, fout);
        }

        GenerateDatabaseScript gen = new GenerateMySqlDatabaseScript();

        try ( Writer out = new FileWriter(resourcesBasePath + "/" + basePackagePath + "/schema/" + name + "-schema.sql") ) {
            out.write("/*\n--- Schema generated by Sort static definitions \n*/");
            out.write(gen.generateScript(playSpec));
            out.flush();
        }

        GenerateEnums generateEnums = new GenerateEnums();
        generateEnums.generateEnums(javaBasePath, playSpec);

        GenerateProxyModels generateDataModels = new GenerateProxyModels();
        generateDataModels.generateDataModels(javaBasePath, playSpec);

        GenerateQueryModels generateQueryModels = new GenerateQueryModels();
        generateQueryModels.generateQueryModels(javaBasePath, playSpec);
    }
}
 
Example 8
Source Project: ph-commons   File: JAXBContextCacheTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMarshalStringWithClassLoader () throws JAXBException
{
  final String sMsg = "Hello world";
  final JAXBContext aCtx = JAXBContextCache.getInstance ()
                                           .getFromCache (String.class, ClassLoaderHelper.getSystemClassLoader ());
  final Marshaller m = aCtx.createMarshaller ();
  final NonBlockingStringWriter aSW = new NonBlockingStringWriter ();
  m.marshal (new JAXBElement <> (new QName ("element"), String.class, sMsg), aSW);
  assertEquals ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><element>" + sMsg + "</element>",
                aSW.getAsString ());
}
 
Example 9
@Override
public void writeTo(TopologiesResource.SimpleTopologyWrapper instance, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
  try {
    Map<String, Object> properties = new HashMap<>(1);
    properties.put( JAXBContextProperties.MEDIA_TYPE, mediaType.toString());
    JAXBContext context = JAXBContext.newInstance(new Class[]{TopologiesResource.SimpleTopologyWrapper.class}, properties);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(instance, entityStream);

  } catch (JAXBException e) {
    throw new IOException(e);
  }
}
 
Example 10
Source Project: XACML   File: XACMLPolicyWriter.java    License: MIT License 5 votes vote down vote up
/**
 * Helper static class that does the work to write a policy set to an output stream.
 * 
 * @param os
 * @param policy
 */
public static void writePolicyFile(OutputStream os, PolicyType policy) {
	JAXBElement<PolicyType> policySetElement = new ObjectFactory().createPolicy(policy);		
	try {
		JAXBContext context = JAXBContext.newInstance(PolicyType.class);
		Marshaller m = context.createMarshaller();
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		m.marshal(policySetElement, os);
	} catch (JAXBException e) {
		logger.error(MSG_WRITE, e);
	}
}
 
Example 11
public void printInterchangeStudentAssessment(PrintStream ps) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(InterchangeStudentAssessment.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);

    InterchangeStudentAssessment interchangeStudentAssessment = new InterchangeStudentAssessment();

    List<Object> list = interchangeStudentAssessment.getStudentReferenceOrAssessmentReferenceOrStudentAssessment();

    // StudentAssessment
    // StudentObjectiveAssessment
    // StudentAssessmentItem

    marshaller.marshal(interchangeStudentAssessment, ps);
}
 
Example 12
/**
 * Convert StoreOperationInput XML to string.
 *
 * @param jaxbContext
 *            JAXBContext
 * @param o
 *            StoreOperationInput
 * @return StoreOperationInput as String
 * @throws JAXBException
 *             Exception if unable to convert
 */
public static String asString(JAXBContext jaxbContext,
        Object o) throws JAXBException {

    java.io.StringWriter sw = new StringWriter();

    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    marshaller.marshal(o, sw);

    return sw.toString();
}
 
Example 13
public static String toString(JAXBContext context, Object object)
		throws JAXBException {
	final Marshaller marshaller = context.createMarshaller();
	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
	final StringWriter sw = new StringWriter();
	marshaller.marshal(object, sw);
	return sw.toString();
}
 
Example 14
/**
 * Transforms an annotated Object to a XML string using javax.xml.bind.Marshaller
 *
 * @param object to transform to a XML String
 * @return a XML string representing the object
 * @throws IOException if is not possible to parse the object
 */
public static String ObjectToXml(Object object) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
    Marshaller marshaller = jaxbContext.createMarshaller();
    StringWriter sw = new StringWriter();
    marshaller.marshal(object, sw);
    return sw.toString();
}
 
Example 15
Source Project: phoenix   File: ConfigurationParserTest.java    License: Apache License 2.0 4 votes vote down vote up
private String writeXML() {
     DataModel data = new DataModel();
     try {
         DataValue dataValue = new DataValue();
         dataValue.setDistribution(20);
         dataValue.setValue("jnhgGhHminwiajn");
         List<DataValue> dataValueList = new ArrayList<>();
         dataValueList.add(dataValue);
         Column column = new Column();
         column.setLength(15);
         column.setDataSequence(DataSequence.RANDOM);
         column.setName("TEST_COL");
         column.setUserDefined(true);
         column.setDataValues(dataValueList);
         List<Column> columnList = new ArrayList<>();
         columnList.add(column);

         data.setDataMappingColumns(columnList);

         Scenario scenario = new Scenario();
         scenario.setName("scenario1");
         scenario.setTenantId("00DXXXXXX");
     	List<Ddl> preScenarioDdls = new ArrayList<Ddl>();
     	preScenarioDdls.add(new Ddl("CREATE INDEX IF NOT EXISTS ? ON FHA (NEWVAL_NUMBER) ASYNC", "FHAIDX_NEWVAL_NUMBER"));
     	preScenarioDdls.add(new Ddl("CREATE LOCAL INDEX IF NOT EXISTS ? ON FHA (NEWVAL_NUMBER)", "FHAIDX_NEWVAL_NUMBER"));
scenario.setPreScenarioDdls(preScenarioDdls);
         scenario.setPhoenixProperties(new HashMap<String, String>());
         scenario.getPhoenixProperties().put("phoenix.query.threadPoolSize", "200");
         scenario.setDataOverride(new DataOverride());
         scenario.setTableName("tableName");
         scenario.setRowCount(10);
         QuerySet querySet = new QuerySet();
         querySet.setExecutionType(ExecutionType.PARALLEL);
         querySet.setExecutionDurationInMs(10000);
         scenario.getQuerySet().add(querySet);
         Query query = new Query();
         querySet.getQuery().add(query);
         querySet.setConcurrency("15");
         querySet.setNumberOfExecutions(20);
         query.setStatement("select * from FHA");
         Scenario scenario2 = new Scenario();
         scenario2.setName("scenario2");
         scenario2.setPhoenixProperties(new HashMap<String, String>());
         scenario2.setDataOverride(new DataOverride());
         scenario2.setTableName("tableName2");
         scenario2.setRowCount(500);
         List<Scenario> scenarios = new ArrayList<Scenario>();
         scenarios.add(scenario);
         scenarios.add(scenario2);
         data.setScenarios(scenarios);

         // create JAXB context and initializing Marshaller
         JAXBContext jaxbContext = JAXBContext.newInstance(DataModel.class);
         Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

         // for getting nice formatted output
         jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

         // Writing to console
         jaxbMarshaller.marshal(data, System.out);
     } catch (JAXBException e) {
         // some exception occured
         e.printStackTrace();
     }
     return data.toString();
 }
 
Example 16
Source Project: training   File: JAXBExample.java    License: MIT License 4 votes vote down vote up
public static void main(String[] args) throws JAXBException {
	JAXBContext context = JAXBContext.newInstance("org.example.employee:org.example.address");

	Marshaller marshaller = context.createMarshaller();
	// Employee employee = new Employee();

	Unmarshaller um = context.createUnmarshaller();
	InputStream resourceAsStream = JAXBExample.class.getResourceAsStream("/xsd/employee-instance.xml");
	Employee employee = (Employee) ((JAXBElement) um.unmarshal(resourceAsStream)).getValue();

	System.out.println("Read employee");
	employee.getName().setFirstName("Mike");

	marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
	
	marshaller.marshal(new ObjectFactory().createEmployee(employee), System.out);

}
 
Example 17
public XmlBindingTool(Class<E> rootElementClass) throws JAXBException {
   JAXBContext context = JAXBContext.newInstance(rootElementClass);
   this.unmarshaller = context.createUnmarshaller();
   this.marshaller = context.createMarshaller();
   this.marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
}
 
Example 18
/**
 * Create an info.xml file for the toolkit.
 * @throws URISyntaxException 
 */
private void addToolkitInfo(File toolkitRoot, JsonObject jsonGraph) throws JAXBException, FileNotFoundException, IOException, URISyntaxException  {
    File infoFile = new File(toolkitRoot, "info.xml");
    
    ToolkitInfoModelType info = new ToolkitInfoModelType();
    final String namespace = GraphKeys.splAppNamespace(jsonGraph);
    final boolean haveNamespace = namespace != null && !namespace.isEmpty();
    info.setIdentity(new IdentityType());
    // toolkit name in info.xml
    if (haveNamespace) {
        info.getIdentity().setName(namespace + "." + GraphKeys.splAppName(jsonGraph));
    } else {
        info.getIdentity().setName(GraphKeys.splAppName(jsonGraph));
    }
    info.getIdentity().setDescription(new DescriptionType());
    info.getIdentity().setVersion("1.0.0." + System.currentTimeMillis());
    info.getIdentity().setRequiredProductVersion(jstring(object(jsonGraph, "config"), CFG_STREAMS_VERSION));
          
    DependenciesType dependencies = new DependenciesType();
    
    List<ToolkitDependencyType> toolkits = dependencies.getToolkit();
    
    GsonUtilities.objectArray(object(jsonGraph, "config", "spl"), TOOLKITS_JSON, tk -> {
        ToolkitDependencyType depTkInfo;
        String root = jstring(tk, "root");
        if (root != null) {
            try {
                depTkInfo = TkInfo.getTookitDependency(root, false);
                // Handle missing info.xml
                if (depTkInfo == null)
                    return;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            depTkInfo = new ToolkitDependencyType();
            
            depTkInfo.setName(jstring(tk, "name"));
            depTkInfo.setVersion(jstring(tk, "version"));
        }
        toolkits.add(depTkInfo);
    });
    
    File topologyToolkitRoot = TkInfo.getTopologyToolkitRoot();
    toolkits.add(TkInfo.getTookitDependency(topologyToolkitRoot.getAbsolutePath(), true));
    
    info.setDependencies(dependencies);
    
    
    JAXBContext context = JAXBContext
            .newInstance(ObjectFactory.class);
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    try (FileOutputStream out = new FileOutputStream(infoFile)) {
        m.marshal(info, out);
    }
}
 
Example 19
/**
 * Dumps this model into XML.
 *
 * For debug only.
 *
 * TODO: not sure if this actually works. We don't really know what are T,C.
 */
public void dump( Result out ) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(this.getClass());
    Marshaller m = context.createMarshaller();
    m.marshal(this,out);
}
 
Example 20
/**
 * Dumps this model into XML.
 *
 * For debug only.
 *
 * TODO: not sure if this actually works. We don't really know what are T,C.
 */
public void dump( Result out ) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(this.getClass());
    Marshaller m = context.createMarshaller();
    m.marshal(this,out);
}