Java Code Examples for javax.xml.bind.Unmarshaller

The following are top voted examples for showing how to use javax.xml.bind.Unmarshaller. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: litiengine   File: GameFile.java   View source code 6 votes vote down vote up
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);
  }
}
 
Example 2
Project: ditb   File: TestTableScan.java   View source code 6 votes vote down vote up
@Test
public void testNegativeCustomFilter() throws IOException, JAXBException {
  StringBuilder builder = new StringBuilder();
  builder = new StringBuilder();
  builder.append("/b*");
  builder.append("?");
  builder.append(Constants.SCAN_COLUMN + "=" + COLUMN_1);
  builder.append("&");
  builder.append(Constants.SCAN_FILTER + "=" + URLEncoder.encode("CustomFilter('abc')", "UTF-8"));
  Response response =
      client.get("/" + TABLE + builder.toString(), Constants.MIMETYPE_XML);
  assertEquals(200, response.getCode());
  JAXBContext ctx = JAXBContext.newInstance(CellSetModel.class);
  Unmarshaller ush = ctx.createUnmarshaller();
  CellSetModel model = (CellSetModel) ush.unmarshal(response.getStream());
  int count = TestScannerResource.countCellSet(model);
  // Should return no rows as the filters conflict
  assertEquals(0, count);
}
 
Example 3
Project: AgentWorkbench   File: ProjectExportController.java   View source code 6 votes vote down vote up
/**
 * 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;

}
 
Example 4
Project: openjdk-jdk10   File: SCDBasedBindingSet.java   View source code 6 votes vote down vote up
/**
 * Applies the additional binding customizations.
 */
public void apply(XSSchemaSet schema, ErrorReceiver errorReceiver) {
    if(topLevel!=null) {
        this.errorReceiver = errorReceiver;
        Unmarshaller u =  BindInfo.getCustomizationUnmarshaller();
        this.unmarshaller = u.getUnmarshallerHandler();
        ValidatorHandler v = BindInfo.bindingFileSchema.newValidator();
        v.setErrorHandler(errorReceiver);
        loader = new ForkContentHandler(v,unmarshaller);

        topLevel.applyAll(schema.getSchemas());

        this.loader = null;
        this.unmarshaller = null;
        this.errorReceiver = null;
    }
}
 
Example 5
Project: JavaRushTasks   File: Solution.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws JAXBException {
    String xmlData =
            "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                    "<shop>\n" +
                    "    <goods>\n" +
                    "        <names>S1</names>\n" +
                    "        <names>S2</names>\n" +
                    "    </goods>\n" +
                    "    <count>12</count>\n" +
                    "    <profit>123.4</profit>\n" +
                    "    <secretData>String1</secretData>\n" +
                    "    <secretData>String2</secretData>\n" +
                    "    <secretData>String3</secretData>\n" +
                    "    <secretData>String4</secretData>\n" +
                    "    <secretData>String5</secretData>\n" +
                    "</shop>";

    StringReader reader = new StringReader(xmlData);

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

    Object o = unmarshaller.unmarshal(reader);

    System.out.println(o.toString());
}
 
