Example usage for com.fasterxml.jackson.core JsonEncoding UTF8

List of usage examples for com.fasterxml.jackson.core JsonEncoding UTF8

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonEncoding UTF8.

Prototype

JsonEncoding UTF8

To view the source code for com.fasterxml.jackson.core JsonEncoding UTF8.

Click Source Link

Usage

From source file:com.bazaarvoice.jackson.rison.RisonFactory.java

@Deprecated
@Override/* w  ww .j av  a2  s.c o m*/
protected RisonGenerator _createUTF8JsonGenerator(OutputStream out, IOContext ctxt) throws IOException {
    return _createJsonGenerator(_createWriter(out, JsonEncoding.UTF8, ctxt), ctxt);
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.TelekomSMSTokenProvider.java

@Override
protected void sendSMS(String text, String recipientNumber) {
    recipientNumber = recipientNumber.replaceAll("^00", "\\+");

    try {// w ww .  jav  a 2s .c om
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JsonFactory jsonFactory = new JsonFactory();
        JsonGenerator jg = jsonFactory.createGenerator(baos, JsonEncoding.UTF8);

        jg.writeStartObject();
        jg.writeObjectFieldStart("outboundSMSMessageRequest");
        jg.writeArrayFieldStart("address");
        jg.writeString("tel:" + recipientNumber);
        jg.writeEndArray();
        jg.writeStringField("senderAddress", senderAddress);
        jg.writeObjectFieldStart("outboundSMSTextMessage");
        jg.writeStringField("message", text);
        jg.writeEndObject();
        jg.writeStringField("outboundEncoding", "7bitGSM");
        jg.writeStringField("clientCorrelator", "" + ((long) (Math.random() * Long.MAX_VALUE)));
        if (senderName != null)
            jg.writeStringField("senderName", senderName);
        jg.writeEndObject();
        jg.writeEndObject();

        jg.close();

        Exchange exc = new Request.Builder()
                .post("https://gateway.developer.telekom.com/plone/sms/rest/"
                        + environment.name().toLowerCase() + "/smsmessaging/v1/outbound/"
                        + URLEncoder.encode(senderAddress, "UTF-8") + "/requests")
                .header("Host", "gateway.developer.telekom.com")
                .header("Authorization",
                        "OAuth realm=\"developergarden.com\",oauth_token=\"" + getAccessToken() + "\"")
                .header("Accept", "application/json").header("Content-Type", "application/json")
                .body(baos.toByteArray()).buildExchange();

        exc.setRule(new NullRule() {
            @Override
            public SSLProvider getSslOutboundContext() {
                return new SSLContext(new SSLParser(), new ResolverMap(), null);
            }
        });
        hc.call(exc, false, true);

        if (exc.getResponse().getStatusCode() != 201)
            throw new RuntimeException("Could not send SMS: " + exc.getResponse());

        log.debug("sent SMS to " + recipientNumber);
    } catch (Exception e2) {
        throw new RuntimeException(e2);
    }
}

From source file:com.meetingninja.csse.database.MeetingDatabaseAdapter.java

public static Meeting createMeeting(String userID, Meeting m) throws IOException, MalformedURLException {
    // Server URL setup
    String _url = getBaseUri().appendPath(userID).build().toString();

    // establish connection
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("POST");
    addRequestHeader(conn, true);/*w ww.  j  ava  2 s.  co  m*/

    // prepare POST payload
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);

    // Build JSON Object
    jgen.writeStartObject();
    jgen.writeStringField(Keys.User.ID, userID);
    jgen.writeStringField(Keys.Meeting.TITLE, m.getTitle());
    jgen.writeStringField(Keys.Meeting.LOCATION, m.getLocation());
    jgen.writeStringField(Keys.Meeting.DATETIME, m.getStartTime());
    jgen.writeStringField(Keys.Meeting.OTHEREND, m.getEndTime());
    jgen.writeStringField(Keys.Meeting.DESC, m.getDescription());
    jgen.writeArrayFieldStart(Keys.Meeting.ATTEND);
    // TODO: Add attendees to meeting
    // for (String attendee : m.getAttendance()) {
    // if (attendee.isAttending()) {
    jgen.writeStartObject();
    jgen.writeStringField(Keys.User.ID, userID);
    jgen.writeEndObject();
    // }
    // }
    jgen.writeEndArray();
    jgen.writeEndObject();
    jgen.close();

    // Get JSON Object payload from print stream
    String payload = json.toString("UTF8");
    ps.close();

    // send payload
    int responseCode = sendPostPayload(conn, payload);
    String response = getServerResponse(conn);

    // prepare to get the id of the created Meeting
    JsonNode responseMap;
    m.setID(404);
    Meeting created = new Meeting(m);
    /*
     * result should get valid={"meetingID":"##"}
     */
    //      String result = new String();
    if (!response.isEmpty()) {
        responseMap = MAPPER.readTree(response);
        if (responseMap.has(Keys.Meeting.ID))
            created.setID(responseMap.get(Keys.Meeting.ID).asText());
    }

    //      if (!result.equalsIgnoreCase("invalid"))
    //         created.setID(result);

    conn.disconnect();
    return created;
}

