Java 类javax.xml.bind.JAXBContext 实例源码

项目:MFM    文件:MAMEtoJTree.java   
/**
 * This is simply to provide MAME input to test this class
 */
private static Mame JAXB() throws JAXBException, MAMEexe.MAME_Exception {
    Mame mame = null;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Phweda.MFM.mame.Mame.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        // hard code path to mame exe
        MAMEexe.setBaseArgs("E:\\Test\\177\\mame64.exe");
        ArrayList<String> args = new ArrayList<String>(Arrays.asList("-listxml", "*"));
        Process process = MAMEexe.run(args);
        InputStream inputStream = process.getInputStream();
        mame = (Mame) jaxbUnmarshaller.unmarshal(inputStream);

        System.out.println("Machines" + mame.getMachine().size());
    } catch (JAXBException | MAMEexe.MAME_Exception e) {
        e.printStackTrace();
        throw e;
    }
    return mame;
}
项目:litiengine    文件:GameFile.java   
private static GameFile getGameFileFromFile(String file) throws JAXBException, IOException {
  final JAXBContext jaxbContext = JAXBContext.newInstance(GameFile.class);
  final Unmarshaller um = jaxbContext.createUnmarshaller();
  try (InputStream inputStream = FileUtilities.getGameResource(file)) {

    // try to get compressed game file
    final GZIPInputStream zipStream = new GZIPInputStream(inputStream);
    return (GameFile) um.unmarshal(zipStream);
  } catch (final ZipException e) {

    // if it fails to load the compressed file, get it from plain XML
    InputStream stream = null;
    stream = FileUtilities.getGameResource(file);
    if (stream == null) {
      return null;
    }

    return (GameFile) um.unmarshal(stream);
  }
}
项目:Java-9-Cookbook    文件:HelloWorldXml.java   
public static void main(String[] args) throws JAXBException{
  //create instance of JAXBContext with the class we want to serialize into XML
  JAXBContext jaxb = JAXBContext.newInstance(Messages.class);

  //create a marshaller which will do the task of generating xml
  Marshaller marshaller = jaxb.createMarshaller();

  //setting the property of marshaller to not add the <? xml> tag
  marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

  StringWriter writer = new StringWriter();

  //serialze the Messages instance and send the string to the writer
  marshaller.marshal(new Messages(), writer);

  //get the XML from the writer
  System.out.println(writer.toString());
}
项目:hashsdn-controller    文件:FeatureConfigSnapshotHolder.java   
public FeatureConfigSnapshotHolder(final ConfigFileInfo fileInfo,
                                   final Feature feature) throws JAXBException, XMLStreamException {
    Preconditions.checkNotNull(fileInfo);
    Preconditions.checkNotNull(fileInfo.getFinalname());
    Preconditions.checkNotNull(feature);
    this.fileInfo = fileInfo;
    this.featureChain.add(feature);
    // TODO extract utility method for umarshalling config snapshots
    JAXBContext jaxbContext = JAXBContext.newInstance(ConfigSnapshot.class);
    Unmarshaller um = jaxbContext.createUnmarshaller();
    XMLInputFactory xif = XMLInputFactory.newFactory();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);

    XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(new File(fileInfo.getFinalname())));
    unmarshalled = (ConfigSnapshot) um.unmarshal(xsr);
}
项目:AgentWorkbench    文件:ProjectExportController.java   
/**
 * Loads the simulation setup with the specified name
 * @param setupName The setup to be loaded
 * @return The setup
 * @throws JAXBException Parsing the setup file failed
 * @throws IOException Reading the setup file failed
 */