Example 6
Project: CharmMylynConnector   File: CharmAttachmentMessageBodyReader.java   View source code 6 votes vote down vote up
@Override
public CharmAttachmentMeta readFrom(Class<CharmAttachmentMeta> type, Type genericType, Annotation[] annotations,
		MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
		throws IOException, WebApplicationException {

	try {

		JAXBContext context = JAXBContext.newInstance(CharmAttachmentMeta.class);
		Unmarshaller attachmentUnmarshaller = context.createUnmarshaller();
		return (CharmAttachmentMeta) attachmentUnmarshaller.unmarshal(entityStream);

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

}
 
Example 7
Project: dss-demonstrations   File: XSLTServiceTest.java   View source code 6 votes vote down vote up
@Test
public void generateDetailedReport() throws Exception {
	JAXBContext context = JAXBContext.newInstance(DetailedReport.class.getPackage().getName());
	Unmarshaller unmarshaller = context.createUnmarshaller();
	Marshaller marshaller = context.createMarshaller();

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

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

	String htmlDetailedReport = service.generateDetailedReport(writer.toString());
	assertTrue(Utils.isStringNotEmpty(htmlDetailedReport));
	logger.debug("Detailed report html : " + htmlDetailedReport);
}
 
Example 8
Project: stdds-monitor   File: StatusMessageParserV4.java   View source code 6 votes vote down vote up
@Override
protected void parseAPDSStatusMessage(Tracon tracon, String messageText) {
	long timestamp = System.currentTimeMillis();

	AirportDataServiceStatus apdsMessage = null;
	try {
		JAXBContext context = JAXBContext.newInstance(AirportDataServiceStatus.class);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		StringReader reader = new StringReader(messageText);
		apdsMessage = (AirportDataServiceStatus) unmarshaller.unmarshal(reader);
	} catch (Exception e) {
		e.printStackTrace();
	}
	Service service = tracon.getService(Constants.APDS);
	if ((service == null) && (DYNAMIC_MODE)) {
		service = new Service();
		service.setName(Constants.APDS);
		tracon.addService(service);
	}
	if (service != null) {
		service.setTimeStamp(timestamp);
		RVRExternalLinks rvrLinks = apdsMessage.getRvrLinks();
		if (rvrLinks != null) {
			for (ExternalLink exLink : rvrLinks.getRvrLink()) {
				handleLink(timestamp, service, tracon.getName(), exLink);
			}
		}
		// Don't set the service status if not configured for override
		boolean changed = false;
		if (!OVERRIDE_STATUS) {
			changed = service.setStatus(getMessageStatus(apdsMessage.getServiceStatus()));
		} else {
			changed = service.refreshStatus();
		}
		if (changed) {
			notificationRepo.save(new Notification(timestamp, service.getStatus(),
					service.getName(), tracon.getName(), NotificationType.SERVICE));
		}
	}
}
 
Example 9
Project: CharmMylynConnector   File: CharmTaskMessageBodyReader.java   View source code 6 votes vote down vote up
@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");
	}

}
 
Example 10
Project: OpenJSharp   File: SCDBasedBindingSet.java   View source code 6 votes vote down vote up
/**
 * Applies the additional binding customizations.
 */
public void apply(XSSchemaSet schema, ErrorReceiver errorReceiver) {
    if(topLevel!=null) {
        this.errorReceiver = errorReceiver;
        Unmarshaller u =  BindInfo.getCustomizationUnmarshaller();
        this.unmarshaller = u.getUnmarshallerHandler();
        ValidatorHandler v = BindInfo.bindingFileSchema.newValidator();
        v.setErrorHandler(errorReceiver);
        loader = new ForkContentHandler(v,unmarshaller);

        topLevel.applyAll(schema.getSchemas());

        this.loader = null;
        this.unmarshaller = null;
        this.errorReceiver = null;
    }
}
 
Example 11
Project: omr-dataset-tools   File: SheetAnnotations.java   View source code 6 votes vote down vote up
/**
 * Load SheetAnnotations from the annotations XML file.
 *
 * @param path to the XML input file.
 * @return the unmarshalled SheetAnnotations object
 * @throws IOException in case of IO problem
 */
public static SheetAnnotations unmarshal (Path path)
        throws IOException
{
    logger.debug("SheetAnnotations unmarshalling {}", path);

    try {
        InputStream is = Files.newInputStream(path, StandardOpenOption.READ);
        Unmarshaller um = getJaxbContext().createUnmarshaller();
        SheetAnnotations sheetInfo = (SheetAnnotations) um.unmarshal(is);
        logger.debug("Unmarshalled {}", sheetInfo);
        is.close();

        return sheetInfo;
    } catch (JAXBException ex) {
        logger.warn("Error unmarshalling " + path + " " + ex, ex);

        return null;
    }
}
 
Example 12
Project: oxygen-dita-translation-package-builder   File: MilestoneUtil.java   View source code 6 votes vote down vote up
/**
 * Loads the last creation date of the milestone file.
 * 
 * @param rootDir The location of the "special file"(milestone file).
 * 
 * @return  The last creation date of the "special file"(milestone).
 * 
 * @throws JAXBException   Problems with JAXB, serialization/deserialization of a file.
 */
public static Date getMilestoneCreationDate(URL rootMap) throws JAXBException, IOException {
  File rootMapFile = getFile(rootMap);
  File milestoneFile = new File(rootMapFile.getParentFile(),MilestoneUtil.getMilestoneFileName(rootMapFile));

  if (!milestoneFile.exists()) {
    throw new IOException("No milestone was created.");
  }

  JAXBContext jaxbContext = JAXBContext.newInstance(InfoResources.class); 

  Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();   

  InfoResources resources = (InfoResources) jaxbUnmarshaller.unmarshal(milestoneFile);    

  return resources.getMilestoneCreation();
}
 