From source file:io.protostuff.JsonIOUtil.java

/**
 * Creates a {@link UTF8JsonGenerator} for the outputstream with the supplied buf {@code outBuffer} to use.
 *///from  w w  w . ja  va  2s .c o m
static UTF8JsonGenerator newJsonGenerator(OutputStream out, byte[] buf, int offset, boolean bufferRecyclable,
        IOContext context) {
    context.setEncoding(JsonEncoding.UTF8);

    return new UTF8JsonGenerator(context, DEFAULT_JSON_FACTORY.getGeneratorFeatures(),
            DEFAULT_JSON_FACTORY.getCodec(), out, buf, offset, bufferRecyclable);
}

From source file:com.meetingninja.csse.database.TaskDatabaseAdapter.java

private static String getEditPayload(String taskID, String field, String value) throws IOException {
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Title
    jgen.writeStartObject();/*from   w  w  w  .j  a va2 s  .co  m*/
    jgen.writeStringField(Keys.Task.ID, taskID);
    jgen.writeStringField("field", field);
    jgen.writeStringField("value", value);
    jgen.writeEndObject();
    jgen.close();
    String payload = json.toString("UTF8");
    ps.close();
    return payload;
}

From source file:com.proofpoint.jaxrs.JsonMapper.java

@Override
public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream)
        throws IOException {
    // Prevent broken browser from attempting to render the json as html
    httpHeaders.add(HttpHeaders.X_CONTENT_TYPE_OPTIONS, "nosniff");

    JsonFactory jsonFactory = objectMapper.getFactory();
    jsonFactory.setCharacterEscapes(HTMLCharacterEscapes.INSTANCE);

    JsonGenerator jsonGenerator = jsonFactory.createGenerator(outputStream, JsonEncoding.UTF8);

    // Important: we are NOT to close the underlying stream after
    // mapping, so we need to instruct generator:
    jsonGenerator.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);

    // Pretty print?
    if (isPrettyPrintRequested()) {
        jsonGenerator.useDefaultPrettyPrinter();
    }// ww w . j  ava2 s  .co  m

    // 04-Mar-2010, tatu: How about type we were given? (if any)
    JavaType rootType = null;
    if (genericType != null && value != null) {
        // 10-Jan-2011, tatu: as per [JACKSON-456], it's not safe to just force root
        //    type since it prevents polymorphic type serialization. Since we really
        //    just need this for generics, let's only use generic type if it's truly
        //    generic.
        if (genericType.getClass() != Class.class) { // generic types are other implementations of 'java.lang.reflect.Type'
            // This is still not exactly right; should root type be further
            // specialized with 'value.getClass()'? Let's see how well this works before
            // trying to come up with more complete solution.
            rootType = objectMapper.getTypeFactory().constructType(genericType);
            // 26-Feb-2011, tatu: To help with [JACKSON-518], we better recognize cases where
            //    type degenerates back into "Object.class" (as is the case with plain TypeVariable,
            //    for example), and not use that.
            //
            if (rootType.getRawClass() == Object.class) {
                rootType = null;
            }
        }
    }

    ObjectWriter writer;
    if (rootType != null) {
        writer = objectMapper.writerWithType(rootType);
    } else {
        writer = objectMapper.writer();
    }

    writer.writeValue(jsonGenerator, value);

    // add a newline so when you use curl it looks nice
    outputStream.write('\n');
}

From source file:net.floodlightcontroller.configuration.ConfigurationManager.java