private SimulationSetup loadSimSetup(String setupName) throws JAXBException, IOException {
    // --- Determine the setup file path ----------
    String setupFileName = this.project.getSimulationSetups().get(setupName);
    String setupFileFullPath = this.project.getSubFolder4Setups(true) + File.separator + setupFileName;
    File setupFile = new File(setupFileFullPath);

    // --- Load the setup -------------
    JAXBContext pc;
    SimulationSetup simSetup = null;
    pc = JAXBContext.newInstance(this.project.getSimulationSetups().getCurrSimSetup().getClass());
    Unmarshaller um = pc.createUnmarshaller();
    FileReader fr = new FileReader(setupFile);
    simSetup = (SimulationSetup) um.unmarshal(fr);
    fr.close();

    return simSetup;

}
项目:CharmMylynConnector    文件:CharmTaskMessageBodyWriter.java   
@Override
public void writeTo(CharmTask charmTask, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {

    try {

        JAXBContext context = JAXBContext.newInstance(CharmTask.class);
        Marshaller taskMarshaller = context.createMarshaller();
        taskMarshaller.marshal(charmTask, entityStream);

    } catch (JAXBException e) {
        throw new ProcessingException("Error serializing Charm Task to output stream");
    }

}
项目:openjdk-jdk10    文件:JAXBContextFactory.java   
/**
 * 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);
}
项目:framework    文件:JaxbParser.java   
/**
 * 转为xml串
 *
 * @param obj
 * @return
 */
public String toXML(Object obj) {
    String result = null;
    try {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.setProperty(Marshaller.JAXB_FRAGMENT, true);// 去掉报文头
        OutputStream os = new ByteArrayOutputStream();
        XMLSerializer serializer = getXMLSerializer(os);
        m.marshal(obj, serializer.asContentHandler());
        result = os.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    logger.info("response text:" + result);
    return result;
}
项目:Proyecto-DASI    文件:SchemaHelper.java   
/** Serialise the object to an XML string
 * @param obj the object to be serialised
 * @param objclass the class of the object to be serialised
 * @return an XML string representing the object, or null if the object couldn't be serialised
 * @throws JAXBException 
 */

static private JAXBContext getJAXBContext(Class<?> objclass) throws JAXBException
{
    JAXBContext jaxbContext;
    if (jaxbContentCache.containsKey(objclass.getName()))
    {
        jaxbContext = jaxbContentCache.get(objclass.getName());
    }
    else
    {
        jaxbContext = JAXBContext.newInstance(objclass);
        jaxbContentCache.put(objclass.getName(), jaxbContext);
    }
    return jaxbContext;
}
项目:dss-demonstrations    文件:XSLTServiceTest.java   
@Test
public void generateSimpleReport() throws Exception {
    JAXBContext context = JAXBContext.newInstance(SimpleReport.class.getPackage().getName());
    Unmarshaller unmarshaller = context.createUnmarshaller();
    Marshaller marshaller = context.createMarshaller();

    SimpleReport simpleReport = (SimpleReport) unmarshaller.unmarshal(new File("src/test/resources/simpleReport.xml"));
    assertNotNull(simpleReport);

    StringWriter writer = new StringWriter();
    marshaller.marshal(simpleReport, writer);

    String htmlSimpleReport = service.generateSimpleReport(writer.toString());
    assertTrue(Utils.isStringNotEmpty(htmlSimpleReport));
    logger.debug("Simple report html : " + htmlSimpleReport);
}
项目:automatic-mower    文件:MowerStatusChangedXMLReport.java   
@Override
public void sendAlert(Observable observable) {
    if (observable instanceof AbstarctMower) {
        try {
            AbstarctMower mower = (AbstarctMower) observable;
            SettingInterface settingLoader = SettingLoaderFactory.getSettingLoader(DEFAULT);
            StringBuilder br = new StringBuilder(settingLoader.getSerFolder());
            br.append(BACKSLASH).append(settingLoader.getReportingFolder()).append(BACKSLASH)
                    .append(mower.getIdentifier()).append(new Date().getTime()).append(XML_EXTENTION);
            File file = new File(br.toString());
            JAXBContext jaxbContext = JAXBContext.newInstance(AbstarctMower.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(mower, file);
        } catch (Exception e) {
            throw new MowerException(e);
        }
    }
}
项目:kie-ml    文件:KieMLContainerImpl.java   
private void loadModels() {
    ClassLoader cl = kieContainer.getClassLoader();
    InputStream modelsIS = cl.getResourceAsStream(MODEL_DESCRIPTOR_PATH);
    if (modelsIS == null) {
        throw new IllegalArgumentException("Not able to read descriptor" + MODEL_DESCRIPTOR_PATH);
    }
    try {
        JAXBContext context = JAXBContext.newInstance(Model.class, ModelList.class, ModelParam.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        models = (ModelList) unmarshaller.unmarshal(modelsIS);
        models.getModels().stream().filter(m -> m.getModelLabelsPath() !=  null).forEach(m -> m.setLabels(loadLabelsForModel(m)));
    } catch (JAXBException e) {
        throw new IllegalArgumentException("Not able to unmarshall descriptor" + MODEL_DESCRIPTOR_PATH, e);
    }

}
项目:CharmMylynConnector    文件:CharmTaskMessageBodyReader.java   
@Override
public CharmTask readFrom(Class<CharmTask> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

    try {


        JAXBContext context = JAXBContext.newInstance(CharmTask.class);
        Unmarshaller taskUnmarshaller = context.createUnmarshaller();
        return (CharmTask) taskUnmarshaller.unmarshal(entityStream);

    } catch (JAXBException e) {
        throw new ProcessingException("Error deserializing Task");
    }

}
项目:keycloak_training    文件:BindTest.java   
@Test
public void testMarschallingMessage() throws Exception {

    JAXBContext jc = JAXBContext.newInstance(Message.class);

    // Create the Marshaller Object using the JaxB Context
    Marshaller marshaller = jc.createMarshaller();

    marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
    marshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT,false);
    Message message = new Message();
    message.setMessage("success");
    // Marshal the employee object to JSON and print the output to console
    marshaller.marshal(message, System.out);

}
项目:Open_Source_ECOA_Toolset_AS5    文件:ServicesWizard.java   
/**
 * We will initialize file contents with a sample text.
 */

private InputStream openContentStream(ServiceDefinition def) {
    JAXBContext jaxbContext;
    try {
        jaxbContext = JAXBContext.newInstance(ServiceDefinition.class);
        MarshallerImpl jaxbMarshallerImpl = (MarshallerImpl) jaxbContext.createMarshaller();
        jaxbMarshallerImpl.setProperty(MarshallerImpl.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshallerImpl.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new NamespacePrefixMapper());
        StringWriter sw = new StringWriter();
        jaxbMarshallerImpl.marshal(def, sw);
        return new ByteArrayInputStream(sw.toString().getBytes());
    } catch (JAXBException e) {
        return new ByteArrayInputStream("Generation Error".getBytes());
    }
}
项目:keycloak_training    文件:BindTest.java   
@Test
public void testUnmarschallingMessage() throws Exception{
    JAXBContext jc = JAXBContext.newInstance(Message.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");

    // Set it to true if you need to include the JSON root element in
    // the
    // JSON input
    unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
    String json = "{\"message\":\"success\"}";
    StreamSource stream = 
            new StreamSource(new StringReader(json));

    Message message = unmarshaller.unmarshal(stream, Message.class).getValue();
    Assert.assertNotNull(message);
    Assert.assertTrue(message.getMessage().equals("success"));
}
项目:server-utility    文件:JaxbXMLUtil.java   
/**
 * JavaBean转换成xml,默认编码UTF-8
 *
 * @param obj 待转换对象
 * @return 转换后的xml
 */
public static String convertToXml(Object obj) {
    String result = null;
    try {
        JAXBContext context = JAXBContext.newInstance(obj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, CharsetConstant.UTF_8);

        StringWriter writer = new StringWriter();
        marshaller.marshal(obj, writer);
        result = writer.toString();
    } catch (Exception e) {
        logger.error(ExceptionUtil.parseException(e));
    }

    return result;
}
项目:alvisnlp    文件:TEESTrain.java   
@Override
    public void process(ProcessingContext<Corpus> ctx, Corpus corpus) throws ModuleException {
        Logger logger = getLogger(ctx);

        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(CorpusTEES.class);
//          logger.info("Accessing the corpora");
            Marshaller jaxbm = jaxbContext.createMarshaller();
            jaxbm.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            // marshaling
            this.prepareTEESCorpora(ctx, corpus);
            TEESTrainExternal teesTrainExt = new TEESTrainExternal(ctx);
            jaxbm.marshal(getCorpus(getTrainSetValue()), teesTrainExt.getTrainInput());
            jaxbm.marshal(getCorpus(getDevSetValue()), teesTrainExt.getDevInput());
            jaxbm.marshal(getCorpus(getTestSetValue()), teesTrainExt.getTestInput());

            logger.info("Training classifier");
            callExternal(ctx, "run-tees-train", teesTrainExt, INTERNAL_ENCODING, "tees-train.sh");
        }
        catch (JAXBException|IOException e) {
            rethrow(e);
        }
    }
项目:openjdk-jdk10    文件:SOAPMessageContextImpl.java   
public Object[] getHeaders(QName header, JAXBContext jaxbContext, boolean allRoles) {
    SOAPVersion soapVersion = binding.getSOAPVersion();

    List<Object> beanList = new ArrayList<Object>();
    try {
        Iterator<Header> itr = packet.getMessage().getHeaders().getHeaders(header,false);
        if(allRoles) {
            while(itr.hasNext()) {
                beanList.add(itr.next().readAsJAXB(jaxbContext.createUnmarshaller()));
            }
        } else {
            while(itr.hasNext()) {
                Header soapHeader = itr.next();
                //Check if the role is one of the roles on this Binding
                String role = soapHeader.getRole(soapVersion);
                if(getRoles().contains(role)) {
                    beanList.add(soapHeader.readAsJAXB(jaxbContext.createUnmarshaller()));
                }
            }
        }
        return beanList.toArray();
    } catch(Exception e) {
        throw new WebServiceException(e);
    }
}
项目:RoughWorld    文件:StateToXML.java   
public static void objectToXMLFile(StoryInstance o)
{
    String concept = o.uniqueID;
    int ind = concept.indexOf("/");
    String instance = concept.substring(ind+1);
    concept = concept.substring(0,ind);

    String instancepath = "Concepts/"+concept+"/instances/"+instance;       
    String datapath = instancepath+"/data.xml";

    try {
           JAXBContext context = JAXBContext.newInstance(StoryInstance.class);
           Marshaller m = context.createMarshaller();
           //for pretty-print XML in JAXB
           m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

           // Write to System.out for debugging
           // m.marshal(emp, System.out);

           // Write to File
           m.marshal(o, new File(datapath));
       } catch (JAXBException e) {
           e.printStackTrace();
       }
}
项目:tck    文件:TestCasesTest.java   
@SuppressWarnings({ "unchecked" })
protected final TestCases load(InputStream inputStream)
   throws JAXBException
{
   JAXBContext context = JAXBContext.newInstance(TestCases.class);
   Unmarshaller um = context.createUnmarshaller();

   Object obj = um.unmarshal(inputStream);
   if (obj instanceof JAXBElement<?>)
   {
      return ((JAXBElement<TestCases>) obj).getValue();
   }
   else
   {
      return (TestCases) obj;
   }
}
项目:AndroTickler    文件:XMLReader.java   
public void unmarshalManifest() {
    Manifest man=new Manifest();
    File manifest = new File(this.manifestFile);

    try {

        JAXBContext context = JAXBContext.newInstance(Manifest.class);
        Unmarshaller jaxbUnmarshaller = context.createUnmarshaller();
        man = (Manifest) jaxbUnmarshaller.unmarshal(manifest);
    }
    catch(Exception e)
    {
        System.out.println("ERROR: Manifest cannot be parsed");
        e.printStackTrace();
    }

    this.manifest = man;
}
项目:CharmMylynConnector    文件:CharmAttachmentPostWriter.java   
@Override
public void writeTo(CharmAttachmentPost attachment, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {

    try {

        JAXBContext context = JAXBContext.newInstance(CharmAttachmentPost.class);
        Marshaller taskMarshaller = context.createMarshaller();
        taskMarshaller.marshal(attachment, entityStream);

    } catch (JAXBException e) {
        throw new ProcessingException("Error serializing Attachment to output stream");
    }

}
项目:springboot-security-wechat    文件:XMLConverUtil.java   
/**
 * XML to Object
 * @param <T> T
 * @param clazz clazz
 * @param reader reader
 * @return T
 */
@SuppressWarnings("unchecked")
public static <T> T convertToObject(Class<T> clazz,Reader reader){
    try {
        Map<Class<?>, Unmarshaller> uMap = uMapLocal.get();
        if(!uMap.containsKey(clazz)){
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            uMap.put(clazz, unmarshaller);
        }
        return (T) uMap.get(clazz).unmarshal(reader);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return null;
}
项目:export-distro    文件:XMLFormatTransformer.java   
private String eventToXML(Event event) throws JAXBException {
    JAXBEvent jaxbEvent = new JAXBEvent(event);
    StringWriter xmlString = new StringWriter();
    JAXBContext context = JAXBContext.newInstance(JAXBEvent.class);
    Marshaller marshallerObj = context.createMarshaller();
    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshallerObj.marshal(jaxbEvent, xmlString);
    return xmlString.toString();
}
项目:util    文件:XmlMapper.java   
/**
 * 创建UnMarshaller. 线程不安全,需要每次创建或pooling。
 */
@SuppressWarnings("rawtypes")
public static Unmarshaller createUnmarshaller(Class clazz) {
    try {
        JAXBContext jaxbContext = getJaxbContext(clazz);
        return jaxbContext.createUnmarshaller();
    } catch (JAXBException e) {
        throw ExceptionUtil.unchecked(e);
    }
}
项目:oscm    文件:StateMachine.java   
private States loadStateMachine(String filename)
        throws StateMachineException {
    logger.debug("filename: " + filename);
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try (InputStream stream = loader.getResourceAsStream("statemachines/"
            + filename);) {
        JAXBContext jaxbContext = JAXBContext.newInstance(States.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        return (States) jaxbUnmarshaller.unmarshal(stream);
    } catch (Exception e) {
        throw new StateMachineException(
                "Failed to load state machine definition file: " + filename,
                e);
    }
}
项目:nifi-registry    文件:IdentityProviderFactory.java   
private static JAXBContext initializeJaxbContext() {
    try {
        return JAXBContext.newInstance(JAXB_GENERATED_PATH, IdentityProviderFactory.class.getClassLoader());
    } catch (JAXBException e) {
        throw new RuntimeException("Unable to create JAXBContext.");
    }
}
项目:s3-proxy-chunk-upload    文件:JAXBUtils.java   
private static <T> T unmarshallFromString(String sourceString,
        Class<T> resultingClass) throws UnmarshalException {
    try {
        JAXBContext context = JAXBContext.newInstance(resultingClass);
        return (T) context.createUnmarshaller().unmarshal(
                new StringReader(sourceString));
    } catch (Throwable e) {
        throw new UnmarshalException("Unable to unmarshal string", e);
    }
}
项目:openjdk-jdk10    文件:LogicalMessageImpl.java   
@Override
public Source getPayload() {
    JAXBContext context = ctxt;
    if (context == null) {
        context = defaultJaxbContext.getJAXBContext();
    }
    try {
        return new JAXBSource(context, o);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }
}
项目:incubator-netbeans    文件:Util.java   
public static List<String> getJaxBClassImports() {
    List<String> imports = new ArrayList<String>();
    ClassLoader orig = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(Util.class.getClassLoader());
    try {
        imports.add(JAXBContext.class.getName());
        imports.add(Unmarshaller.class.getName());
        imports.add(StreamSource.class.getName());
        imports.add(StringReader.class.getName());
    } finally {
      Thread.currentThread().setContextClassLoader(orig);
    }
    return imports;
}
项目:oscm    文件:RoleBasedFilter.java   
private void loadConfig(ServletContext servletContext) {
    try {
        final JAXBContext context = JAXBContext
                .newInstance(RoleBasedFilterConfig.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        StreamSource source = new StreamSource(
                servletContext.getResourceAsStream(CONFIG_FILE_LOCATION));
        config = unmarshaller.unmarshal(source, RoleBasedFilterConfig.class)
                .getValue();
    } catch (JAXBException e) {
        throw new IllegalArgumentException(e);
    }
}
项目:Steam-trader-tools    文件:AllAppList.java   
public void saveToXml()
{
    JAXBContext context;
    try {
        context = JAXBContext.newInstance(this.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        File file = new File("steamAppList.xml");
        marshaller.marshal(this,file);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}
项目:stvs    文件:XmlConstraintSpecImporter.java   
/**
 * Creates an Importer for {@link ConstraintSpecification ConstraintSpecifications}.
 *
 * @throws ImportException Exception while marshalling
 */
public XmlConstraintSpecImporter() throws ImportException {
  try {
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    unmarshaller = jaxbContext.createUnmarshaller();
  } catch (JAXBException e) {
    throw new ImportException(e);
  }
}
项目:stvs    文件:XmlConcreteSpecImporter.java   
/**
 * Creates an Importer. The {@code typeContext} is later used for assigning the right type to
 * variables while importing.
 *
 * @param typeContext list of types
 * @throws ImportException Exception while marshalling
 */
public XmlConcreteSpecImporter(List<Type> typeContext) throws ImportException {
  this.typeContext = typeContext;
  try {
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    unmarshaller = jaxbContext.createUnmarshaller();
  } catch (JAXBException e) {
    throw new ImportException(e);
  }
}
项目:osc-core    文件:LoggingUtil.java   
public static <T> String pojoToXmlString(T pojo) {
    try {
        StringWriter writer = new StringWriter();

        JAXBContext context = JAXBContext.newInstance(pojo.getClass());
        Marshaller ms = context.createMarshaller();
        ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        ms.marshal(pojo, writer);
        return writer.toString();

    } catch (Exception ex) {
        log.error("Problem converting the input to Xml. This should not happen.", ex);
    }
    return null;
}
项目:Open_Source_ECOA_Toolset_AS5    文件:CompDefUtil.java   
public ArrayList<String> getAllServerProprties() throws IOException, JAXBException {
    ArrayList<String> ret = new ArrayList<String>();
    ArrayList<String> cDefFiles = util.getResourcesWithExtension("cdef", containerName);
    for (String file : cDefFiles) {
        String content = FileUtils.readFileToString(new File(file));
        Unmarshaller unmarshaller = JAXBContext.newInstance(ComponentType.class).createUnmarshaller();
        ComponentType def = ((JAXBElement<ComponentType>) unmarshaller.unmarshal(new StringReader(content))).getValue();
        for (Object obj : def.getServiceOrReferenceOrProperty()) {
            if (obj instanceof Property)
                ret.add(((Service) obj).getName());
        }
    }
    return ret;
}
项目:cas-fortress-example    文件:IamUserDetails.java   
public IamUserDetails(String[] attributes) {
  Assert.notNull(attributes, "attributes cannot be null.");
  Assert.isTrue(attributes.length > 0,
      "At least one attribute is required to retrieve roles from.");
  this.attributes = attributes;
  try {
    context = JAXBContext.newInstance(Session.class);
  } catch (JAXBException e) {
    LOG.error("can not creating jaxb unmarshaller", e);
  }
}
项目:JavaRushTasks    文件:Solution.java   
public static <T> T convertFromXmlToNormal(String xmlData, Class<T> clazz) throws IOException, JAXBException {
    StringReader reader = new StringReader(xmlData);

    JAXBContext context = JAXBContext.newInstance(clazz);
    Unmarshaller unmarshaller = context.createUnmarshaller();

    return (T) unmarshaller.unmarshal(reader);
}
项目:openjdk-jdk10    文件:JAXBContextWithSubclassedFactory.java   
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());
    }
}