Example usage for javax.xml.bind JAXBContext createUnmarshaller

List of usage examples for javax.xml.bind JAXBContext createUnmarshaller

Introduction

In this page you can find the example usage for javax.xml.bind JAXBContext createUnmarshaller.

Prototype

public abstract Unmarshaller createUnmarshaller() throws JAXBException;

Source Link

Document

Create an Unmarshaller object that can be used to convert XML data into a java content tree.

Usage

From source file:eu.apenet.dpt.standalone.gui.eaccpf.EacCpfFrame.java

public void createFrame(InputStream eacCpfStream, boolean isNew) {
    timeMaintenance = null;/*  w  w  w .j  a  v a 2s .co  m*/
    personResponsible = null;
    inUse(true);
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            inUse(false);
        }
    });
    EacCpf eacCpf = null;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(EacCpf.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        eacCpf = (EacCpf) jaxbUnmarshaller.unmarshal(eacCpfStream);
        eacCpfStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    this.buildPanel(eacCpf, isNew);
    this.getContentPane().add(mainTabbedPane);

    Dimension frameDim = new Dimension(((Double) (dimension.getWidth() * 0.95)).intValue(),
            ((Double) (dimension.getHeight() * 0.95)).intValue());
    this.setSize(frameDim);
    this.setPreferredSize(frameDim);
    this.pack();
    this.setVisible(true);
    this.setExtendedState(JFrame.MAXIMIZED_BOTH);
}

From source file:org.trpr.platform.integration.impl.xml.XMLTranscoderImpl.java

/**
 * Replacement method that uses JAXB directly instead of via Spring OXM. Provided just as an option
 *///from  w  ww  . j  av a  2  s  . c  o m
@SuppressWarnings("unchecked")
private <T> T unmarshalUsingJAXB(String xml, Class<T> clazz) throws XMLDataException {
    try {
        javax.xml.bind.JAXBContext context = javax.xml.bind.JAXBContext
                .newInstance(clazz.getPackage().getName());
        javax.xml.bind.Unmarshaller unmarshaller = context.createUnmarshaller();
        return (T) unmarshaller.unmarshal(new StringReader(xml));
    } catch (javax.xml.bind.JAXBException e) {
        throw new XMLDataException(
                "Error unmarshalling XML. XML:packageName is " + xml + ":" + clazz.getPackage().getName(), e);
    }
}

From source file:eu.eexcess.zbw.recommender.PartnerConnector.java

@Override
public Document queryPartner(PartnerConfiguration partnerConfiguration, SecureUserProfile userProfile,
        PartnerdataLogger logger) throws IOException {

    // Configure/*from   www  .j a  v  a 2 s  .co m*/
    try {
        Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientJAXBContext());
        queryGenerator = PartnerConfigurationEnum.CONFIG.getQueryGenerator();

        String query = getQueryGenerator().toQuery(userProfile);
        query = query.replaceAll("\"", "");
        query = query.replaceAll("\\(", " ");
        query = query.replaceAll("\\)", " ");
        query = URLEncoder.encode(query, "UTF-8");
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("query", query);
        if (userProfile.numResults != null)
            valuesMap.put("size", userProfile.numResults.toString());
        else
            valuesMap.put("size", "10");
        String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);

        WebResource service = client.resource(searchRequest);
        log.log(Level.INFO, "SearchRequest: " + searchRequest);

        Builder builder = service.accept(MediaType.APPLICATION_XML);
        String response = builder.get(String.class);
        StringReader respStringReader = new StringReader(response);
        client.destroy();
        JAXBContext jaxbContext = JAXBContext.newInstance(ZBWDocument.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        ZBWDocument zbwResponse = (ZBWDocument) jaxbUnmarshaller.unmarshal(respStringReader);
        for (ZBWDocumentHit hit : zbwResponse.hits.hit) {
            try {
                if (hit.element.type.equals("event")) {
                    Document detail = fetchDocumentDetails(hit.element.id);
                    PartnerdataTracer.dumpFile(this.getClass(), partnerConfiguration, detail, "detail-response",
                            logger);
                    String latValue = getValueWithXPath("/doc/record/geocode/lat", detail);
                    String longValue = getValueWithXPath("/doc/record/geocode/lng", detail);
                    hit.element.lat = latValue;
                    hit.element.lng = longValue;
                }
            } catch (Exception e) {
                log.log(Level.WARNING,
                        "Could not get longitude and latitude for event element " + hit.element.id, e);
            }
            // put all creators in the creatorString
            if (hit.element.creator != null) {
                for (String creator : hit.element.creator) {
                    if (hit.element.creatorString == null)
                        hit.element.creatorString = "";
                    if (hit.element.creatorString.length() > 0)
                        hit.element.creatorString += ", ";
                    hit.element.creatorString += creator;
                }
            }
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.marshal(zbwResponse, document);

        return document;
    } catch (Exception e) {
        throw new IOException("Cannot query partner REST API!", e);
    }

}

