Java tutorial
/* * $Id: Converter.java,v 1.0.alpha Feb 2014 (C) INRA - DJ $ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.nmrml.converter; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.MissingArgumentException; import org.apache.commons.cli.MissingOptionException; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.util.GregorianCalendar; import java.util.*; import java.lang.*; import org.nmrml.parser.*; import org.nmrml.parser.bruker.*; import org.nmrml.parser.varian.*; import org.nmrml.schema.*; import org.nmrml.cv.*; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; // create a nmrML file based on a java object tree generated by the JAXB XJC Tool (JDK 7 and above). public class Converter { private static final String Version = "1.0b"; private static final String nmrMLVersion = "1.0.rc1"; public static int ID_count; public static String getNewIdentifier() { return String.format("ID%05d", ++ID_count); } public static BigInteger getBigInteger(Integer entier) { return new BigInteger(entier.toString()); } private enum Vendor_Type { bruker, varian; } private enum BinaryFile_Type { FID_FILE, REAL_DATA_FILE; } public static void main(String[] args) { /* Containers of Acquisition/Processing Parameters */ Acqu acq = null; 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(); } } }