Example 13
Project: stvs   File: XmlSessionImporter.java   View source code 6 votes vote down vote up
/**
 * Imports a {@link StvsRootModel} from {@code source}.
 *
 * @param source Node to import
 * @return imported model
 * @throws ImportException Exception while importing.
 */
@Override
public StvsRootModel doImportFromXmlNode(Node source) throws ImportException {
  try {
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Session importedSession =
        ((JAXBElement<Session>) jaxbUnmarshaller.unmarshal(source)).getValue();

    // Code
    Code code = new Code();
    code.updateSourcecode(importedSession.getCode().getPlaintext());
    VerificationScenario scenario = new VerificationScenario(code);

    List<Type> typeContext = Optional.ofNullable(code.getParsedCode())
        .map(ParsedCode::getDefinedTypes).orElse(Arrays.asList(TypeInt.INT, TypeBool.BOOL));

    // Tabs
    List<HybridSpecification> hybridSpecs = importTabs(importedSession, typeContext);

    return new StvsRootModel(hybridSpecs, currentConfig, currentHistory, scenario,
        new File(System.getProperty("user.home")), "");
  } catch (JAXBException e) {
    throw new ImportException(e);
  }
}
 
Example 14
Project: AndroTickler   File: XMLReader.java   View source code 6 votes vote down vote up
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;
}
 
Example 15
Project: xitk   File: FileHttpServersConf.java   View source code 6 votes vote down vote up
public void setConfFile(String confFile) throws Exception {
    this.confFile = confFile;

    Object root;
    try {
        JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
        Unmarshaller jaxbUnmarshaller = context.createUnmarshaller();
        final SchemaFactory schemaFact = SchemaFactory.newInstance(
                javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        URL url = ObjectFactory.class.getResource("/xsd/httpserver.xsd");
        jaxbUnmarshaller.setSchema(schemaFact.newSchema(url));

        root = jaxbUnmarshaller.unmarshal(new File(confFile));
    } catch (Exception ex) {
        throw new Exception("parsing config file failed, message: " + ex.getMessage(), ex);
    }

    if (root instanceof Httpservers) {
        this.conf = (Httpservers) root;
    } else if (root instanceof JAXBElement) {
        this.conf = (Httpservers) ((JAXBElement<?>) root).getValue();
    } else {
        throw new Exception("invalid root element type");
    }
}
 
Example 16
Project: Hydrograph   File: DebugUtils.java   View source code 6 votes vote down vote up
/**
 * Creates the object of type {@link HydrographDebugInfo} from the graph xml of type
 * {@link Document}.
 * <p>
 * The method uses jaxb framework to unmarshall the xml document
 *
 * @param graphDocument the xml document with all the graph contents to unmarshall
 * @return an object of type {@link HydrographDebugInfo}
 * @throws SAXException
 */
public static HydrographDebugInfo createHydrographDebugInfo(Document graphDocument, String debugXSDLocation) throws SAXException {
    try {
        LOG.trace("Creating DebugJAXB object.");
        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(ClassLoader.getSystemResource(debugXSDLocation));
        JAXBContext context = JAXBContext.newInstance(Debug.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ComponentValidationEventHandler());
        Debug debug = (Debug) unmarshaller.unmarshal(graphDocument);
        HydrographDebugInfo hydrographDebugInfo = new HydrographDebugInfo(debug);
        LOG.trace("DebugJAXB object created successfully");
        return hydrographDebugInfo;
    } catch (JAXBException e) {
        LOG.error("Error while creating JAXB objects from debug XML.", e);
        throw new RuntimeException("Error while creating JAXB objects from debug XML.", e);
    }
}
 
Example 17
Project: openjdk-jdk10   File: StreamMessage.java   View source code 6 votes vote down vote up
public Object readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
    if(!hasPayload())
        return null;
    assert unconsumed();
    // TODO: How can the unmarshaller process this as a fragment?
    if(hasAttachments())
        unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshallerImpl(getAttachments()));
    try {
        return unmarshaller.unmarshal(reader);
    } finally{
        unmarshaller.setAttachmentUnmarshaller(null);
        XMLStreamReaderUtil.readRest(reader);
        XMLStreamReaderUtil.close(reader);
        XMLStreamReaderFactory.recycle(reader);
    }
}
 
Example 18
Project: keycloak_training   File: BindTest.java   View source code 6 votes vote down vote up
@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"));
}
 
