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.learnpad.core.impl.mv.XwikiBridgeInterfaceRestResource.java

@Override
public VerificationResults getVerificationResult(String verificationProcessId) throws LpRestException {

    HttpClient httpClient = this.getHttpClient();
    String uri = String.format("%s/learnpad/mv/bridge/getverificationresult", this.restPrefix);
    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader("Accept", "application/xml");

    NameValuePair[] queryString = new NameValuePair[1];
    queryString[0] = new NameValuePair("verificationprocessid", verificationProcessId);
    getMethod.setQueryString(queryString);

    try {/*  ww w . j a  v a 2 s.com*/
        httpClient.executeMethod(getMethod);
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
    VerificationResults verificationResults = null;

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(VerificationResults.class);
        InputStream retIs = getMethod.getResponseBodyAsStream();
        verificationResults = (VerificationResults) jaxbContext.createUnmarshaller().unmarshal(retIs);
    } catch (Exception e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }

    return verificationResults;
}

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

@Override
public VerificationsAvailable getAvailableVerifications() throws LpRestException {
    HttpClient httpClient = this.getHttpClient();
    String uri = String.format("%s/learnpad/mv/bridge/getavailableverifications", this.restPrefix);
    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader("Accept", "application/xml");

    try {/*from w w w  . j a  v  a 2 s.co m*/
        httpClient.executeMethod(getMethod);
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }

    VerificationsAvailable verificationsAvailable = null;
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(VerificationsAvailable.class);
        InputStream retIs = getMethod.getResponseBodyAsStream();
        verificationsAvailable = (VerificationsAvailable) jaxbContext.createUnmarshaller().unmarshal(retIs);
    } catch (Exception e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }

    return verificationsAvailable;
}

