Example usage for javax.xml.bind Unmarshaller unmarshal

List of usage examples for javax.xml.bind Unmarshaller unmarshal

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller unmarshal.

Prototype

public Object unmarshal(javax.xml.stream.XMLEventReader reader) throws JAXBException;

Source Link

Document

Unmarshal XML data from the specified pull parser and return the resulting content tree.

Usage

From source file:eu.learnpad.core.impl.cw.XwikiBridgeInterfaceRestResource.java

@Override
public PFResults getFeedbacks(String modelSetId) throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/bridge/%s/feedbacks", DefaultRestResource.REST_URI, modelSetId);
    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader("Accept", "application/xml");

    InputStream pfStream = null;/*  w ww.  j  a v  a  2s.  c  o  m*/
    PFResults pf = null;

    try {
        httpClient.executeMethod(getMethod);

        pfStream = getMethod.getResponseBodyAsStream();

        JAXBContext jc = JAXBContext.newInstance(PFResults.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        pf = (PFResults) unmarshaller.unmarshal(pfStream);
    } catch (JAXBException | IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
    return pf;
}

From source file:com.github.jrrdev.mantisbtsync.core.common.auth.PortalAuthBuilder.java

/**
 * Build the portal authentication manager from an XML file
 * describing the sequence of requests to be sent.
 *
 * @param filepath/*www .ja  va2s  . c o m*/
 *       File path of the XML file. The file is loaded through Spring resource loader, so
 *       the file path can contain definition like "classpath:"
 * @return the portal authentication manager
 * @throws JAXBException
 *       If an error occurs during the XML unmarshalling
 * @throws IOException
 *       if the resource cannot be resolved as absolute file path, i.e. if the resource is
 *       not available in a file system
 */
public PortalAuthManager buildAuthManager(final String filepath) throws JAXBException, IOException {
    final PortalAuthManager mgr = new PortalAuthManager();

    if (filepath != null && !filepath.isEmpty()) {

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Loading portal authentication configuration from file : " + filepath);
        }

        final File file = resourceLoader.getResource(filepath).getFile();

        if (file.exists() && file.isFile() && file.canRead()) {
            final JAXBContext jaxbContext = JAXBContext.newInstance(AuthSequenceBean.class);
            final Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            final AuthSequenceBean sequence = (AuthSequenceBean) jaxbUnmarshaller.unmarshal(file);

            if (sequence != null) {
                mgr.setFirstRequest(buildRequest(sequence.getFirstRequest()));
            }

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Portal authentication configuration loaded");
            }

        } else {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(
                        "Portal authentication configuration loading failed, file may not exists or can't be read");
                throw new IOException(
                        "Portal authentication configuration loading failed, file may not exists or can't be read : "
                                + filepath);
            }
        }
    } else if (LOGGER.isInfoEnabled()) {
        LOGGER.info("No portal authentication configuration file specified");
    }

    return mgr;
}

From source file:org.usd.edu.btl.cli.ConvertGalaxy.java