Example 19
Project: litiengine   File: CustomEmitter.java   View source code 5 votes vote down vote up
public static CustomEmitterData load(String emitterXml) {
  final String name = FileUtilities.getFileName(emitterXml);
  if (loadedCustomEmitters.containsKey(name)) {
    return loadedCustomEmitters.get(name);
  }

  try {
    final JAXBContext jaxbContext = JAXBContext.newInstance(CustomEmitterData.class);
    final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

    if (!new File(emitterXml).exists()) {
      emitterXml = Paths.get(GameDirectories.EMITTERS, emitterXml).toString();
    }

    final InputStream xml = FileUtilities.getGameResource(emitterXml);
    if (xml == null) {
      return null;
    }

    final CustomEmitterData loaded = (CustomEmitterData) jaxbUnmarshaller.unmarshal(xml);
    loadedCustomEmitters.put(name, loaded);
    return loaded;
  } catch (final JAXBException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }

  return null;
}
 
Example 20
Project: litiengine   File: Layer.java   View source code 5 votes vote down vote up
@SuppressWarnings("unused")
private void afterUnmarshal(Unmarshaller u, Object parent) {
  if (order == -1 && parent instanceof Map) {
    Map map = (Map) parent;
    int layerCnt = map.getTileLayers().size();
    layerCnt += map.getImageLayers().size();
    layerCnt += map.getTileLayers().size();
    this.order = layerCnt;
  }

  if (this.offsetx != null && this.offsetx.intValue() == 0) {
    this.offsetx = null;
  }

  if (this.offsety != null && this.offsety.intValue() == 0) {
    this.offsety = null;
  }

  if (this.width != null && this.width.intValue() == 0) {
    this.width = null;
  }

  if (this.height != null && this.height.intValue() == 0) {
    this.height = null;
  }

  if (this.opacity != null && this.opacity.floatValue() == 1.0f) {
    this.opacity = null;
  }

  if (this.visible != null && this.visible.intValue() == 1) {
    this.visible = null;
  }
}
 
Example 21
Project: litiengine   File: MapObjectLayer.java   View source code 5 votes vote down vote up
@SuppressWarnings("unused")
private void afterUnmarshal(Unmarshaller u, Object parent) {
  if (this.objects == null) {
    this.objects = new ArrayList<>();
  }

  Method m;
  try {
    m = getClass().getSuperclass().getDeclaredMethod("afterUnmarshal", Unmarshaller.class, Object.class);
    m.setAccessible(true);
    m.invoke(this, u, parent);
  } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
    log.log(Level.SEVERE, e.getMessage(), e);
  }
}
 
Example 22
Project: redirector   File: JSONSerializer.java   View source code 5 votes vote down vote up
private <T> T deserializeInternal(StreamSource streamSource, Class<T> clazz) throws SerializerException {
    try {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
        unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
        unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
        return unmarshaller.unmarshal(streamSource, clazz).getValue();
    } catch (JAXBException e) {
        log.error("Can't deserialize object of type {}", clazz.getSimpleName());
        throw new SerializerException("Can't deserialize object of type " + clazz.getSimpleName(), e);
    }
}
 
Example 23
Project: litiengine   File: Tile.java   View source code 5 votes vote down vote up
@SuppressWarnings("unused")
private void afterUnmarshal(Unmarshaller u, Object parent) {
  if (this.gid != null && this.gid == 0) {
    this.gid = null;
  }

  if (this.id != null && this.id == 0) {
    this.id = null;
  }
}
 
Example 24
Project: nifi-registry   File: JAXBSerializer.java   View source code 5 votes vote down vote up
@Override
public T deserialize(final InputStream input) throws SerializationException {
    if (input == null) {
        throw new IllegalArgumentException("InputStream cannot be null");
    }

    try {
        final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return (T) unmarshaller.unmarshal(input);
    } catch (JAXBException e) {
        throw new SerializationException("Unable to deserialize object", e);
    }
}
 
Example 25
Project: incubator-netbeans   File: SQLHistoryManager.java   View source code 5 votes vote down vote up
private void loadHistory() {
    try (InputStream is = getHistoryRoot(false).getInputStream()) {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        sqlHistory = (SQLHistory) unmarshaller.unmarshal(is);
        sqlHistory.setHistoryLimit(getListSize());
    } catch (JAXBException | IOException | RuntimeException ex) {
        sqlHistory = new SQLHistory();
        sqlHistory.setHistoryLimit(getListSize());
        LOGGER.log(Level.INFO, ex.getMessage());
    }
}
 
