Example usage for com.fasterxml.jackson.dataformat.xml XmlMapper XmlMapper

List of usage examples for com.fasterxml.jackson.dataformat.xml XmlMapper XmlMapper

Introduction

In this page you can find the example usage for com.fasterxml.jackson.dataformat.xml XmlMapper XmlMapper.

Prototype

public XmlMapper() 

Source Link

Usage

From source file:com.ning.billing.recurly.model.TestXmlMapper.java

@Test(groups = "fast", description = "See https://github.com/FasterXML/jackson-dataformat-xml/issues/76")
public void testCollection() throws Exception {
    final XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.setSerializerProvider(new RecurlyXmlSerializerProvider());
    final SimpleModule m = new SimpleModule("module", new Version(1, 0, 0, null, null, null));
    m.addSerializer(Values.class, new ValuesSerializer());
    xmlMapper.registerModule(m);//from  w w w. j a  v a 2  s  . c  om

    final Values values = xmlMapper
            .readValue(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "  <values type=\"array\">\n"
                            + "    <value>Hi!</value>" + "    <value>Salut!</value>" + "  </values>",
                    Values.class);
    Assert.assertEquals(values.size(), 2, values.toString());
    Assert.assertEquals(values.get(0), "Hi!");
    Assert.assertEquals(values.get(1), "Salut!");

    // Test we can re-serialize
    final String valueAsString = xmlMapper.writeValueAsString(values);
    final Values values2 = xmlMapper.readValue(valueAsString, Values.class);
    Assert.assertEquals(values2, values, valueAsString);
}

From source file:com.omertron.bgg.BggApi.java

/**
 * BoardGameGeek API wrapper./*from  w  w w.  j  ava 2s  . co m*/
 *
 * @param httpClient Use the supplied HttpClient for web access
 */
public BggApi(HttpClient httpClient) {
    httpTools = new HttpTools(httpClient);
    mapper = new XmlMapper();
}

From source file:net.maurerit.zkb.KillParser.java

public List<Kill> parse(InputStream is, boolean isXml) throws IOException {
    List<Kill> kills = new ArrayList<Kill>();

    ObjectMapper mapper;//from ww  w.j av  a 2 s.c  o m
    if (isXml) {
        mapper = new XmlMapper();
    } else {
        mapper = new ObjectMapper();
    }

    TreeNode root = mapper.readTree(is);

    if (root instanceof ArrayNode) {
        ArrayNode rootCasted = (ArrayNode) root;
        for (int idx = 0; idx < rootCasted.size(); idx++) {
            kills.add(parseKill(rootCasted.get(idx)));
        }
    }

    return kills;
}

From source file:org.apache.olingo.fit.CXFOAuth2HttpClientFactory.java

@Override
protected void init() throws OAuth2Exception {
    final URI authURI = OAuthClientUtils.getAuthorizationURI(oauth2GrantServiceURI.toASCIIString(),
            OAuth2Provider.CLIENT_ID, OAuth2Provider.REDIRECT_URI, null, null);

    // Disable automatic redirects handling
    final HttpParams params = new BasicHttpParams();
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    final DefaultHttpClient httpClient = new DefaultHttpClient(params);

    JsonNode oAuthAuthorizationData = null;
    String authenticityCookie = null;
    try {/*from ww  w  .jav  a  2  s  . c  o  m*/
        // 1. Need to (basic) authenticate against the OAuth2 service
        final HttpGet method = new HttpGet(authURI);
        method.addHeader("Authorization",
                "Basic " + Base64.encodeBase64String("odatajclient:odatajclient".getBytes()));
        final HttpResponse response = httpClient.execute(method);

        // 2. Pull out OAuth2 authorization data and "authenticity" cookie (CXF specific)
        oAuthAuthorizationData = new XmlMapper().readTree(EntityUtils.toString(response.getEntity()));

        final Header setCookieHeader = response.getFirstHeader("Set-Cookie");
        if (setCookieHeader == null) {
            throw new IllegalStateException("OAuth flow is broken");
        }
        authenticityCookie = setCookieHeader.getValue();
    } catch (Exception e) {
        throw new OAuth2Exception(e);
    }

    String code = null;
    try {
        // 3. Submit the HTTP form for allowing access to the application
        final URI location = new URIBuilder(oAuthAuthorizationData.get("replyTo").asText())
                .addParameter("session_authenticity_token",
                        oAuthAuthorizationData.get("authenticityToken").asText())
                .addParameter("client_id", oAuthAuthorizationData.get("clientId").asText())
                .addParameter("redirect_uri", oAuthAuthorizationData.get("redirectUri").asText())
                .addParameter("oauthDecision", "allow").build();
        final HttpGet method = new HttpGet(location);
        method.addHeader("Authorization",
                "Basic " + Base64.encodeBase64String("odatajclient:odatajclient".getBytes()));
        method.addHeader("Cookie", authenticityCookie);

        final HttpResponse response = httpClient.execute(method);

        final Header locationHeader = response.getFirstHeader("Location");
        if (response.getStatusLine().getStatusCode() != 303 || locationHeader == null) {
            throw new IllegalStateException("OAuth flow is broken");
        }

        // 4. Get the authorization code value out of this last redirect
        code = StringUtils.substringAfterLast(locationHeader.getValue(), "=");

        EntityUtils.consumeQuietly(response.getEntity());
    } catch (Exception e) {
        throw new OAuth2Exception(e);
    }

    // 5. Obtain the access token
    try {
        accessToken = OAuthClientUtils.getAccessToken(getAccessTokenService(), OAUTH2_CONSUMER,
                new AuthorizationCodeGrant(code));
    } catch (OAuthServiceException e) {
        throw new OAuth2Exception(e);
    }

    if (accessToken == null) {
        throw new OAuth2Exception("No OAuth2 access token");
    }
}