From source file:com.t2tierp.controller.nfe.CancelaNfe.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public Map cancelaNfe(String alias, KeyStore ks, char[] senha, String codigoUf, String ambiente,
        String chaveAcesso, String numeroProtocolo, String justificativa, String cnpj) throws Exception {
    String versaoDados = "1.00";
    String url = "";
    if (codigoUf.equals("53")) {
        if (ambiente.equals("1")) {
            url = "https://nfe.sefazvirtual.rs.gov.br/ws/recepcaoevento/recepcaoevento.asmx";
        } else if (ambiente.equals("2")) {
            url = "https://homologacao.nfe.sefazvirtual.rs.gov.br/ws/recepcaoevento/recepcaoevento.asmx";
        }/* ww w  .j a v a 2 s  .  co  m*/
    }
    /* fica a cargo de cada participante definir a url que ser utiizada de acordo com o cdigo da UF
     * URLs disponveis em:
     * Homologao: http://hom.nfe.fazenda.gov.br/PORTAL/WebServices.aspx
     * Produo: http://www.nfe.fazenda.gov.br/portal/WebServices.aspx
     */

    if (url.equals("")) {
        throw new Exception("URL da sefaz no definida para o cdigo de UF = " + codigoUf);
    }

    SimpleDateFormat formatoIso = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    String dataHoraEvento = formatoIso.format(new Date());

    String xmlCanc = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
            + "<envEvento xmlns=\"http://www.portalfiscal.inf.br/nfe\" versao=\"" + versaoDados + "\">"
            + "<idLote>1</idLote>" + "<evento versao=\"" + versaoDados + "\">" + "<infEvento Id=\"ID" + "110111"
            + chaveAcesso + "01\">" + "<cOrgao>" + codigoUf + "</cOrgao>" + "<tpAmb>" + ambiente + "</tpAmb>"
            + "<CNPJ>" + cnpj + "</CNPJ>" + "<chNFe>" + chaveAcesso + "</chNFe>" + "<dhEvento>" + dataHoraEvento
            + "</dhEvento>" + "<tpEvento>110111</tpEvento>" + "<nSeqEvento>1</nSeqEvento>" + "<verEvento>"
            + versaoDados + "</verEvento>" + "<detEvento versao=\"" + versaoDados + "\">"
            + "<descEvento>Cancelamento</descEvento>" + "<nProt>" + numeroProtocolo + "</nProt>" + "<xJust>"
            + justificativa + "</xJust>" + "</detEvento>" + "</infEvento>" + "</evento>" + "</envEvento>";

    xmlCanc = Biblioteca.assinaXML(xmlCanc, alias, ks, senha, "#ID110111" + chaveAcesso + "01", "evento",
            "infEvento", "Id");

    X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
    PrivateKey privatekey = (PrivateKey) ks.getKey(alias, senha);
    SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(certificate, privatekey);
    //arquivo que contm a cadeia de certificados do servio a ser consumido
    socketFactory.setFileCacerts(this.getClass().getResourceAsStream("/br/inf/portalfiscal/nfe/jssecacerts"));

    //define o protocolo a ser utilizado na conexo
    Protocol protocol = new Protocol("https", socketFactory, 443);
    Protocol.registerProtocol("https", protocol);

    OMElement omElement = AXIOMUtil.stringToOM(xmlCanc);

    RecepcaoEventoStub.NfeDadosMsg dadosMsg = new RecepcaoEventoStub.NfeDadosMsg();
    dadosMsg.setExtraElement(omElement);

    RecepcaoEventoStub.NfeCabecMsg cabecMsg = new RecepcaoEventoStub.NfeCabecMsg();
    cabecMsg.setCUF(codigoUf);
    cabecMsg.setVersaoDados(versaoDados);

    RecepcaoEventoStub.NfeCabecMsgE cabecMsgE = new RecepcaoEventoStub.NfeCabecMsgE();
    cabecMsgE.setNfeCabecMsg(cabecMsg);

    RecepcaoEventoStub stub = new RecepcaoEventoStub(url);

    RecepcaoEventoStub.NfeRecepcaoEventoResult result = stub.nfeRecepcaoEvento(dadosMsg, cabecMsgE);

    ByteArrayInputStream in = new ByteArrayInputStream(result.getExtraElement().toString().getBytes());

    JAXBContext jc = JAXBContext.newInstance("br.inf.portalfiscal.nfe.retevento");
    Unmarshaller unmarshaller = jc.createUnmarshaller();

    JAXBElement<br.inf.portalfiscal.nfe.retevento.TRetEnvEvento> retEvento = (JAXBElement) unmarshaller
            .unmarshal(in);

    Map map = new HashMap();
    if (retEvento.getValue().getRetEvento().get(0).getInfEvento().getCStat().equals("135")) {
        map.put("nfeCancelada", true);
        xmlCanc = xmlCancelamento(retEvento.getValue(), versaoDados, codigoUf, ambiente, chaveAcesso,
                numeroProtocolo, justificativa, cnpj, dataHoraEvento);
        xmlCanc = xmlCanc.replaceAll("xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\"", "");

        xmlCanc = Biblioteca.assinaXML(xmlCanc, alias, ks, senha, "#ID110111" + chaveAcesso + "01", "evento",
                "infEvento", "Id");
        map.put("xmlCancelamento", xmlCanc);
    } else {
        map.put("nfeCancelada", false);
    }
    map.put("motivo1", retEvento.getValue().getXMotivo());
    map.put("motivo2", retEvento.getValue().getRetEvento().get(0).getInfEvento().getXMotivo());

    return map;
}

From source file:eu.trentorise.smartcampus.permissionprovider.manager.AttributesAdapter.java

/**
 * Load attributes from the XML descriptor.
 * @throws JAXBException// w w w.j  ava 2s.c  o m
 */