public void toBets(String inputS, String output) {
    System.out.println("Converting from GALAXY TO BETS");
    File input = new File(inputS);

    InputStream infile = null;//from  w w w  . j  ava  2  s. co m
    Tool myTool = null;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Tool.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); //Unmarshalling  Conversion XML content into a Java Object.
        infile = new FileInputStream(input);
        Tool test_tool = (Tool) unmarshaller.unmarshal(infile);
        myTool = test_tool;
        //System.out.println(test_tool.toString()); //print the test_tool 

    } catch (FileNotFoundException | JAXBException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            if (infile != null) {
                infile.close();
            }
        } catch (IOException e) {
            System.out.println("You're rubbish, you can't even close a file");
            System.out.println(e.getMessage());
        }
    }

    //JAXB-Marshall Java back to XML
    //        try {
    //            JAXBContext jaxbContext = JAXBContext.newInstance(Tool.class);
    //            Marshaller marshaller = jaxbContext.createMarshaller(); //Marshalling  Conversion a Java object into a XML file.
    //            marshaller.marshal(myTool, System.out); //print XML out
    //        } catch (JAXBException e) {
    //            System.out.println("JAXB dun goofed");
    //            System.out.println(e.getMessage());
    //        }
    // RUN GALAXY TO BETS CONVERSION
    BETSV1 betsOutput = GalaxyConverter.toBETS(myTool);
    try {
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("************************************************\n"
                + "*********PRINTING OUT CONVERSION************\n" + "----------Galaxy --> Bets--------------\n"
                + "************************************************\n");
        //print objects as Json using jackson
        ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
        String betsJson = ow.writeValueAsString(betsOutput); //write Json as String
        System.out.println("=== GALAXY TO BETS JSON === \n" + betsJson);

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

From source file:de.uni_potsdam.hpi.bpt.promnicat.importer.ibm.test.IBMImporterTest.java

@Test
public void parse() throws JAXBException, JSONException {
    File xml = new File("resources\\IBM\\A\\s00000016\\s00000018\\s00000020\\s00000024\\s00000777.bpmn.xml");
    JAXBContext context = JAXBContext.newInstance(Definitions.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    Definitions definitions = (Definitions) unmarshaller.unmarshal(xml);

    List<Diagram> diagrams = new ArrayList<Diagram>();
    for (RootElement e : definitions.getRootElement()) {
        if (e instanceof de.hpi.bpmn2_0.model.Process) {
            de.hpi.bpmn2_0.model.Process p = (de.hpi.bpmn2_0.model.Process) e;
            String resourceId = "oryx-canvas123";
            StencilType type = new StencilType("BPMNDiagram");
            String stencilSetNs = "http://b3mn.org/stencilset/bpmn2.0#";
            String url = "/oryx/stencilsets/bpmn2.0/bpmn2.0.json";
            StencilSet stencilSet = new StencilSet(url, stencilSetNs);
            Diagram diagram = new Diagram(resourceId, type, stencilSet);

            //         List<Shape> shapes = new ArrayList<Shape>();
            Map<String, Shape> shapes = new HashMap<String, Shape>();
            for (FlowElement flowElement : p.getFlowElement()) {
                if (flowElement instanceof Edge) {
                    Edge edge = (Edge) flowElement;
                    if (edge.getSourceRef() != null) {
                        //FIXME parse all nodes first and afterwards add edges.
                        shapes.get(edge.getSourceRef().getId()).addOutgoing(new Shape(edge.getId()));
                    }//from ww w. j  a v  a 2 s  .  c om

                }
                Shape shape = new Shape(flowElement.getId());
                Point lr = new Point(200d, 200d);
                Point ul = new Point(100d, 100d);
                Bounds bounds = new Bounds(lr, ul);
                shape.setBounds(bounds);
                flowElement.toShape(shape);
                if (flowElement.getName() != null) {
                    shape.getProperties().put("name", flowElement.getName());
                }
                shapes.put(flowElement.getId(), shape);
            }

            diagram.getChildShapes().addAll(shapes.values());

            diagrams.add(diagram);
        }
    }
    //TODO use logger
    System.out.println(JSONBuilder.parseModeltoString(diagrams.get(0)));

}

From source file:fr.mael.microrss.xml.AtomFeedParser.java

@Override
public List<Article> readArticles(Feed feed) throws Exception {
    List<Article> articles = new ArrayList<Article>();
    JAXBContext jc = JAXBContext.newInstance("fr.mael.microrss.xml.atom");
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    HttpGet get = new HttpGet(feed.getUrl());
    HttpResponse response = client.execute(get);
    try {//  w  w  w.j  a v  a2s  . c o m
        Object o = unmarshaller.unmarshal(response.getEntity().getContent());
        if (o instanceof JAXBElement) {
            JAXBElement element = (JAXBElement) o;
            FeedType feedType = (FeedType) element.getValue();
            articles = readEntries(feedType.getAuthorOrCategoryOrContributor(), feed, feedType);
        }
        return articles;
    } catch (Exception e) {
        EntityUtils.consume(response.getEntity());
        throw new Exception(e);
    }
}

From source file:net.urlgrey.mythpodcaster.dao.SubscriptionsDAOImpl.java

/**
 * @param subscriptionsFile//from w  ww.j a  v  a2  s  .c o  m
 * @return
 */
private FeedSubscriptions loadSubscriptionDocument() {
    final File subscriptionsFile = new File(subscriptionsFilePath);
    FeedSubscriptions subscriptionsDocument = null;
    if (subscriptionsFile.exists()) {
        try {
            final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            subscriptionsDocument = (FeedSubscriptions) unmarshaller.unmarshal(subscriptionsFile);
        } catch (JAXBException e) {
            LOGGER.error("Unable to unmarshal subscriptions document from XML", e);
        }

        if (subscriptionsDocument == null) {
            subscriptionsDocument = new FeedSubscriptions();
        }
    } else {
        subscriptionsDocument = new FeedSubscriptions();
    }
    return subscriptionsDocument;
}

From source file:org.jasig.portlet.courses.dao.xml.Jaxb2CourseSummaryHttpMessageConverter.java

@Override
protected Object readFromSource(Class<? extends Object> clazz, HttpHeaders headers, Source source)
        throws IOException {
    try {/*from w w w.  ja  v a  2  s.c o m*/
        Unmarshaller unmarshaller = createWrapperUnmarshaller(clazz);
        if (clazz.isAnnotationPresent(XmlRootElement.class)) {
            return unmarshaller.unmarshal(source);
        } else {
            JAXBElement<? extends Object> jaxbElement = unmarshaller.unmarshal(source, clazz);
            return jaxbElement.getValue();
        }
    } catch (UnmarshalException ex) {
        throw new HttpMessageNotReadableException("Could not unmarshal to [" + clazz + "]: " + ex.getMessage(),
                ex);

    } catch (JAXBException ex) {
        throw new HttpMessageConversionException("Could not instantiate JAXBContext: " + ex.getMessage(), ex);
    }
}

From source file:mx.bigdata.sat.cfd.CFDv2.java

private Comprobante copy(Comprobante comprobante) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from w ww.  java2  s.  c  o  m*/
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Marshaller m = context.createMarshaller();
    m.marshal(comprobante, doc);
    Unmarshaller u = context.createUnmarshaller();
    return (Comprobante) u.unmarshal(doc);
}

From source file:ait.ffma.service.preservation.riskmanagement.api.riskanalysis.risk.RiskUtils.java

/**
 * This method returns risk analysis object.
 * @return//  w  ww. ja va  2s  . co  m
 */
public static RiskAnalysis loadRiskAnalysis() {
    if (RiskUtils.ra == null
            || RiskUtils.getGeneralProperty("RiskAnalysis.ReloadXML").equalsIgnoreCase("true")) {
        try {
            JAXBContext jc = JAXBContext.newInstance(RiskAnalysis.class);
            Unmarshaller u = jc.createUnmarshaller();
            InputStream in = RiskUtils.class
                    .getResourceAsStream(RiskUtils.getGeneralProperty("Riskanalysis.XML"));
            ra = (RiskAnalysis) u.unmarshal(in);
        } catch (JAXBException e) {
            LOG.log(Level.SEVERE, e.getMessage());
            return null;
        }
        RiskUtils.setGeneralProperty("RiskAnalysis.ReloadXML", "false");
    }
    resetProperties(ra.getRiskFactors());
    return ra;
}

From source file:com.tera.common.dataload.xml.XMLDataLoadService.java

/**
 * For all files in specified directory recursively unmarshall all xml's into
 * one object/*from  w  w w. ja va2s. c  o m*/
 * 
 * @param un
 * @param dir
 * @return
 * @throws JAXBException
 */
private T loadFromRealDirectory(Unmarshaller un, File dir) throws JAXBException {
    T container = null;
    for (File file : FileUtils.listFiles(dir, new String[] { "xml" }, true)) {
        @SuppressWarnings("unchecked")
        T data = (T) un.unmarshal(file);
        if (container == null) {
            container = data;
        } else {
            container.combine(data);
        }
    }
    return container;
}