From source file:nl.esciencecenter.medim.dicom.DicomProcessingProfile.java

public static DicomProcessingProfile parseXML(String xml)
        throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper xmlMapper = new XmlMapper();
    DicomProcessingProfile value = xmlMapper.readValue(xml, DicomProcessingProfile.class);
    // check ?/* ww  w . j a v a 2s .  co m*/
    return value;
}

From source file:com.blockwithme.lessobjects.util.JSONParser.java

/**
 * To json string.//  ww  w .  j av  a 2  s .  co m
 *
 * @return the string
 */
@SuppressWarnings("null")
public String toJSONString() {

    if (jsonString == null) {
        if (fromSchema) {
            try {
                final ObjectWriter writer = initMapper();
                jsonString = writer.writeValueAsString(schema);
            } catch (final JsonProcessingException jpe) {
                throw new IllegalStateException(jpe.getMessage(), jpe);
            }
        } else {
            try {
                if (format == SchemaFormat.JSON) {
                    jsonString = jsonOrXMLString;
                } else {
                    if (xmlString == null) {
                        xmlString = jsonOrXMLString;
                    }
                    final XmlMapper xmlMapper = new XmlMapper();
                    schema = xmlMapper.readValue(jsonOrXMLString, StructSchema.class);
                    final ObjectMapper jsonMapper = new ObjectMapper();
                    jsonString = jsonMapper.writeValueAsString(schema);
                }
            } catch (final IOException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
        }
    }
    return jsonString;
}

From source file:com.blockwithme.lessobjects.util.JSONParser.java

/**
 * To xml string./* www  . j  a  va2  s.  com*/
 *
 * @return the string
 */
@SuppressWarnings("null")
public String toXMLString() {

    if (xmlString == null) {
        if (!fromSchema) {
            try {
                final XmlMapper mapper = new XmlMapper();
                xmlString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
            } catch (final JsonProcessingException jpe) {
                throw new IllegalStateException(jpe.getMessage(), jpe);
            }
        } else {
            try {
                if (format == SchemaFormat.JSON) {
                    if (jsonString == null) {
                        jsonString = jsonOrXMLString;
                    }
                    schema = getBinding();
                    xmlString = new XmlMapper().writerWithDefaultPrettyPrinter().writeValueAsString(schema);
                } else {
                    xmlString = jsonOrXMLString;
                }
            } catch (final IOException e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
        }
    }
    return xmlString;
}

From source file:uk.ac.kcl.Transform23.java

public static String convertHL7ToJson(Message message) {
    try {/*from ww w .  j av a2s .c  om*/
        DefaultXMLParser xmlParser = new DefaultXMLParser(new CanonicalModelClassFactory("2.4"));
        Document xml = xmlParser.encodeDocument(message);
        cleanFieldNames(xml.getChildNodes().item(0));
        XmlMapper xmlMapper = new XmlMapper();
        List entries = null;
        try {
            entries = xmlMapper.readValue(getStringFromDocument(xml), List.class);
        } catch (IOException | TransformerException ex) {
            Logger.getLogger(Transform23.class.getName()).log(Level.SEVERE, null, ex);
        }

        ObjectMapper jsonMapper = new ObjectMapper();

        String json = null;
        try {
            json = jsonMapper.writeValueAsString(entries);
        } catch (IOException ex) {
            Logger.getLogger(Transform23.class.getName()).log(Level.SEVERE, null, ex);
        }

        //System.out.println(json);
        json = json.substring(1, (json.length() - 1));
        //to do  - add code to rename fields, removing periods

        return json;
    } catch (HL7Exception ex) {
        Logger.getLogger(Transform23.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:uk.ac.kcl.Transform231.java

public static String convertHL7ToJson(Message message) {
    try {/*from  w  ww. ja  v a 2s.com*/
        DefaultXMLParser xmlParser = new DefaultXMLParser(new CanonicalModelClassFactory("2.4"));
        Document xml = xmlParser.encodeDocument(message);
        cleanFieldNames(xml.getChildNodes().item(0));
        XmlMapper xmlMapper = new XmlMapper();
        List entries = null;
        try {
            entries = xmlMapper.readValue(getStringFromDocument(xml), List.class);
        } catch (IOException | TransformerException ex) {
            Logger.getLogger(Transform231.class.getName()).log(Level.SEVERE, null, ex);
        }

        ObjectMapper jsonMapper = new ObjectMapper();

        String json = null;
        try {
            json = jsonMapper.writeValueAsString(entries);
        } catch (IOException ex) {
            Logger.getLogger(Transform231.class.getName()).log(Level.SEVERE, null, ex);
        }

        //System.out.println(json);
        json = json.substring(1, (json.length() - 1));
        //to do  - add code to rename fields, removing periods

        return json;
    } catch (HL7Exception ex) {
        Logger.getLogger(Transform231.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}