protected void init() throws JAXBException {
    JAXBContext jaxb = JAXBContext.newInstance(AuthorityMapping.class, Authorities.class);
    Unmarshaller unm = jaxb.createUnmarshaller();
    JAXBElement<Authorities> element = (JAXBElement<Authorities>) unm
            .unmarshal(new StreamSource(getClass().getResourceAsStream("authorities.xml")), Authorities.class);
    Authorities auths = element.getValue();
    authorities = new HashMap<String, AuthorityMapping>();
    authorityMatches = ArrayListMultimap.create();//new HashMap<String, AuthorityMatching>();
    identityAttributes = new HashMap<String, Set<String>>();
    for (AuthorityMapping mapping : auths.getAuthorityMapping()) {
        Authority auth = authorityRepository.findOne(mapping.getName());
        if (auth == null) {
            auth = new Authority();
            auth.setName(mapping.getName());
            auth.setRedirectUrl(mapping.getUrl());
            authorityRepository.saveAndFlush(auth);
        }
        authorities.put(mapping.getName(), mapping);
        Set<String> identities = new HashSet<String>();
        if (mapping.getIdentifyingAttributes() != null) {
            identities.addAll(mapping.getIdentifyingAttributes());
        }
        identityAttributes.put(auth.getName(), identities);
    }
    if (auths.getAuthorityMatching() != null) {
        for (AuthorityMatching am : auths.getAuthorityMatching()) {
            for (Match match : am.getAuthority()) {
                authorityMatches.put(match.getName(), am);
            }
        }
    }
}

From source file:com.siberhus.geopoint.restclient.GeoPointRestClient.java

/**
 * /*ww w  .j a v a 2  s. c o  m*/
 * @param ipAddr
 * @param format
 * @return
 */
public IpInfo query(String ipAddr, Format format) {

    Assert.notNull("apiKey", apiKey);
    Assert.notNull("secret", secret);

    Assert.notNull("ipAddr", ipAddr);
    Assert.notNull("format", format);

    MessageDigest digest = null;

    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        // should not happen
        throw new RuntimeException(e);
    }

    String formatStr = format == Format.XML ? "xml" : "json";

    long timeInSeconds = (long) (System.currentTimeMillis() / 1000);

    String input = apiKey + secret + timeInSeconds;
    digest.update(input.getBytes());
    String signature = String.format("%032x", new BigInteger(1, digest.digest()));

    String url = serviceUrl + ipAddr + "?apikey=" + apiKey + "&sig=" + signature + "&format=" + formatStr;
    log.debug("Calling Quova ip2loc service from URL: {}", url);
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Create an HTTP GET request
    HttpGet httpget = new HttpGet(url);

    // Execute the request
    httpget.getRequestLine();
    HttpResponse response = null;
    try {
        response = httpclient.execute(httpget);
    } catch (IOException e) {
        throw new HttpRequestException(e);
    }

    HttpEntity entity = response.getEntity();
    StatusLine status = response.getStatusLine();
    if (status.getStatusCode() != 200) {
        throw new HttpRequestException(status.getReasonPhrase());
    }
    // Print the response
    log.debug("Response status: {}", status);

    StringBuilder responseText = new StringBuilder();
    if (entity != null) {
        try {
            InputStream inputStream = entity.getContent();
            // Process the response
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                responseText.append(line);
            }
            bufferedReader.close();
        } catch (IOException e) {
            throw new HttpRequestException(e);
        }
    }
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources.
    httpclient.getConnectionManager().shutdown();

    IpInfo ipInfo = null;
    if (format == Format.XML) {
        JAXBContext context;
        try {
            context = JAXBContext.newInstance(IpInfo.class);
            Unmarshaller um = context.createUnmarshaller();
            ipInfo = (IpInfo) um.unmarshal(new StringReader(responseText.toString()));
        } catch (JAXBException e) {
            throw new ResultParseException(e);
        }
    } else {

        ObjectMapper mapper = new ObjectMapper();
        try {
            ipInfo = mapper.readValue(new StringReader(responseText.toString()), IpInfoWrapper.class)
                    .getIpInfo();
        } catch (IOException e) {
            throw new ResultParseException(e);
        }
    }
    return ipInfo;
}

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