Example 26
Project: Spring-5.0-Cookbook   File: DepartmentItemReader.java   View source code 5 votes vote down vote up
private List<Department> depts() throws FileNotFoundException, JAXBException {
   JAXBContext context = JAXBContext.newInstance(Departments.class, Department.class);
   Unmarshaller unmarshaller = context.createUnmarshaller();
   Departments deptList = (Departments) unmarshaller.unmarshal(new FileInputStream(filename));
   return deptList.getDepartment();
         
}
 
Example 27
Project: OpenJSharp   File: MetroConfigLoader.java   View source code 5 votes vote down vote up
private static MetroConfig loadMetroConfig(@NotNull URL resourceUrl) {
    MetroConfig result = null;
    try {
        JAXBContext jaxbContext = createJAXBContext();
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        XMLInputFactory factory = XmlUtil.newXMLInputFactory(true);
        final JAXBElement<MetroConfig> configElement = unmarshaller.unmarshal(factory.createXMLStreamReader(resourceUrl.openStream()), MetroConfig.class);
        result = configElement.getValue();
    } catch (Exception e) {
        LOGGER.warning(TubelineassemblyMessages.MASM_0010_ERROR_READING_CFG_FILE_FROM_LOCATION(resourceUrl.toString()), e);
    }
    return result;
}
 
Example 28
Project: mintleaf   File: MintleafXmlConfiguration.java   View source code 5 votes vote down vote up
public static MintleafConfiguration deSerialize(String configFileName) throws MintleafException {
    MintleafReader reader = new TextContentStreamReader(configFileName);
    reader.read();
    try {
        JAXBContext jc = JAXBContext.newInstance(MintleafXmlConfiguration.class);
        Unmarshaller marshaller = jc.createUnmarshaller();
        StringReader sr = new StringReader(reader.toString());
        MintleafXmlConfiguration configurationRoot = (MintleafXmlConfiguration) marshaller.unmarshal(sr);
        return configurationRoot;

    } catch (JAXBException e) {
        throw new MintleafException(e);
    }
}
 
Example 29
Project: util   File: XmlMapper.java   View source code 5 votes vote down vote up
/**
 * 创建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);
	}
}
 
Example 30
Project: dss-demonstrations   File: FOPServiceTest.java   View source code 5 votes vote down vote up
@Test
public void generateDetailedReportMultiSignatures() throws Exception {
	JAXBContext context = JAXBContext.newInstance(DetailedReport.class.getPackage().getName());
	Unmarshaller unmarshaller = context.createUnmarshaller();
	Marshaller marshaller = context.createMarshaller();

	DetailedReport detailedReport = (DetailedReport) unmarshaller.unmarshal(new File("src/test/resources/detailed-report-multi-signatures.xml"));
	assertNotNull(detailedReport);

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

	FileOutputStream fos = new FileOutputStream("target/detailedReportMulti.pdf");
	service.generateDetailedReport(writer.toString(), fos);
}
 
Example 31
Project: activemq-cli-tools   File: ArtemisJournalMarshallerTest.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void validate(File file) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    JAXBElement<ActivemqJournalType> read = (JAXBElement<ActivemqJournalType>) jaxbUnmarshaller.unmarshal(file);
    assertEquals(3, read.getValue().getMessages().getMessage().size());
}
 
Example 32
Project: OpenJSharp   File: SAAJMessage.java   View source code 5 votes vote down vote up
public <T> T readPayloadAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
    access();
    if (payload != null) {
        if(hasAttachments())
            unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshallerImpl(getAttachments()));
        return (T) unmarshaller.unmarshal(payload);

    }
    return null;
}
 
Example 33
Project: OpenJSharp   File: AbstractHeaderImpl.java   View source code 5 votes vote down vote up
public <T> T readAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
    try {
        return (T)unmarshaller.unmarshal(readHeader());
    } catch (Exception e) {
        throw new JAXBException(e);
    }
}
 
Example 34
Project: ditb   File: RemoteAdmin.java   View source code 5 votes vote down vote up
static Unmarshaller getUnmarsheller() throws JAXBException {

    if (versionClusterUnmarshaller == null) {

      RemoteAdmin.versionClusterUnmarshaller = JAXBContext.newInstance(
          StorageClusterVersionModel.class).createUnmarshaller();
    }
    return RemoteAdmin.versionClusterUnmarshaller;
  }
 
Example 35
Project: DocIT   File: Serialization.java   View source code 5 votes vote down vote up
public static Company readCompany(File input)
throws JAXBException 
{
	initializeJaxbContext();
	Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
	return (Company) unMarshaller.unmarshal(input);		
}
 
Example 36
Project: OpenJSharp   File: LogicalMessageImpl.java   View source code 5 votes vote down vote up
public Object getPayload(JAXBContext context) {
    try {
        Source payloadSrc = getPayload();
        if (payloadSrc == null)
            return null;
        Unmarshaller unmarshaller = context.createUnmarshaller();
        return unmarshaller.unmarshal(payloadSrc);
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }

}
 
Example 37
Project: ts-benchmark   File: Core.java   View source code 5 votes vote down vote up
/**.
	 * 初始化内置函数
	 * functionParam
	 */
	public static void initInnerFucntion() {
		
		FunctionXml xml=null;
		try {
			InputStream input = Core.class.getResourceAsStream("function.xml");
			JAXBContext context = JAXBContext.newInstance(FunctionXml.class,FunctionParam.class);
			Unmarshaller unmarshaller = context.createUnmarshaller(); 
			xml = (FunctionXml)unmarshaller.unmarshal(input);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(0);
		}
		List<FunctionParam> xmlFuctions = xml.getFunctions();
		for(FunctionParam param:xmlFuctions){
			if(param.getFunctionType().indexOf("-mono-k")!=-1){
				Constants.LINE_LIST.add(param);
			}else if(param.getFunctionType().indexOf("-mono")!=-1){
				//如果min==max则为常数,系统没有非常数的
				if(param.getMin()==param.getMax()){
					Constants.CONSTANT_LIST.add(param);
				}
			}else if(param.getFunctionType().indexOf("-sin")!=-1){
				Constants.SIN_LIST.add(param);
			}else if(param.getFunctionType().indexOf("-square")!=-1){
				Constants.SQUARE_LIST.add(param);
			}else if(param.getFunctionType().indexOf("-random")!=-1){
				Constants.RANDOM_LIST.add(param);
			}
		}
//		System.out.println("line:"+Constants.LINE_LIST.size());
//		System.out.println("sinList:"+Constants.SIN_LIST.size());
//		System.out.println("squareList:"+Constants.SQUARE_LIST.size());
//		System.out.println("randomList:"+Constants.RANDOM_LIST.size());
//		System.out.println("constantList:"+Constants.CONSTANT_LIST.size());
	}
 