From source file:in.gov.uidai.core.aua.client.AuthClient.java

private AuthRes parseAuthResponseXML(String xmlToParse) throws JAXBException {

    //Create an XMLReader to use with our filter
    try {//from w  w  w  .  jav  a 2s.  c  o m
        //Prepare JAXB objects
        JAXBContext jc = JAXBContext.newInstance(AuthRes.class);
        Unmarshaller u = jc.createUnmarshaller();

        XMLReader reader;
        reader = XMLReaderFactory.createXMLReader();

        //Create the filter (to add namespace) and set the xmlReader as its parent.
        NamespaceFilter inFilter = new NamespaceFilter("http://www.uidai.gov.in/auth/uid-auth-response/1.0",
                true);
        inFilter.setParent(reader);

        //Prepare the input, in this case a java.io.File (output)
        InputSource is = new InputSource(new StringReader(xmlToParse));

        //Create a SAXSource specifying the filter
        SAXSource source = new SAXSource(inFilter, is);

        //Do unmarshalling
        AuthRes res = u.unmarshal(source, AuthRes.class).getValue();
        return res;
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:admincommands.Reload.java

@Override
public void executeCommand(Player admin, String[] params) {
    if (admin.getAccessLevel() < AdminConfig.COMMAND_RELOAD) {
        PacketSendUtility.sendMessage(admin, "You dont have enough rights to execute this command");
        return;/* ww  w  .j a  v  a2 s  .  c  om*/
    }

    if (params == null || params.length != 1) {
        PacketSendUtility.sendMessage(admin, "syntax //reload <quest | skill | portal | spawn | admcmd>");
        return;
    }
    if (params[0].equals("quest")) {
        File xml = new File("./data/static_data/quest_data/quest_data.xml");
        File dir = new File("./data/static_data/quest_script_data");
        try {
            QuestEngine.getInstance().shutdown();
            JAXBContext jc = JAXBContext.newInstance(StaticData.class);
            Unmarshaller un = jc.createUnmarshaller();
            un.setSchema(getSchema("./data/static_data/static_data.xsd"));
            QuestsData newQuestData = (QuestsData) un.unmarshal(xml);
            QuestsData questsData = DataManager.QUEST_DATA;
            questsData.setQuestsData(newQuestData.getQuestsData());
            QuestScriptsData questScriptsData = DataManager.QUEST_SCRIPTS_DATA;
            questScriptsData.getData().clear();
            for (File file : listFiles(dir, true)) {
                QuestScriptsData data = ((QuestScriptsData) un.unmarshal(file));
                if (data != null)
                    if (data.getData() != null)
                        questScriptsData.getData().addAll(data.getData());
            }
            QuestEngine.getInstance().load();
        } catch (Exception e) {
            PacketSendUtility.sendMessage(admin, "Quests reload failed!");
            log.error(e);
        } finally {
            PacketSendUtility.sendMessage(admin, "Quests reloaded successfuly!");
        }
    } else if (params[0].equals("skill")) {
        File dir = new File("./data/static_data/skills");
        try {
            JAXBContext jc = JAXBContext.newInstance(StaticData.class);
            Unmarshaller un = jc.createUnmarshaller();
            un.setSchema(getSchema("./data/static_data/static_data.xsd"));
            List<SkillTemplate> newTemplates = new ArrayList<SkillTemplate>();
            for (File file : listFiles(dir, true)) {
                SkillData data = (SkillData) un.unmarshal(file);
                if (data != null)
                    newTemplates.addAll(data.getSkillTemplates());
            }
            DataManager.SKILL_DATA.setSkillTemplates(newTemplates);
        } catch (Exception e) {
            PacketSendUtility.sendMessage(admin, "Skills reload failed!");
            log.error(e);
        } finally {
            PacketSendUtility.sendMessage(admin, "Skills reloaded successfuly!");
        }
    } else if (params[0].equals("portal")) {
        File dir = new File("./data/static_data/portals");
        try {
            JAXBContext jc = JAXBContext.newInstance(StaticData.class);
            Unmarshaller un = jc.createUnmarshaller();
            un.setSchema(getSchema("./data/static_data/static_data.xsd"));
            List<PortalTemplate> newTemplates = new ArrayList<PortalTemplate>();
            for (File file : listFiles(dir, true)) {
                PortalData data = (PortalData) un.unmarshal(file);
                if (data != null && data.getPortals() != null)
                    newTemplates.addAll(data.getPortals());
            }
            DataManager.PORTAL_DATA.setPortals(newTemplates);
        } catch (Exception e) {
            PacketSendUtility.sendMessage(admin, "Portals reload failed!");
            log.error(e);
        } finally {
            PacketSendUtility.sendMessage(admin, "Portals reloaded successfuly!");
        }
    } else if (params[0].equals("spawn")) {
        File dir = new File("./data/static_data/spawns");
        try {
            JAXBContext jc = JAXBContext.newInstance(StaticData.class);
            Unmarshaller un = jc.createUnmarshaller();
            un.setSchema(getSchema("./data/static_data/static_data.xsd"));
            List<SpawnGroup> newTemplates = new ArrayList<SpawnGroup>();
            for (File file : listFiles(dir, true)) {
                SpawnsData data = (SpawnsData) un.unmarshal(file);
                if (data != null && data.getSpawnGroups() != null)
                    newTemplates.addAll(data.getSpawnGroups());
            }
            DataManager.SPAWNS_DATA.setSpawns(newTemplates);
        } catch (Exception e) {
            PacketSendUtility.sendMessage(admin, "Spawns reload failed!");
            log.error(e);
        } finally {
            PacketSendUtility.sendMessage(admin, "Spawns reloaded successfuly!");
        }
    } else if (params[0].equals("admcmd")) {
        ChatHandlers.getInstance().reloadChatHandlers();
        PacketSendUtility.sendMessage(admin, "Admin commands reloaded successfully!");
    } else
        PacketSendUtility.sendMessage(admin, "syntax //reload <quest | skill | portal | spawn | admcmd>");
}

From source file:esg.node.components.registry.ShardsListGleaner.java

public synchronized ShardsListGleaner loadMyShardsWhitelist() {
    log.info("Loading my SHARDS Whitelist info from " + shardsListPath + shardsListFile);
    try {//w w w.j  a  va 2  s  . c  o  m
        JAXBContext jc = JAXBContext.newInstance(Shards.class);
        Unmarshaller u = jc.createUnmarshaller();
        JAXBElement<Shards> root = u.unmarshal(new StreamSource(new File(shardsListPath + shardsListFile)),
                Shards.class);
        shardlist = root.getValue();
    } catch (Exception e) {
        log.error(e);
    }
    return this;
}

From source file:org.openmrs.module.dhisreport.web.controller.LocationMappingController.java

public Metadata getDHIS2OrganizationUnits() throws Exception {
    String username = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2UserName");
    String password = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2Password");
    String dhisurl = Context.getAdministrationService().getGlobalProperty("dhisreport.dhis2URL");
    String url = dhisurl + "/api/organisationUnits.xml?fields=name,code&paging=false";
    // String url = "https://play.dhis2.org/demo/api/dataSets";
    // String referer = webRequest.getHeader( "Referer" );

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(url);
    getRequest.addHeader("accept", "application/xml");
    getRequest.addHeader(//from  w  ww. j ava 2  s.c  om
            BasicScheme.authenticate(new UsernamePasswordCredentials(username, password), "UTF-8", false));
    HttpResponse response;
    InputStream is = null;
    Metadata metadata = null;
    try {
        response = httpClient.execute(getRequest);
        is = response.getEntity().getContent();
        // String result = getStringFromInputStream( is );
        // System.out.println( result + "\n" );
        JAXBContext jaxbContext = JAXBContext.newInstance(Metadata.class);
        javax.xml.bind.Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        metadata = (Metadata) jaxbUnmarshaller.unmarshal(is);

        return metadata;
    } catch (ClientProtocolException e) {
        log.debug("ClientProtocolException occured : " + e.toString());
        e.printStackTrace();
    } finally {
        is.close();
    }
    return metadata;

}

From source file:esg.node.components.registry.ShardsListGleaner.java

public Shards createShardsWhitelistFromString(String shardsListContentString) {
    log.info("Loading my SHARDS info from \n" + shardsListContentString + "\n");
    Shards fromContentShardsList = null;
    try {/*from w w  w  . ja v  a2s. c  o m*/
        JAXBContext jc = JAXBContext.newInstance(Shards.class);
        Unmarshaller u = jc.createUnmarshaller();
        JAXBElement<Shards> root = u.unmarshal(new StreamSource(new StringReader(shardsListContentString)),
                Shards.class);
        fromContentShardsList = root.getValue();
    } catch (Exception e) {
        log.error(e);
    }
    return fromContentShardsList;
}

From source file:com.mgmtp.perfload.loadprofiles.ui.ctrl.ConfigController.java

public void loadActiveSettings() {
    checkState(activeSettingsFile != null, "No active settings file set.");

    Reader r = null;//from   w  ww  .  jav a 2s.co  m
    File file = new File(settingsDir, activeSettingsFile);
    try {
        r = new InputStreamReader(new FileInputStream(file), "UTF-8");
        JAXBContext context = JAXBContext.newInstance(Settings.class);
        Unmarshaller m = context.createUnmarshaller();
        activeSettings = (Settings) m.unmarshal(r);
    } catch (JAXBException ex) {
        String msg = "Error unmarshalling contents from file: " + file;
        throw new LoadProfileException(msg, ex);
    } catch (IOException ex) {
        throw new LoadProfileException(ex.getMessage(), ex);
    } finally {
        Closeables.closeQuietly(r);
    }
}

From source file:com.evolveum.midpoint.web.application.DescriptorLoader.java

public void loadData(MidPointApplication application) {
    LOGGER.info("Loading data from descriptor files.");

    String baseFileName = "/WEB-INF/descriptor.xml";
    String customFileName = "/WEB-INF/classes/descriptor.xml";

    try (InputStream baseInput = application.getServletContext().getResourceAsStream(baseFileName);
            InputStream customInput = application.getServletContext().getResourceAsStream(customFileName)) {
        if (baseInput == null) {
            LOGGER.error(// w  w w . j  av a2 s.com
                    "Couldn't find " + baseFileName + " file, can't load application menu and other stuff.");
        }

        JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        JAXBElement<DescriptorType> element = (JAXBElement) unmarshaller.unmarshal(baseInput);
        DescriptorType descriptor = element.getValue();

        LOGGER.debug("Loading menu bar from " + baseFileName + " .");
        MenuType menu = descriptor.getMenu();
        Map<Integer, RootMenuItemType> rootMenuItems = new HashMap<>();
        mergeRootMenuItems(menu, rootMenuItems);

        DescriptorType customDescriptor = null;
        if (customInput != null) {
            element = (JAXBElement) unmarshaller.unmarshal(customInput);
            customDescriptor = element.getValue();
            mergeRootMenuItems(customDescriptor.getMenu(), rootMenuItems);
        }

        List<RootMenuItemType> sortedRootMenuItems = sortRootMenuItems(rootMenuItems);
        loadMenuBar(sortedRootMenuItems);

        scanPackagesForPages(descriptor.getPackagesToScan(), application);
        if (customDescriptor != null) {
            scanPackagesForPages(customDescriptor.getPackagesToScan(), application);
        }
    } catch (Exception ex) {
        LoggingUtils.logException(LOGGER, "Couldn't process application descriptor", ex);
    }
}