@Override
public AnnotatedCollaborativeContentAnalyses getCollaborativeContentVerifications(String contentID)
        throws LpRestException {
    HttpClient httpClient = this.getAnonymousClient();
    String uri = String.format("%s/learnpad/ca/bridge/validatecollaborativecontent/%s", this.restPrefix,
            contentID);//from   ww  w .j  av  a2  s. co  m
    GetMethod getMethod = new GetMethod(uri);

    try {
        httpClient.executeMethod(getMethod);

        AnnotatedCollaborativeContentAnalyses analysis = null;

        JAXBContext jaxbContext = JAXBContext.newInstance(AnnotatedCollaborativeContentAnalyses.class);
        InputStream retIs = getMethod.getResponseBodyAsStream();
        analysis = (AnnotatedCollaborativeContentAnalyses) jaxbContext.createUnmarshaller().unmarshal(retIs);
        return analysis;
    } catch (Exception e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
}

From source file:net.ageto.gyrex.impex.persistence.cassandra.storage.CassandraRepositoryImpl.java

/**
 * Find process by the given id.//ww  w.  j a  v  a  2s.  com
 * 
 * @param id
 * @return
 */
public IProcessConfig findProcessById(String id) {

    ColumnQuery<String, String, String> columnQuery = HFactory.createStringColumnQuery(getImpexKeyspace());
    columnQuery.setColumnFamily(columnFamilyProcesses).setKey(id).setName(columnNameProcess);
    QueryResult<HColumn<String, String>> result = columnQuery.execute();

    HColumn<String, String> column = result.get();

    IProcessConfig process = null;
    if (column != null) {
        try {
            JAXBContext context = JAXBContext.newInstance(ProcessConfig.class);
            Unmarshaller u = context.createUnmarshaller();

            StringReader reader = new StringReader(column.getValue());

            // create process from xml
            process = (ProcessConfig) u.unmarshal(reader);

        } catch (JAXBException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    return process;
}

From source file:eu.eco2clouds.scheduler.em.EMClientHC.java

@Override
public List<ManagedExperiment> listExperiments(String userId) {
    this.userId = userId;
    Boolean exception = false;//from   w  ww  .j a  v a2s. c  o  m
    String testbedsUrl = url;

    String response = getMethod(testbedsUrl, exception);

    List<ManagedExperiment> managedExperiments = new ArrayList<ManagedExperiment>();

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Collection.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Collection collection = (Collection) jaxbUnmarshaller.unmarshal(new StringReader(response));
        managedExperiments = collection.getItems().getManagedExperiments();
    } catch (JAXBException e) {
        logger.warn("Error trying to parse returned status of hosts: " + url + testbedsUrl + " Exception: "
                + e.getMessage());
        exception = true;
    }

    if (exception)
        return new ArrayList<ManagedExperiment>();
    return managedExperiments;
}

From source file:org.motechproject.mobile.web.ivr.intellivr.IntellIVRController.java

public void init() {
    Resource schemaResource = resourceLoader.getResource("classpath:intellivr-in.xsd");
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    try {//from ww w .  j  av a  2s  .c om
        Schema schema = factory.newSchema(schemaResource.getFile());
        parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        validator = schema.newValidator();
    } catch (SAXException e) {
        log.error("Error initializing controller:", e);
    } catch (IOException e) {
        log.error("Error initializing controller:", e);
    } catch (ParserConfigurationException e) {
        log.error("Error initializing controller:", e);
    } catch (FactoryConfigurationError e) {
        log.error("Error initializing controller:", e);
    }
    try {
        JAXBContext jaxbc = JAXBContext.newInstance("org.motechproject.mobile.omp.manager.intellivr");
        marshaller = jaxbc.createMarshaller();
        unmarshaller = jaxbc.createUnmarshaller();
    } catch (JAXBException e) {
        log.error("Error initializing controller:", e);
    }
}