Example usage for javax.xml.bind JAXBException printStackTrace

List of usage examples for javax.xml.bind JAXBException printStackTrace

Introduction

In this page you can find the example usage for javax.xml.bind JAXBException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this JAXBException and its stack trace (including the stack trace of the linkedException if it is non-null) to System.err .

Usage

From source file:org.kalypso.ogc.core.exceptions.OWSException.java

/**
 * This function serializes the OWS exception into XML form.
 *
 * @return The OWS exception in XML form.
 *//*ww  w  .  j a  v  a 2  s .c om*/
public String toXML() {
    /* The string writer. */
    StringWriter writer = null;

    try {
        /* Create the string writer. */
        writer = new StringWriter();

        /* Retrieve the exception types. */
        final ExceptionType[] exceptions = getExceptionTypes();

        /* Build the exception report. */
        final ExceptionReport exeptionReport = OWSUtilities.buildExeptionReport(exceptions, m_version, m_lang);

        /* Marshall into the string writer. */
        OWSUtilities.marshal(exeptionReport, writer);

        /* Return the marshalled OWS exception as XML. */
        return writer.toString();
    } catch (final JAXBException ex) {
        /* Ignore this exception. */
        ex.printStackTrace();

        /* There was an error marshalling the OWS exception into a XML. */
        /* We can only return the exception text as fallback. */
        return getLocalizedMessage();
    } finally {
        /* Close the string writer. */
        IOUtils.closeQuietly(writer);
    }
}

From source file:org.kalypso.ogc.sensor.request.RequestFactory.java

/**
 * Parse an href (usually a Zml-Href) that might contain the request specification
 * /*  w w  w .  j  a  v a  2s .c  o  m*/
 * @throws SensorException
 *           if the href does not contain a valid request
 */
public static Request parseRequest(final String href) throws SensorException {
    if (href == null || href.length() == 0)
        return null;

    // final int i1 = href.indexOf( ZmlURLConstants.TAG_REQUEST1 );
    // if( i1 == -1 )
    // return null;
    // final int i2 = href.indexOf( ZmlURLConstants.TAG_REQUEST2, i1 );
    // if( i2 == -1 )
    final String strRequestXml = XMLStringUtilities.getXMLPart(href, ZmlURLConstants.TAG_REQUEST);
    if (strRequestXml == null)
        return null;

    // throw new SensorException( "URL-fragment does not contain a valid request definition. URL: " + href );
    // final String strRequestXml = href.substring( i1, i2 + ZmlURLConstants.TAG_REQUEST2.length() );
    StringReader sr = null;
    try {
        sr = new StringReader(strRequestXml);
        final Request xmlReq = (Request) JC.createUnmarshaller().unmarshal(new InputSource(sr));
        sr.close();
        return xmlReq;
    } catch (final JAXBException e) {
        e.printStackTrace();
        throw new SensorException(e);
    } finally {
        IOUtils.closeQuietly(sr);
    }
}

From source file:org.kalypso.simulation.core.KalypsoSimulationCoreJaxb.java

private static Unmarshaller createUnmarshaller() {
    try {/* w w  w .  jav  a 2s .c  o  m*/
        return JC.createUnmarshaller();
    } catch (final JAXBException e) {
        // will not happen
        e.printStackTrace();
        return null;
    }
}

From source file:org.n52.wps.ags.algorithmpackage.AlgorithmPackage.java