Example 38
Project: omr-dataset-tools   File: SymbolInfo.java   View source code 5 votes vote down vote up
/**
 * Called after all the properties (except IDREF) are unmarshalled
 * for this object, but before this object is set to the parent object.
 */
@PostConstruct
private void afterUnmarshal (Unmarshaller um,
                             Object parent)
{
    if (omrShape == null) {
        logger.warn("*** Null shape {}", this);
    }
}
 
Example 39
Project: tck   File: SchemaValidator.java   View source code 5 votes vote down vote up
private void validateSchema(File file) throws Exception {
    try {
        JAXBContext jc = JAXBContext.newInstance(context);
        Unmarshaller u = jc.createUnmarshaller();
        setSchema(u, schemaLocation);

        u.unmarshal(file.toURI().toURL());
        System.out.println(String.format("'%s' is valid", file.getName()));
    } catch (Exception e) {
        System.out.println(String.format("'%s' is invalid", file.getName()));
        e.printStackTrace();
    }
}
 
Example 40
Project: jaffa-framework   File: ConfigurationService.java   View source code 5 votes vote down vote up
/**
 * Loads the configurationFile using JAXB.
 * The XML is validated as per the schema ''.
 * The XML is then parsed to return a corresponding Java object.
 * @return the Java representation of the XML inside the configuration file.
 * @throws MalformedURLException if the configuration file is not found.
 * @throws JAXBException if any error occurs during the unmarshalling of XML.
 * @throws SAXException if the schema file cannot be loaded.
 */
private Dwr parseConfigurationFile()
        throws MalformedURLException, JAXBException, SAXException {
    if (log.isDebugEnabled())
        log.debug("Unmarshalling the configuration file " + CONFIGURATION_FILE);
    URL configFileUrl = URLHelper.newExtendedURL(CONFIGURATION_FILE);
    URL configSchemaFileUrl = URLHelper.newExtendedURL(CONFIGURATION_SCHEMA_FILE);
    JAXBContext jc = JAXBHelper.obtainJAXBContext(Dwr.class);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(configSchemaFileUrl);
    unmarshaller.setSchema(schema);
    return (Dwr) unmarshaller.unmarshal(configFileUrl);
}