List of usage examples for javax.xml.bind Marshaller JAXB_SCHEMA_LOCATION
String JAXB_SCHEMA_LOCATION
To view the source code for javax.xml.bind Marshaller JAXB_SCHEMA_LOCATION.
Click Source Link
From source file:org.betaconceptframework.astroboa.model.jaxb.CmsEntitySerialization.java
private String marshalEntity(CmsRepositoryEntity cmsRepositoryEntity, ResourceRepresentationType<?> resourceRepresentationType, boolean exportBinaryContent, boolean prettyPrint, String... propertyPathsToBeMarshalled) { if (cmsRepositoryEntity != null) { if (cmsRepositoryEntity instanceof ContentObject || cmsRepositoryEntity instanceof Topic || cmsRepositoryEntity instanceof Space || cmsRepositoryEntity instanceof RepositoryUser || cmsRepositoryEntity instanceof Taxonomy) { StringWriter writer = new StringWriter(); Marshaller marshaller = null; try { marshaller = createMarshaller(resourceRepresentationType, prettyPrint); if (cmsRepositoryEntity instanceof ContentObject) { if (!ArrayUtils.isEmpty(propertyPathsToBeMarshalled)) { marshaller.setProperty(AstroboaMarshaller.CMS_PROPERTIES_TO_BE_MARSHALLED, Arrays.asList(propertyPathsToBeMarshalled)); }/*from w ww. ja v a2 s. com*/ //ContentObject needs special marshaling as JAXB does not have //enough information in order to initialize appropriate adapter for //ContentObject ContentObjectAdapter adapter = new ContentObjectAdapter(); adapter.setMarshaller(marshaller, exportBinaryContent, ArrayUtils.isEmpty(propertyPathsToBeMarshalled)); marshaller.setAdapter(adapter); ContentObjectType contentObjectType = marshaller.getAdapter(ContentObjectAdapter.class) .marshal((ContentObject) cmsRepositoryEntity); JAXBElement<ContentObjectType> contentObjectTypeJaxb = new JAXBElement<ContentObjectType>( ((ContentObject) cmsRepositoryEntity).getTypeDefinition().getQualifiedName(), ContentObjectType.class, null, contentObjectType); marshaller.marshal(contentObjectTypeJaxb, writer); } else { //Provide schema location marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, " " + BetaConceptNamespaceConstants.ASTROBOA_MODEL_DEFINITION_URI + " " + SchemaUtils.buildSchemaLocationForAstroboaModelSchemaAccordingToActiveClient()); marshaller.marshal(cmsRepositoryEntity, writer); } } catch (Exception e) { throw new CmsException(e); } finally { marshaller = null; } return writer.toString(); } else { throw new CmsException("Creating XML for entity type " + cmsRepositoryEntity.getClass().getName() + " is not supported"); } } throw new CmsException("No entity is provided. Unable to create xml"); }
From source file:org.betaconceptframework.astroboa.util.SchemaUtils.java
public static void appendSchemaLocationToMarshaller(Marshaller marshaller, String namespace, String schemaLocationURL, String prefix) throws PropertyException { if (StringUtils.isBlank(namespace) || StringUtils.isBlank(schemaLocationURL)) { return;/*from ww w .j av a 2 s .co m*/ } String schemaLocation = (String) marshaller.getProperty(Marshaller.JAXB_SCHEMA_LOCATION); if (schemaLocation == null) { schemaLocation = ""; } if (!schemaLocation.contains(namespace)) { marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocation + " " + namespace + " " + schemaLocationURL); } }
From source file:org.dawnsci.conversion.converters.CustomNCDConverter.java
private void exportCanSAS(final ILazyDataset lz, final String nameFrag, final IConversionContext context, final OutputBean outputBean) throws Exception { String titleNodeString = outputBean.title; String selFilePath = outputBean.filepath; //get the x axis if required Dataset axis = outputBean.axis;// w w w . jav a2s . c o m Dataset axisErrors = outputBean.axis.getError(); String axisUnits = outputBean.axisUnits; //Set up position iterator (final 2 dimensions saved in a single file int[] stop = lz.getShape(); boolean hasErrors = (lz.getError() != null ? true : false); int iterDim = lz.getRank() - 1; int[] cutAxes = new int[] { lz.getRank() - 1 }; PositionIterator iterator = new PositionIterator(stop, cutAxes); for (int i = 0; i < iterDim; i++) { stop[i] = 0; } int[] step = new int[stop.length]; for (int i = 0; i < step.length; i++) { step[i] = 1; } ObjectFactory of = new ObjectFactory(); SASrootType sasRoot = of.createSASrootType(); SASsampleType sasSample = of.createSASsampleType(); SASsourceType sasSource = of.createSASsourceType(); sasSource.setRadiation("x-ray"); SASdetectorType sasDetector = of.createSASdetectorType(); sasDetector.setName(nameFrag); SAScollimationType sasCollimation = of.createSAScollimationType(); SASinstrumentType sasInstrument = of.createSASinstrumentType(); sasInstrument.setName("Diamond Light Source Ltd."); sasInstrument.setSASsource(sasSource); sasInstrument.getSASdetector().add(sasDetector); sasInstrument.getSAScollimation().add(sasCollimation); SAStransmissionSpectrumType sasTransmission = of.createSAStransmissionSpectrumType(); if (titleNodeString != null && !titleNodeString.isEmpty()) { sasSample.setID(titleNodeString); } else { sasSample.setID("N/A"); } String pathToFolder = context.getOutputPath(); String fileName; if (context.getSelectedConversionFile() != null) { fileName = buildFileName(context.getSelectedConversionFile().getAbsolutePath(), nameFrag); } else { fileName = buildFileNameGeneric(context.getDatasetNames().get(0), nameFrag); } String fullName = pathToFolder + File.separator + fileName + ".xml"; checkWhetherFileExists(fullName); //Iterate over lazy dataset and save while (iterator.hasNext()) { SASentryType sasEntry = of.createSASentryType(); int[] start = iterator.getPos(); for (int j = 0; j < iterDim; j++) { stop[j] = start[j] + 1; } Slice[] slices = Slice.convertToSlice(start, stop, step); Dataset data = DatasetUtils.convertToDataset(lz.getSlice(slices).squeeze()); Dataset errors = null; if (hasErrors) { errors = DatasetUtils.cast(data.getError(), data.getDtype()); errors.squeeze(); } Run run = new Run(); String runName = "Frame" + nameStringFromSliceArray(iterDim, slices); run.setValue(runName); sasEntry.getRun().add(run); SASdataType sasData = of.createSASdataType(); PositionIterator iter = new PositionIterator(data.getShape(), new int[] {}); while (iter.hasNext()) { int[] idx = iter.getPos(); float val; IdataType iData = of.createIdataType(); FloatUnitType I = of.createFloatUnitType(); val = data.getFloat(idx); I.setValue(val); I.setUnit("a.u."); iData.setI(I); if (axis != null) { FloatUnitType Q = of.createFloatUnitType(); val = axis.getFloat(idx); Q.setValue(val); Q.setUnit(axisUnits); iData.setQ(Q); } if (errors != null) { FloatUnitType devI = of.createFloatUnitType(); val = errors.getFloat(idx); devI.setValue(val); devI.setUnit("a.u."); iData.setIdev(devI); } if (axisErrors != null) { FloatUnitType devQ = of.createFloatUnitType(); val = axisErrors.getFloat(idx); devQ.setValue(val); devQ.setUnit(axisUnits); iData.setQdev(devQ); } sasData.getIdata().add(iData); } sasEntry.setTitle(data.getName()); sasEntry.getSASdata().add(sasData); sasEntry.setSASsample(sasSample); sasEntry.getSAStransmissionSpectrum().add(sasTransmission); sasEntry.setSASinstrument(sasInstrument); if (selFilePath != null && !selFilePath.isEmpty()) { sasEntry.getSASnote().add(selFilePath); } sasRoot.setVersion("1.1"); sasRoot.getSASentry().add(sasEntry); } JAXBElement<SASrootType> jabxSASroot = of.createSASroot(sasRoot); JAXBContext jc = JAXBContext.newInstance(CANSAS_JAXB_CONTEXT); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "urn:cansas1d:1.1 http://www.cansas.org/formats/1.1/cansas1d.xsd"); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.marshal(jabxSASroot, new FileOutputStream(fullName)); if (context.getMonitor() != null) { IMonitor mon = context.getMonitor(); mon.worked(1); } }
From source file:org.ets.ereg.web.util.CRSContentUploadThread.java
/** * Marshalls from object to XML input stream *//*from w w w .j av a2 s .com*/ private void marshall(JAXBElement<TMrss> jaxbElement, File xmlFile) { try { Marshaller marshaller = JAXBContext.newInstance(TMrss.class).createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, ""); marshaller.marshal(jaxbElement, xmlFile); } catch (JAXBException e) { log.error(e.getMessage(), e); } }
From source file:org.intermine.modelviewer.jaxb.ConfigParser.java
/** * Marshalls an object of the given context to the given writer. * <p>All sorts of niceties regarding schema locations, name spaces and so forth * are set up to embellish the output and make is as correct as possible.</p> * //from ww w. j av a 2 s. c o m * @param context The type of object being written. * @param object The object to marshall. * @param out The writer to marshall to. * * @throws JAXBException if JAXB marshalling fails. * @throws XMLStreamException if there is a problem with lower level XML streaming. * * @see KnownNamespacePrefixMatcher */ protected void writeFileJaxb(Context context, Object object, Writer out) throws JAXBException, XMLStreamException { String namespace = namespaces.get(context); StringBuilder schemaLocations = new StringBuilder(); /* switch (context) { case CORE: case GENOMIC: schemaLocations.append(GENOMIC_CORE_NAMESPACE).append(' '); schemaLocations.append(GENOMIC_CORE_URL).append(' '); break; } */ schemaLocations.append(namespace).append(' ').append(xsdUrls.get(context)); /* XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xmlStreamWriter.setPrefix("gc", GENOMIC_CORE_NAMESPACE); xmlStreamWriter.setPrefix("core", CORE_NAMESPACE); xmlStreamWriter.setPrefix("genomic", GENOMIC_NAMESPACE); xmlStreamWriter.setPrefix("project", PROJECT_NAMESPACE); //xmlStreamWriter.setDefaultNamespace(namespace); xmlStreamWriter = new IndentingXMLStreamWriter(xmlStreamWriter); */ Marshaller marshall = jaxbContexts.get(context).createMarshaller(); //marshall.setSchema(schemas.get(context)); marshall.setProperty(PREFIX_MAPPER_PROPERTY, new KnownNamespacePrefixMatcher()); marshall.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshall.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocations.toString()); marshall.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); //marshall.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, xsdUrls.get(context)); //marshall.marshal(object, xmlStreamWriter); marshall.marshal(object, out); }
From source file:org.netbeans.jbpmn.modeler.specification.bpmn.model.conversation.util.BPMNConversationUtil.java
public void saveModelerFile(ModelerFile file) { try {//from ww w. ja va 2 s . co m updateBPMNDiagram(file); File savedFile = file.getFile(); if (bpmnConversationContext == null) { bpmnConversationContext = JAXBContext .newInstance(new Class<?>[] { ShapeDesign.class, TDefinitions.class }); } if (bpmnConversationMarshaller == null) { bpmnConversationMarshaller = bpmnConversationContext.createMarshaller(); } // output pretty printed bpmnConversationMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); bpmnConversationMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.omg.org/spec/BPMN/20100524/MODEL http://www.omg.org/spec/BPMN/2.0/20100501/BPMN20.xsd"); // // jaxbMarshaller.setProperty(CharacterEscapeHandler.class.getName(), new CharacterEscapeHandler() { // property required for CDATA // @Override // public void escape(char[] ac, int i, int j, boolean flag, // Writer writer) throws IOException { // writer.write( ac, i, j ); } // }); bpmnConversationMarshaller.setEventHandler(new ValidateJAXB()); StringWriter sw = new StringWriter(); bpmnConversationMarshaller.marshal(file.getDefinitionElement(), sw); bpmnConversationMarshaller.marshal(file.getDefinitionElement(), System.out); FileUtils.writeStringToFile(savedFile, sw.toString().replaceFirst( "xmlns:ns[A-Za-z\\d]{0,3}=\"http://www.omg.org/spec/BPMN/20100524/MODEL\"", "xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\"")); } catch (JAXBException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } // file.get }
From source file:org.netbeans.jbpmn.modeler.specification.bpmn.model.process.util.BPMNProcessUtil.java
public void saveModelerFile(ModelerFile file) { try {//from w w w.j ava2 s .co m updateBPMNDiagram(file); File savedFile = file.getFile(); if (bpmnProcessContext == null) { bpmnProcessContext = JAXBContext .newInstance(new Class<?>[] { ShapeDesign.class, TDefinitions.class, TProperty.class }); } if (bpmnProcessMarshaller == null) { bpmnProcessMarshaller = bpmnProcessContext.createMarshaller(); } // output pretty printed bpmnProcessMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); bpmnProcessMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.omg.org/spec/BPMN/20100524/MODEL http://www.omg.org/spec/BPMN/2.0/20100501/BPMN20.xsd"); // bpmnProcessMarshaller.setProperty("com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler", new CharacterEscapeHandler() { // property required for CDATA // @Override // public void escape(char[] ac, int i, int j, boolean flag, Writer writer) throws IOException { // writer.write(ac, i, j); // } // }); // bpmnProcessMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // bpmnProcessMarshaller.marshal(file.getDefinitionElement(), savedFile); // com.sun.xml.bind.marshaller.NamespacePrefixMapper mapper = new com.sun.xml.bind.marshaller.NamespacePrefixMapper() { // public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) { // if ("http://www.omg.org/spec/BPMN/20100524/MODEL".equals(namespaceUri) && !requirePrefix) { // return ""; // } // return "ns"; // } // }; // bpmnProcessMarshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper); bpmnProcessMarshaller.setEventHandler(new ValidateJAXB()); bpmnProcessMarshaller.marshal(file.getDefinitionElement(), System.out); StringWriter sw = new StringWriter(); bpmnProcessMarshaller.marshal(file.getDefinitionElement(), sw); FileUtils.writeStringToFile(savedFile, sw.toString().replaceFirst( "xmlns:ns[A-Za-z\\d]{0,3}=\"http://www.omg.org/spec/BPMN/20100524/MODEL\"", "xmlns=\"http://www.omg.org/spec/BPMN/20100524/MODEL\"")); // NamespacePrefixMapper prefixMapper = new BPMNNamespacePrefixMapper(); //jaxbMarshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", prefixMapper); } catch (JAXBException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } // file.get }
From source file:org.netbeans.jpa.modeler.specification.model.util.JPAModelerUtil.java
public static void saveFile(EntityMappings entityMappings, File file) { try {/*from w w w. j a va 2s. co m*/ if (MODELER_MARSHALLER == null) { MODELER_MARSHALLER = MODELER_CONTEXT.createMarshaller(); MODELER_MARSHALLER.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); MODELER_MARSHALLER.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://java.sun.com/xml/ns/persistence/orm orm_2_1.xsd"); MODELER_MARSHALLER.setEventHandler(new ValidateJAXB()); } MODELER_MARSHALLER.marshal(entityMappings, file); } catch (JAXBException ex) { ExceptionUtils.printStackTrace(ex); } }
From source file:org.nmrml.converter.Converter.java
public static void main(String[] args) { /* Containers of Acquisition/Processing Parameters */ Acqu acq = null;// w ww . jav a 2 s .co m Proc proc = null; String Vendor = "bruker"; /* HashMap for Source Files */ HashMap<String, SourceFileType> hSourceFileObj = new HashMap<String, SourceFileType>(); HashMap<String, BinaryData> hBinaryDataObj = new HashMap<String, BinaryData>(); Options options = new Options(); options.addOption("h", "help", false, "prints the help content"); options.addOption("v", "version", false, "prints the version"); options.addOption("d", "binary-data", false, "include binary data such as fid and spectrum values"); options.addOption("z", "compress", false, "compress binary data"); options.addOption(null, "only-fid", false, "exclude all spectrum processing parameters and corresponding binary data"); options.addOption(OptionBuilder.withArgName("vendor").hasArg().withDescription("type") .withLongOpt("vendortype").create("t")); options.addOption(OptionBuilder.withArgName("directory").hasArg().isRequired() .withDescription("input directory").withLongOpt("inputdir").create("i")); options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("output file") .withLongOpt("outputfile").create("o")); try { CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); String inputFolder = cmd.getOptionValue("i"); inputFolder = (inputFolder.lastIndexOf("/") == inputFolder.length()) ? inputFolder : inputFolder.concat("/"); /* Properties object */ Properties prop = new Properties(); prop.load(Converter.class.getClassLoader().getResourceAsStream("resources/config.properties")); String onto_ini = prop.getProperty("onto_ini_file"); String schemaLocation = prop.getProperty("schemaLocation"); /* CVLoader object */ CVLoader cvLoader = (new File(onto_ini)).isFile() ? new CVLoader(Converter.class.getClassLoader().getResourceAsStream(onto_ini)) : new CVLoader(); if (cmd.hasOption("t")) { Vendor = cmd.getOptionValue("t").toLowerCase(); } String Vendor_Label = Vendor.toUpperCase(); String vendor_ini = prop.getProperty(Vendor); Vendor_Type vendor_type = Vendor_Type.valueOf(Vendor); /* Vendor terms file */ SpectrometerMapper vendorMapper = new SpectrometerMapper(vendor_ini); /* Get Acquisition & Processing Parameters depending on the vendor type */ switch (vendor_type) { case bruker: BrukerReader brukerValues = new BrukerReader(inputFolder, vendorMapper); acq = brukerValues.acq; proc = brukerValues.proc; break; case varian: VarianReader varianValues = new VarianReader(inputFolder, vendorMapper); acq = varianValues.acq; proc = varianValues.proc; break; } /* NmrMLType object */ ObjectFactory objFactory = new ObjectFactory(); NmrMLType nmrMLtype = objFactory.createNmrMLType(); nmrMLtype.setVersion(nmrMLVersion); /* ACQUISITION PARAMETERS */ /* CV List : used as references for all CV in the document */ int cvCount = 0; CVListType cvList = objFactory.createCVListType(); for (String cvKey : cvLoader.getCVOntologySet()) { CVType cv = cvLoader.fetchCVType(cvKey); cvList.getCv().add(cv); cvCount = cvCount + 1; } nmrMLtype.setCvList(cvList); /* FileDescription */ FileDescriptionType filedesc = objFactory.createFileDescriptionType(); ParamGroupType paramgrp = objFactory.createParamGroupType(); paramgrp.getCvParam().add(cvLoader.fetchCVParam("NMRCV", "ONE_DIM_NMR")); filedesc.setFileContent(paramgrp); nmrMLtype.setFileDescription(filedesc); /* Contact List */ ContactListType contactlist = objFactory.createContactListType(); ContactType contact1 = objFactory.createContactType(); contact1.setId(getNewIdentifier()); contact1.setFullname(acq.getOwner()); contact1.setEmail(acq.getEmail()); contactlist.getContact().add(contact1); nmrMLtype.setContactList(contactlist); /* Contact Ref List */ ContactRefListType contactRefList = objFactory.createContactRefListType(); ContactRefType contactRef = objFactory.createContactRefType(); contactRef.setRef(contact1); contactRefList.getContactRef().add(contactRef); /* SourceFile List */ int sourceFileCount = 0; SourceFileListType srcfilelist = objFactory.createSourceFileListType(); for (String sourceName : vendorMapper.getSection("FILES").keySet()) { File sourceFile = new File(inputFolder + vendorMapper.getTerm("FILES", sourceName)); if (sourceFile.isFile() & sourceFile.canRead()) { SourceFileType srcfile = objFactory.createSourceFileType(); srcfile.setId(getNewIdentifier()); srcfile.setName(sourceFile.getName()); srcfile.setLocation(sourceFile.toURI().toString()); srcfile.getCvParam().add(cvLoader.fetchCVParam("NMRCV", acq.getSoftware())); srcfile.getCvParam().add(cvLoader.fetchCVParam("NMRCV", sourceName)); hSourceFileObj.put(sourceName, srcfile); boolean doBinData = false; for (BinaryFile_Type choice : BinaryFile_Type.values()) if (choice.name().equals(sourceName)) doBinData = true; if (doBinData) { boolean bComplexData = false; if (BinaryFile_Type.FID_FILE.name().equals(sourceName)) { bComplexData = true; } BinaryData binaryData = new BinaryData(sourceFile, acq, bComplexData, cmd.hasOption("z")); hBinaryDataObj.put(sourceName, binaryData); if (binaryData.isExists()) { srcfile.setSha1(binaryData.getSha1()); } } srcfilelist.getSourceFile().add(srcfile); sourceFileCount = sourceFileCount + 1; } } nmrMLtype.setSourceFileList(srcfilelist); /* Software List */ SoftwareListType softwareList = objFactory.createSoftwareListType(); SoftwareType software1 = objFactory.createSoftwareType(); CVTermType softterm1 = cvLoader.fetchCVTerm("NMRCV", acq.getSoftware()); software1.setCvRef(softterm1.getCvRef()); software1.setAccession(softterm1.getAccession()); software1.setId(getNewIdentifier()); software1.setName(acq.getSoftware()); software1.setVersion(acq.getSoftVersion()); softwareList.getSoftware().add(software1); nmrMLtype.setSoftwareList(softwareList); /* Software Ref List */ SoftwareRefListType softwareRefList = objFactory.createSoftwareRefListType(); SoftwareRefType softref1 = objFactory.createSoftwareRefType(); softref1.setRef(software1); softwareRefList.getSoftwareRef().add(softref1); /* InstrumentConfiguration List */ InstrumentConfigurationListType instrumentConfList = objFactory.createInstrumentConfigurationListType(); InstrumentConfigurationType instrumentConf = objFactory.createInstrumentConfigurationType(); instrumentConf.getSoftwareRef().add(softref1); instrumentConf.setId(getNewIdentifier()); instrumentConf.getCvParam().add(cvLoader.fetchCVParam("NMRCV", Vendor_Label)); UserParamType probeParam = objFactory.createUserParamType(); probeParam.setName("ProbeHead"); probeParam.setValue(acq.getProbehead()); instrumentConf.getUserParam().add(probeParam); instrumentConfList.getInstrumentConfiguration().add(instrumentConf); nmrMLtype.setInstrumentConfigurationList(instrumentConfList); /* Acquition */ /* CV Units */ CVTermType cvUnitNone = cvLoader.fetchCVTerm("UO", "NONE"); CVTermType cvUnitPpm = cvLoader.fetchCVTerm("UO", "PPM"); CVTermType cvUnitHz = cvLoader.fetchCVTerm("UO", "HERTZ"); CVTermType cvUnitmHz = cvLoader.fetchCVTerm("UO", "MEGAHERTZ"); CVTermType cvUnitT = cvLoader.fetchCVTerm("UO", "TESLA"); CVTermType cvUnitK = cvLoader.fetchCVTerm("UO", "KELVIN"); CVTermType cvUnitDeg = cvLoader.fetchCVTerm("UO", "DEGREE"); CVTermType cvUnitSec = cvLoader.fetchCVTerm("UO", "SECOND"); CVTermType cvUnitmSec = cvLoader.fetchCVTerm("UO", "MICROSECOND"); /* AcquisitionParameterSet1D object */ AcquisitionParameterSet1DType acqparam = objFactory.createAcquisitionParameterSet1DType(); acqparam.setNumberOfScans(acq.getNumberOfScans()); acqparam.setNumberOfSteadyStateScans(acq.getNumberOfSteadyStateScans()); /* sample container */ acqparam.setSampleContainer(cvLoader.fetchCVTerm("NMRCV", "TUBE")); /* sample temperature */ ValueWithUnitType temperature = objFactory.createValueWithUnitType(); temperature.setValue(String.format("%f", acq.getTemperature())); temperature.setUnitCvRef(cvUnitK.getCvRef()); temperature.setUnitAccession(cvUnitK.getAccession()); temperature.setUnitName(cvUnitK.getName()); acqparam.setSampleAcquisitionTemperature(temperature); /* Relaxation Delay */ ValueWithUnitType relaxationDelay = objFactory.createValueWithUnitType(); relaxationDelay.setValue(String.format("%f", acq.getRelaxationDelay())); relaxationDelay.setUnitCvRef(cvUnitSec.getCvRef()); relaxationDelay.setUnitAccession(cvUnitSec.getAccession()); relaxationDelay.setUnitName(cvUnitSec.getName()); acqparam.setRelaxationDelay(relaxationDelay); /* Spinning Rate */ ValueWithUnitType spinningRate = objFactory.createValueWithUnitType(); spinningRate.setValue("0"); spinningRate.setUnitCvRef(cvUnitNone.getCvRef()); spinningRate.setUnitAccession(cvUnitNone.getAccession()); spinningRate.setUnitName(cvUnitNone.getName()); acqparam.setSpinningRate(spinningRate); /* PulseSequenceType object */ PulseSequenceType.PulseSequenceFileRefList pulseFileRefList = objFactory .createPulseSequenceTypePulseSequenceFileRefList(); SourceFileRefType pulseFileRef = objFactory.createSourceFileRefType(); pulseFileRef.setRef(hSourceFileObj.get("PULSEPROGRAM_FILE")); pulseFileRefList.getSourceFileRef().add(pulseFileRef); PulseSequenceType pulse_sequence = objFactory.createPulseSequenceType(); pulse_sequence.setPulseSequenceFileRefList(pulseFileRefList); UserParamType pulseParam = objFactory.createUserParamType(); pulseParam.setName("Pulse Program"); pulseParam.setValue(acq.getPulseProgram()); pulse_sequence.getUserParam().add(pulseParam); acqparam.setPulseSequence(pulse_sequence); /* DirectDimensionParameterSet object */ AcquisitionDimensionParameterSetType acqdimparam = objFactory .createAcquisitionDimensionParameterSetType(); acqdimparam.setNumberOfDataPoints(getBigInteger(acq.getAquiredPoints())); acqdimparam.setAcquisitionNucleus(cvLoader.fetchCVTerm("CHEBI", acq.getObservedNucleus())); // Spectral Width (Hz) ValueWithUnitType SweepWidth = objFactory.createValueWithUnitType(); SweepWidth.setValue(String.format("%f", acq.getSpectralWidthHz())); SweepWidth.setUnitCvRef(cvUnitHz.getCvRef()); SweepWidth.setUnitAccession(cvUnitHz.getAccession()); SweepWidth.setUnitName(cvUnitHz.getName()); acqdimparam.setSweepWidth(SweepWidth); // Irradiation Frequency (Hz) ValueWithUnitType IrradiationFrequency = objFactory.createValueWithUnitType(); IrradiationFrequency.setValue(String.format("%f", acq.getTransmiterFreq())); IrradiationFrequency.setUnitCvRef(cvUnitmHz.getCvRef()); IrradiationFrequency.setUnitAccession(cvUnitmHz.getAccession()); IrradiationFrequency.setUnitName(cvUnitmHz.getName()); acqdimparam.setIrradiationFrequency(IrradiationFrequency); // setEffectiveExcitationField (Hz) ValueWithUnitType effectiveExcitationField = objFactory.createValueWithUnitType(); effectiveExcitationField.setValue(String.format("%f", acq.getSpectralFrequency())); effectiveExcitationField.setUnitCvRef(cvUnitmHz.getCvRef()); effectiveExcitationField.setUnitAccession(cvUnitmHz.getAccession()); effectiveExcitationField.setUnitName(cvUnitmHz.getName()); acqdimparam.setEffectiveExcitationField(effectiveExcitationField); /* Pulse Width */ ValueWithUnitType pulseWidth = objFactory.createValueWithUnitType(); pulseWidth.setValue(String.format("%f", acq.getPulseWidth())); pulseWidth.setUnitCvRef(cvUnitmSec.getCvRef()); pulseWidth.setUnitAccession(cvUnitmSec.getAccession()); pulseWidth.setUnitName(cvUnitmSec.getName()); acqdimparam.setPulseWidth(pulseWidth); /* decouplingNucleus */ CVTermType cvDecoupledNucleus = null; if (acq.getDecoupledNucleus().equals("off")) { acqdimparam.setDecoupled(false); cvDecoupledNucleus = cvLoader.fetchCVTerm("NMRCV", "OFF_DECOUPLE"); } else { acqdimparam.setDecoupled(true); cvDecoupledNucleus = cvLoader.fetchCVTerm("CHEBI", acq.getDecoupledNucleus()); } acqdimparam.setDecouplingNucleus(cvDecoupledNucleus); /* TODO: samplingStrategy */ acqdimparam.setSamplingStrategy(cvLoader.fetchCVTerm("NMRCV", "UNIFORM_SAMPLING")); acqparam.setDirectDimensionParameterSet(acqdimparam); /* AcquisitionParameterFileRefList object */ SourceFileRefListType acqFileRefList = objFactory.createSourceFileRefListType(); SourceFileRefType acqFileRef = objFactory.createSourceFileRefType(); acqFileRef.setRef(hSourceFileObj.get("ACQUISITION_FILE")); acqFileRefList.getSourceFileRef().add(acqFileRef); SourceFileRefType fidFileRef = objFactory.createSourceFileRefType(); fidFileRef.setRef(hSourceFileObj.get("FID_FILE")); acqFileRefList.getSourceFileRef().add(fidFileRef); acqparam.setAcquisitionParameterFileRefList(acqFileRefList); /* Acquisition1D object */ Acquisition1DType acq1Dtype = objFactory.createAcquisition1DType(); acq1Dtype.setAcquisitionParameterSet(acqparam); /* fidData object */ if (hBinaryDataObj.containsKey("FID_FILE") && hBinaryDataObj.get("FID_FILE").isExists()) { BinaryDataArrayType fidData = objFactory.createBinaryDataArrayType(); fidData.setEncodedLength(hBinaryDataObj.get("FID_FILE").getEncodedLength()); //fidData.setByteFormat(vendorMapper.getTerm("BYTEFORMAT","FID_FILE")); fidData.setByteFormat(hBinaryDataObj.get("FID_FILE").getByteFormat()); fidData.setCompressed(hBinaryDataObj.get("FID_FILE").isCompressed()); if (cmd.hasOption("d")) { fidData.setValue(hBinaryDataObj.get("FID_FILE").getData()); } acq1Dtype.setFidData(fidData); } /* Acquisition oject */ AcquisitionType acqtype = objFactory.createAcquisitionType(); acqtype.setAcquisition1D(acq1Dtype); nmrMLtype.setAcquisition(acqtype); /* PROCESSING PARAMETERS */ if (!cmd.hasOption("only-fid") && hBinaryDataObj.containsKey("REAL_DATA_FILE")) { /* DataProcessing List */ DataProcessingListType dataproclist = objFactory.createDataProcessingListType(); DataProcessingType dataproc = objFactory.createDataProcessingType(); ProcessingMethodType procmethod = objFactory.createProcessingMethodType(); procmethod.setOrder(getBigInteger(1)); procmethod.setSoftwareRef(software1); procmethod.getCvParam().add(cvLoader.fetchCVParam("NMRCV", "DATA_TRANSFORM")); dataproc.getProcessingMethod().add(procmethod); dataproc.setId(getNewIdentifier()); dataproclist.getDataProcessing().add(dataproc); nmrMLtype.setDataProcessingList(dataproclist); /* Spectrum List */ SpectrumListType spectrumList = objFactory.createSpectrumListType(); spectrumList.setDefaultDataProcessingRef(dataproc); Spectrum1DType spectrum1D = objFactory.createSpectrum1DType(); /* Spectrum1D - FirstDimensionProcessingParameterSet object */ FirstDimensionProcessingParameterSetType ProcParam1D = objFactory .createFirstDimensionProcessingParameterSetType(); /* Spectrum1D - WindowFunction */ FirstDimensionProcessingParameterSetType.WindowFunction windowFunction = objFactory .createFirstDimensionProcessingParameterSetTypeWindowFunction(); CVTermType cvWinFunc = cvLoader.fetchCVTerm("NMRCV", vendorMapper.getTerm("WDW", String.format("%d", proc.getWindowFunctionType()))); windowFunction.setWindowFunctionMethod(cvWinFunc); CVParamType cvWinParam = cvLoader.fetchCVParam("NMRCV", "LINE_BROADENING"); cvWinParam.setValue(String.format("%f", proc.getLineBroadening())); windowFunction.getWindowFunctionParameter().add(cvWinParam); ProcParam1D.getWindowFunction().add(windowFunction); ProcParam1D.setNoOfDataPoints(getBigInteger(proc.getTransformSize())); /* Spectrum1D - Phasing */ ValueWithUnitType zeroOrderPhaseCorrection = objFactory.createValueWithUnitType(); zeroOrderPhaseCorrection.setValue(String.format("%f", proc.getZeroOrderPhase())); zeroOrderPhaseCorrection.setUnitCvRef(cvUnitDeg.getCvRef()); zeroOrderPhaseCorrection.setUnitAccession(cvUnitDeg.getAccession()); zeroOrderPhaseCorrection.setUnitName(cvUnitDeg.getName()); ProcParam1D.setZeroOrderPhaseCorrection(zeroOrderPhaseCorrection); ValueWithUnitType firstOrderPhaseCorrection = objFactory.createValueWithUnitType(); firstOrderPhaseCorrection.setValue(String.format("%f", proc.getFirstOrderPhase())); firstOrderPhaseCorrection.setUnitCvRef(cvUnitDeg.getCvRef()); firstOrderPhaseCorrection.setUnitAccession(cvUnitDeg.getAccession()); firstOrderPhaseCorrection.setUnitName(cvUnitDeg.getName()); ProcParam1D.setFirstOrderPhaseCorrection(firstOrderPhaseCorrection); /* Calibration Reference Shift */ ValueWithUnitType calibrationReferenceShift = objFactory.createValueWithUnitType(); calibrationReferenceShift.setValue("undefined"); calibrationReferenceShift.setUnitCvRef(cvUnitNone.getCvRef()); calibrationReferenceShift.setUnitAccession(cvUnitNone.getAccession()); calibrationReferenceShift.setUnitName(cvUnitNone.getName()); ProcParam1D.setCalibrationReferenceShift(calibrationReferenceShift); /* spectralDenoisingMethod */ ProcParam1D.setSpectralDenoisingMethod(cvLoader.fetchCVTerm("NCIThesaurus", "UNDEFINED")); /* baselineCorrectionMethod */ ProcParam1D.setBaselineCorrectionMethod(cvLoader.fetchCVTerm("NCIThesaurus", "UNDEFINED")); /* Spectrum1D - Source File Ref */ SourceFileRefType procFileRef = objFactory.createSourceFileRefType(); procFileRef.setRef(hSourceFileObj.get("PROCESSING_FILE")); ProcParam1D.setParameterFileRef(procFileRef); spectrum1D.setFirstDimensionProcessingParameterSet(ProcParam1D); /* SpectrumType - X Axis */ AxisWithUnitType Xaxis = objFactory.createAxisWithUnitType(); Xaxis.setUnitCvRef(cvUnitPpm.getCvRef()); Xaxis.setUnitAccession(cvUnitPpm.getAccession()); Xaxis.setUnitName(cvUnitPpm.getName()); Xaxis.setStartValue(String.format("%f", proc.getMaxPpm())); Xaxis.setEndValue(String.format("%f", proc.getMaxPpm() - acq.getSpectralWidthHz() / acq.getSpectralFrequency())); spectrum1D.setXAxis(Xaxis); /* SpectrumType - Y Axis */ spectrum1D.setYAxisType(cvUnitNone); /* SpectrumType - Software, Contact Ref List */ spectrum1D.getProcessingSoftwareRefList().add(softwareRefList); spectrum1D.setProcessingContactRefList(contactRefList); /* SpectrumType - ProcessingParameterSet */ SpectrumType.ProcessingParameterSet procParamSet = objFactory .createSpectrumTypeProcessingParameterSet(); procParamSet.setDataTransformationMethod(cvLoader.fetchCVTerm("NMRCV", "FFT_TRANSFORM")); procParamSet.setPostAcquisitionSolventSuppressionMethod( cvLoader.fetchCVTerm("NCIThesaurus", "UNDEFINED")); procParamSet.setCalibrationCompound(cvLoader.fetchCVTerm("NCIThesaurus", "UNDEFINED")); spectrum1D.setProcessingParameterSet(procParamSet); /* SpectrumDataArray object */ if (hBinaryDataObj.containsKey("REAL_DATA_FILE") && hBinaryDataObj.get("REAL_DATA_FILE").isExists()) { BinaryDataArrayType RealData = objFactory.createBinaryDataArrayType(); RealData.setEncodedLength(hBinaryDataObj.get("REAL_DATA_FILE").getEncodedLength()); RealData.setByteFormat(vendorMapper.getTerm("BYTEFORMAT", "REAL_DATA_FILE")); RealData.setCompressed(hBinaryDataObj.get("REAL_DATA_FILE").isCompressed()); if (cmd.hasOption("d")) { RealData.setValue(hBinaryDataObj.get("REAL_DATA_FILE").getData()); } spectrum1D.setSpectrumDataArray(RealData); } spectrum1D.setNumberOfDataPoints(getBigInteger(proc.getTransformSize())); spectrumList.getSpectrum1D().add(spectrum1D); nmrMLtype.setSpectrumList(spectrumList); } /* Generate XML */ JAXBElement<NmrMLType> nmrML = (JAXBElement<NmrMLType>) objFactory.createNmrML(nmrMLtype); // create a JAXBContext capable of handling classes generated into the org.nmrml.schema package JAXBContext jc = JAXBContext.newInstance(NmrMLType.class); // create a Marshaller and marshal to a file / stdout Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, schemaLocation); if (cmd.hasOption("o")) { m.marshal(nmrML, new File(cmd.getOptionValue("o", "output.nmrML"))); } else { m.marshal(nmrML, System.out); } } catch (MissingOptionException e) { boolean help = false; boolean version = false; try { Options helpOptions = new Options(); helpOptions.addOption("h", "help", false, "prints the help content"); helpOptions.addOption("v", "version", false, "prints the version"); CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(helpOptions, args); if (line.hasOption("h")) help = true; if (line.hasOption("v")) version = true; } catch (Exception ex) { } if (!help && !version) System.err.println(e.getMessage()); if (help) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("converter", options); } if (version) { System.out.println("nmrML Converter version = " + Version); } System.exit(1); } catch (MissingArgumentException e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("App", options); System.exit(1); } catch (ParseException e) { System.err.println("Error while parsing the command line: " + e.getMessage()); System.exit(1); } catch (JAXBException je) { je.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.orcid.jaxb.model.notification.addactivities.MarshallingTest.java
@Test public void testMarshalling() throws JAXBException, IOException, SAXException { NotificationAddActivities notification = getNotification(); assertNotNull(notification);/*from w w w . j av a 2s . c o m*/ assertEquals(NotificationType.ADD_ACTIVITIES, notification.getNotificationType()); assertEquals(2, notification.getActivities().getActivities().size()); assertEquals("2014-01-01T14:45:32", notification.getSentDate().toXMLFormat()); // Back the other way String expected = IOUtils.toString(getClass().getResourceAsStream(SAMPLE_PATH), "UTF-8"); Pattern pattern = Pattern.compile("<!--.*?-->\\s*", Pattern.DOTALL); expected = pattern.matcher(expected).replaceAll(""); JAXBContext context = JAXBContext.newInstance("org.orcid.jaxb.model.notification.addactivities"); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.orcid.org/ns/notification ../notification-add-activities-2.0_rc1.xsd"); StringWriter writer = new StringWriter(); marshaller.marshal(notification, writer); XMLUnit.setIgnoreWhitespace(true); Diff diff = new Diff(expected, writer.toString()); assertTrue(diff.identical()); }