@Override
public String showConfiguration(String fileName) {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode rootNode = createJsonRootNode();
    JsonFactory f = new JsonFactory();
    OutputStream out = new ByteArrayOutputStream();
    JsonGenerator g = null;/*from  w ww  . ja v  a  2s.  c om*/
    try {
        g = f.createGenerator(out, JsonEncoding.UTF8);
        g.useDefaultPrettyPrinter();
        mapper.writeTree(g, rootNode);
    } catch (IOException e) {
        return "Error: Could not parse the JSON configuration file.";
    }
    return out.toString();
}

From source file:uk.gov.gchq.gaffer.jsonserialisation.JSONSerialiser.java

/**
 * Serialises an object./*from ww w .  j av  a2  s . com*/
 *
 * @param object          the object to be serialised
 * @param prettyPrint     true if the object should be serialised with pretty printing
 * @param fieldsToExclude optional property names to exclude from the json
 * @return the provided object serialised (with pretty printing) into bytes
 * @throws SerialisationException if the object fails to serialise
 */
public byte[] serialise(final Object object, final boolean prettyPrint, final String... fieldsToExclude)
        throws SerialisationException {
    final ByteArrayBuilder byteArrayBuilder = new ByteArrayBuilder();
    try {
        serialise(object, JSON_FACTORY.createGenerator(byteArrayBuilder, JsonEncoding.UTF8), prettyPrint,
                fieldsToExclude);
    } catch (final IOException e) {
        throw new SerialisationException(e.getMessage(), e);
    }

    return byteArrayBuilder.toByteArray();
}

From source file:com.meetingninja.csse.database.NotesDatabaseAdapter.java

private static String getEditPayload(String noteID, String field, String value) throws IOException {
    ByteArrayOutputStream json = new ByteArrayOutputStream();
    // this type of print stream allows us to get a string easily
    PrintStream ps = new PrintStream(json);
    // Create a generator to build the JSON string
    JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8);
    // Build JSON Object for Title
    jgen.writeStartObject();//w  w  w  .  j a  va 2 s. c  o  m
    jgen.writeStringField(Keys.Note.ID, noteID);
    jgen.writeStringField("field", field);
    jgen.writeStringField("value", value);
    jgen.writeEndObject();
    jgen.close();
    String payload = json.toString("UTF8");
    ps.close();
    Log.d("updatenotepayload", payload);
    return payload;
}

From source file:com.sdl.odata.renderer.json.writer.JsonWriter.java

/**
 * Write the given data to the JSON stream. The data to write will be either a single entity or a feed depending on
 * whether it is a single object or list.
 *
 * @param data The given data./* w w  w.  ja  va2 s.  c o  m*/
 * @param meta Additional values to write.
 * @return The written JSON stream.
 * @throws ODataRenderException if unable to render
 */
private String writeJson(Object data, Map<String, Object> meta) throws IOException, NoSuchFieldException,
        IllegalAccessException, ODataEdmException, ODataRenderException {

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    jsonGenerator = JSON_FACTORY.createGenerator(stream, JsonEncoding.UTF8);

    jsonGenerator.writeStartObject();

    // Write @odata constants
    entitySet = (data instanceof List) ? getEntitySet((List<?>) data) : getEntitySet(data);

    jsonGenerator.writeStringField(CONTEXT, contextURL);

    // Write @odata.count if requested and provided.
    if (hasCountOption(odataUri) && data instanceof List && meta != null && meta.containsKey("count")) {

        long count;
        Object countObj = meta.get("count");
        if (countObj instanceof Integer) {
            count = ((Integer) countObj).longValue();
        } else {
            count = (long) countObj;
        }
        jsonGenerator.writeNumberField(COUNT, count);
    }

    if (!(data instanceof List)) {
        if (entitySet != null) {
            jsonGenerator.writeStringField(ID, String.format("%s(%s)", getEntityName(entityDataModel, data),
                    formatEntityKey(entityDataModel, data)));
        } else {
            jsonGenerator.writeStringField(ID, String.format("%s", getEntityName(entityDataModel, data)));
        }
    }

    // Write feed
    if (data instanceof List) {
        marshallEntities((List<?>) data);
    } else {
        marshall(data, this.entityDataModel.getType(data.getClass()));
    }

    jsonGenerator.writeEndObject();
    jsonGenerator.close();

    return stream.toString(StandardCharsets.UTF_8.name());
}