private static AlgorithmDescription createAlgorithmDescription(File xmlFile) {

    // create the AlgorithmDescription document from DescribeProcess file
    StringReader adReader = generateAlgorithmDescription(xmlFile);

    try {//w w w.  ja va 2s . co m
        JAXBContext jc = JAXBContext.newInstance(AlgorithmDescription.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        AlgorithmDescription ad = (AlgorithmDescription) unmarshaller.unmarshal(adReader);
        return ad;
    } catch (JAXBException e) {
        LOGGER.error("Unable to create AlgorithmDescription from xmlFile: " + xmlFile.getAbsolutePath());
        e.printStackTrace();
        return null;
    }

}

From source file:org.netbeans.jbpmn.modeler.specification.bpmn.model.conversation.util.BPMNConversationUtil.java

@Override
public void loadModelerFile(ModelerFile file) {
    try {// w  w w  . ja  v  a 2  s . c om
        IModelerScene scene = file.getModelerScene();
        File savedFile = file.getFile();
        if (bpmnConversationContext == null) {
            bpmnConversationContext = JAXBContext
                    .newInstance(new Class<?>[] { ShapeDesign.class, TDefinitions.class });
        }
        if (bpmnConversationUnmarshaller == null) {
            bpmnConversationUnmarshaller = bpmnConversationContext.createUnmarshaller();
        }
        bpmnConversationUnmarshaller.setEventHandler(new ValidateJAXB());
        TDefinitions definition_Load = bpmnConversationUnmarshaller
                .unmarshal(new StreamSource(savedFile), TDefinitions.class).getValue();
        //            TDefinitions definition_Load = (TDefinitions) JAXBIntrospector.getValue(bpmnConversationUnmarshaller.unmarshal(savedFile));

        TCollaboration collaboration = new TCollaboration();

        for (TRootElement element : new CopyOnWriteArrayList<TRootElement>(definition_Load.getRootElement())) {
            if (element instanceof TCollaboration) {
                TCollaboration collaboration_Tmp = ((TCollaboration) element);
                String name = collaboration_Tmp.getName();
                if (name != null && !name.trim().isEmpty()) {
                    collaboration.setName(name);
                }
                String id = collaboration_Tmp.getId();
                if (id != null && !id.trim().isEmpty()) {
                    collaboration.setId(id);
                }
                collaboration.getConversationLink().addAll(collaboration_Tmp.getConversationLink());
                collaboration.getMessageFlow().addAll(collaboration_Tmp.getMessageFlow());
                collaboration.getConversationNode().addAll(collaboration_Tmp.getConversationNode());
                collaboration.getParticipant().addAll(collaboration_Tmp.getParticipant());
                collaboration.getArtifact().addAll(collaboration_Tmp.getArtifact());
                definition_Load.getRootElement().remove(collaboration_Tmp);
            } else if (element instanceof TProcess) {
                TProcess process_Tmp = (TProcess) element;
                collaboration.getArtifact().addAll(process_Tmp.getArtifact());
                definition_Load.getRootElement().remove(process_Tmp);
            }
        }

        definition_Load.getRootElement().add(collaboration);
        scene.setRootElementSpec(collaboration);

        BPMNDiagram diagram = new BPMNDiagram();
        diagram.setId(NBModelerUtil.getAutoGeneratedStringId());
        BPMNPlane plane = new BPMNPlane();
        plane.setId(NBModelerUtil.getAutoGeneratedStringId());
        diagram.setBPMNPlane(plane);

        for (BPMNDiagram diagram_Tmp : definition_Load.getBPMNDiagram()) {
            if (diagram_Tmp instanceof BPMNDiagram) {
                BPMNPlane tmpPlane = diagram_Tmp.getBPMNPlane();
                for (DiagramElement element : tmpPlane.getDiagramElement()) {
                    plane.getDiagramElement().add(element);
                }
            }
        }
        definition_Load.getBPMNDiagram().removeAll(definition_Load.getBPMNDiagram());
        definition_Load.getBPMNDiagram().add(diagram);

        file.getModelerDiagramModel().setDefinitionElement(definition_Load);
        file.getModelerDiagramModel().setRootElement(collaboration);
        file.getModelerDiagramModel().setDiagramElement(diagram);

        //ELEMENT_UPGRADE
        for (IFlowNode flowNode : new CopyOnWriteArrayList<IFlowNode>(collaboration.getConversationNode())) {
            loadNode(scene, (Widget) scene, flowNode);
        }

        for (IFlowNode flowNode : new CopyOnWriteArrayList<IFlowNode>(collaboration.getParticipant())) {
            loadNode(scene, (Widget) scene, flowNode);
        }

        for (IFlowEdge flowEdge : new CopyOnWriteArrayList<IFlowEdge>(collaboration.getConversationLink())) {
            loadEdge(scene, flowEdge);
        }

        for (IFlowEdge flowEdge : new CopyOnWriteArrayList<IFlowEdge>(collaboration.getMessageFlow())) {
            loadEdge(scene, flowEdge);
        }

        for (IArtifact artifact_Load : new CopyOnWriteArrayList<IArtifact>(collaboration.getArtifact())) {
            loadArtifact(scene, artifact_Load);
        }

        for (DiagramElement diagramElement_Tmp : diagram.getBPMNPlane().getDiagramElement()) {
            loadDiagram(scene, diagram, diagramElement_Tmp);
        }
    } catch (JAXBException e) {
        io.getOut().println("Exception: " + e.toString());
        e.printStackTrace();
        //            Exceptions.printStackTrace(e);
        System.out.println("Document XML Not Exist");
    }

}

From source file:org.netbeans.jbpmn.modeler.specification.bpmn.model.process.util.BPMNProcessUtil.java

@Override
public void loadModelerFile(ModelerFile file) {
    try {//www . jav  a 2 s. co m
        IModelerScene scene = file.getModelerScene();
        File savedFile = file.getFile();
        //            savedFile.getTotalSpace()
        if (bpmnProcessContext == null) {
            bpmnProcessContext = JAXBContext
                    .newInstance(new Class<?>[] { ShapeDesign.class, TDefinitions.class });
        }
        if (bpmnProcessUnmarshaller == null) {
            bpmnProcessUnmarshaller = bpmnProcessContext.createUnmarshaller();
        }
        bpmnProcessUnmarshaller.setEventHandler(new ValidateJAXB());
        TDefinitions definition_Load = bpmnProcessUnmarshaller
                .unmarshal(new StreamSource(savedFile), TDefinitions.class).getValue();

        Set<String> noneTypeProcess = new HashSet<String>();
        Set<String> allProcess = new HashSet<String>();
        Set<String> mainProcess;

        for (TRootElement element : definition_Load.getRootElement()) {
            if (element instanceof TCollaboration) {
                TCollaboration collaboration = ((TCollaboration) element);
                for (TParticipant participant : collaboration.getParticipant()) {
                    noneTypeProcess.add(participant.getProcessRef());
                }
            }
            if (element instanceof TProcess) {
                TProcess process_Load = (TProcess) element;
                allProcess.add(process_Load.getId());
            }
        }
        mainProcess = new HashSet<String>(allProcess);
        mainProcess.removeAll(noneTypeProcess);

        TProcess process = new TProcess();

        for (String processId : mainProcess) {
            TProcess tmpProcess = definition_Load.getProcess(processId);
            if (tmpProcess != null) {
                String name = tmpProcess.getName();
                if (name != null && !name.trim().isEmpty()) {
                    process.setName(name);
                }
                String id = tmpProcess.getId();
                if (id != null && !id.trim().isEmpty()) {
                    process.setId(id);
                }
                process.getProperty().addAll(tmpProcess.getProperty());
                process.getFlowElement().addAll(tmpProcess.getFlowElement());
                process.getArtifact().addAll(tmpProcess.getArtifact());
                definition_Load.getRootElement().remove(tmpProcess);
            }
        }
        definition_Load.getRootElement().add(process);
        scene.setRootElementSpec(process);

        BPMNDiagram diagram = new BPMNDiagram();
        diagram.setId(NBModelerUtil.getAutoGeneratedStringId());
        BPMNPlane plane = new BPMNPlane();
        plane.setId(NBModelerUtil.getAutoGeneratedStringId());
        diagram.setBPMNPlane(plane);
        //        plane.setBpmnElement(process.getId());

        for (BPMNDiagram diagram_Tmp : definition_Load.getBPMNDiagram()) {
            if (diagram_Tmp instanceof BPMNDiagram) {
                BPMNPlane tmpPlane = diagram_Tmp.getBPMNPlane();
                for (DiagramElement element : tmpPlane.getDiagramElement()) {
                    plane.getDiagramElement().add(element);
                }
            }
        }
        definition_Load.getBPMNDiagram().removeAll(definition_Load.getBPMNDiagram());
        definition_Load.getBPMNDiagram().add(diagram);

        file.getModelerDiagramModel().setDefinitionElement(definition_Load);
        file.getModelerDiagramModel().setRootElement(process);
        file.getModelerDiagramModel().setDiagramElement(diagram);

        //ELEMENT_UPGRADE
        for (IFlowElement flowElement_Load : new CopyOnWriteArrayList<IFlowElement>(process.getFlowElement())) {
            loadFlowNode(scene, (Widget) scene, flowElement_Load);
        }

        for (IFlowElement flowElement_Load : new CopyOnWriteArrayList<IFlowElement>(process.getFlowElement())) {
            loadBoundaryEvent(scene, flowElement_Load);
        }

        for (IFlowElement flowElement_Load : new CopyOnWriteArrayList<IFlowElement>(process.getFlowElement())) {
            loadEdge(scene, flowElement_Load);
        }

        for (IArtifact artifact_Load : new CopyOnWriteArrayList<IArtifact>(process.getArtifact())) {
            loadArtifact(scene, artifact_Load);
        }

        for (DiagramElement diagramElement_Tmp : diagram.getBPMNPlane().getDiagramElement()) {
            loadDiagram(scene, diagram, diagramElement_Tmp);
        }
    } catch (JAXBException e) {
        io.getOut().println("Exception: " + e.toString());
        e.printStackTrace();
        //            Exceptions.printStackTrace(e);
        System.out.println("Document XML Not Exist");
    }

}

From source file:org.niord.importer.aton.AtonImportRestService.java

/** Prints the result to the command line */
private void printResult(List<AtonNode> atons) {

    AtonOsmVo osm = toOsm(atons);/*  w w  w.  j  a va  2s .  c o m*/

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(AtonOsmVo.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(osm, System.out);
    } catch (JAXBException e) {
        e.printStackTrace();
    }

}

From source file:org.nmrml.converter.Converter.java

public static void main(String[] args) {

    /* Containers of Acquisition/Processing Parameters  */
    Acqu acq = null;/*  w  ww. j a  v  a  2 s .  c  o 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.occiware.clouddesigner.occi.hypervisor.connector.libvirt.util.DomainMarshaller.java

public void writeToDisk(final Domain domain) {
    FileOutputStream fos = null;//  www .  j ava 2  s  .c  om
    File file = null;
    try {
        final File tmpDir = this.createTempDir(this.xmlDirectory);
        String _plus = (tmpDir + "/");
        String _uuid = domain.getUuid();
        String _string = _uuid.toString();
        String _plus_1 = (_plus + _string);
        String _plus_2 = (_plus_1 + ".xml");
        File _file = new File(_plus_2);
        file = _file;
        String _absolutePath = file.getAbsolutePath();
        DomainMarshaller.LOGGER.info(_absolutePath);
        boolean _exists = file.exists();
        if (_exists) {
            file.delete();
        }
        FileOutputStream _fileOutputStream = new FileOutputStream(file);
        fos = _fileOutputStream;
        JAXBContext context = JAXBContext.newInstance(Domain.class);
        final Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(domain, fos);
    } catch (final Throwable _t) {
        if (_t instanceof JAXBException) {
            final JAXBException e = (JAXBException) _t;
            e.printStackTrace();
        } else if (_t instanceof FileNotFoundException) {
            final FileNotFoundException e_1 = (FileNotFoundException) _t;
            e_1.printStackTrace();
        } else {
            throw Exceptions.sneakyThrow(_t);
        }
    }
}

From source file:org.openbel.framework.tools.Backtrack.java

private String convert(final Document d) throws ConversionError {
    try {/*from  www  .  jav  a2 s  .c  o  m*/
        return converter.toXML(d);
    } catch (JAXBException e) {
        e.printStackTrace();
        final String name = d.getName();
        final String msg = e.getMessage();
        final Throwable cause = e;
        throw new ConversionError(name, msg, cause);
    } catch (IOException e) {
        final String name = d.getName();
        final String msg = e.getMessage();
        final Throwable cause = e;
        throw new ConversionError(name, msg, cause);
    }
}