Search in sources :

Example 61 with JsonFactory

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonFactory in project service-proxy by membrane.

the class JSONBody method write.

@Override
public void write(XMLStreamWriter out) throws XMLStreamException {
    out.writeAttribute("type", "json");
    try {
        final JsonFactory jsonFactory = new JsonFactory();
        final JsonParser jp = jsonFactory.createParser(new InputStreamReader(msg.getBodyAsStreamDecoded(), msg.getCharset()));
        final List<String> stack = new ArrayList<String>();
        String name = "root";
        OUTER: while (jp.nextToken() != null) {
            switch(jp.getCurrentToken()) {
                case START_OBJECT:
                    if (name != null) {
                        stack.add(name);
                        out.writeStartElement(name);
                        out.writeAttribute("type", "o");
                        name = null;
                    }
                    break;
                case END_OBJECT:
                    out.writeEndElement();
                    name = stack.remove(stack.size() - 1);
                    if (stack.isEmpty())
                        break OUTER;
                    break;
                case FIELD_NAME:
                    name = jp.getCurrentName();
                    break;
                case START_ARRAY:
                    if (name != null) {
                        stack.add(name);
                        out.writeStartElement(name);
                        out.writeAttribute("type", "a");
                    }
                    name = "item";
                    break;
                case END_ARRAY:
                    out.writeEndElement();
                    name = stack.remove(stack.size() - 1);
                    if (stack.isEmpty())
                        break OUTER;
                    break;
                case VALUE_TRUE:
                case VALUE_FALSE:
                    out.writeStartElement(name);
                    out.writeAttribute("type", "b");
                    out.writeCharacters(Boolean.toString(jp.getBooleanValue()));
                    out.writeEndElement();
                    break;
                case VALUE_NULL:
                    out.writeStartElement(name);
                    out.writeAttribute("type", "n");
                    out.writeAttribute("isNull", "true");
                    out.writeEndElement();
                    break;
                case VALUE_STRING:
                case VALUE_NUMBER_INT:
                case VALUE_NUMBER_FLOAT:
                    out.writeStartElement(name);
                    out.writeAttribute("type", jp.getCurrentToken() == JsonToken.VALUE_STRING ? "s" : jp.getCurrentToken() == JsonToken.VALUE_NUMBER_INT ? "i" : "f");
                    out.writeCharacters(jp.getText());
                    out.writeEndElement();
                    break;
                case VALUE_EMBEDDED_OBJECT:
                case NOT_AVAILABLE:
                    throw new RuntimeException(jp.getCurrentToken().toString());
            }
        }
    } catch (JsonParseException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) JsonFactory(com.fasterxml.jackson.core.JsonFactory) ArrayList(java.util.ArrayList) IOException(java.io.IOException) JsonParseException(com.fasterxml.jackson.core.JsonParseException) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 62 with JsonFactory

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonFactory in project service-proxy by membrane.

the class JSONValidator method validateMessage.

public Outcome validateMessage(Exchange exc, InputStream body, Charset charset, String source) throws Exception {
    List<String> errors;
    boolean success = true;
    try {
        JsonNode node = JsonLoader.fromReader(new InputStreamReader(body, charset));
        ProcessingReport report = schema.validateUnchecked(node);
        success = report.isSuccess();
        errors = new ArrayList<String>();
        for (ProcessingMessage message : report) errors.add(message.getMessage());
    } catch (JsonParseException e) {
        success = false;
        errors = new ArrayList<String>();
        errors.add(e.getMessage());
    }
    if (success) {
        valid.incrementAndGet();
        return Outcome.CONTINUE;
    }
    if (failureHandler == FailureHandler.VOID) {
        StringBuilder message = new StringBuilder();
        message.append(source);
        message.append(": ");
        for (String error : errors) {
            message.append(error);
            message.append(";");
        }
        exc.setProperty("error", message.toString());
        invalid.incrementAndGet();
        return Outcome.ABORT;
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JsonGenerator jg = new JsonFactory().createGenerator(baos);
    jg.writeStartObject();
    jg.writeStringField("source", source);
    jg.writeArrayFieldStart("errors");
    for (String message : errors) jg.writeString(message);
    jg.close();
    if (failureHandler != null) {
        failureHandler.handleFailure(new String(baos.toByteArray(), UTF8), exc);
        exc.setResponse(Response.badRequest().contentType("application/json;charset=utf-8").body("{\"error\":\"error\"}".getBytes(UTF8)).build());
    } else {
        exc.setResponse(Response.badRequest().contentType("application/json;charset=utf-8").body(baos.toByteArray()).build());
    }
    invalid.incrementAndGet();
    return Outcome.ABORT;
}
Also used : InputStreamReader(java.io.InputStreamReader) ProcessingMessage(com.github.fge.jsonschema.core.report.ProcessingMessage) ArrayList(java.util.ArrayList) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonNode(com.fasterxml.jackson.databind.JsonNode) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JsonParseException(com.fasterxml.jackson.core.JsonParseException) ProcessingReport(com.github.fge.jsonschema.core.report.ProcessingReport) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator)

Example 63 with JsonFactory

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonFactory in project service-proxy by membrane.

the class AMQuota method setResponseToServiceUnavailable.

private void setResponseToServiceUnavailable(Exchange exc, PolicyQuota pq) {
    // TODO do a better response here
    Header hd = new Header();
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonGenerator jgen = null;
    try {
        jgen = new JsonFactory().createGenerator(os);
        jgen.writeStartObject();
        jgen.writeObjectField("Statuscode", 429);
        jgen.writeObjectField("Message", "Quota Exceeded");
        jgen.writeEndObject();
        jgen.close();
    } catch (IOException ignored) {
    }
    Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd).contentType("application/json").body(os.toByteArray()).build();
    exc.setResponse(resp);
}
Also used : Response(com.predic8.membrane.core.http.Response) Header(com.predic8.membrane.core.http.Header) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DateTimeFormatter(org.joda.time.format.DateTimeFormatter)

Example 64 with JsonFactory

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonFactory in project service-proxy by membrane.

the class AMRateLimiter method setResponseToServiceUnavailable.

public void setResponseToServiceUnavailable(Exchange exc, PolicyRateLimit prl) throws UnsupportedEncodingException {
    Header hd = new Header();
    DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'").withZoneUTC().withLocale(Locale.US);
    hd.add("Date", dateFormatter.print(DateTime.now()));
    hd.add("X-LimitDuration", PeriodFormat.getDefault().print(prl.getInterval().toPeriod()));
    hd.add("X-LimitRequests", Integer.toString(prl.getRequests()));
    String ip = exc.getRemoteAddrIp();
    DateTime availableAgainDateTime = prl.getNextCleanup();
    hd.add("X-LimitReset", Long.toString(availableAgainDateTime.getMillis()));
    /*StringBuilder bodyString = new StringBuilder();
        DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
        bodyString.append(ip).append(" exceeded the rate limit of ").append(prl.getRequests())
                .append(" requests per ")
                .append(PeriodFormat.getDefault().print(prl.getInterval().toPeriod()))
                .append(". The next request can be made at ").append(dtFormatter.print(availableAgainDateTime));*/
    DateTimeFormatter dtFormatter = DateTimeFormat.forPattern("HH:mm:ss aa");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonGenerator jgen = null;
    try {
        jgen = new JsonFactory().createGenerator(os);
        jgen.writeStartObject();
        jgen.writeObjectField("Statuscode", 429);
        jgen.writeObjectField("Message", "The rate limit of " + prl.getRequests() + " requests in " + prl.getInterval().getStandardSeconds() + " seconds is exceeded. The next requests can be made at " + dtFormatter.print(availableAgainDateTime));
        jgen.writeEndObject();
        jgen.close();
    } catch (IOException ignored) {
    }
    Response resp = Response.ResponseBuilder.newInstance().status(429, "Too Many Requests.").header(hd).contentType("application/json").body(os.toByteArray()).build();
    exc.setResponse(resp);
}
Also used : Response(com.predic8.membrane.core.http.Response) Header(com.predic8.membrane.core.http.Header) JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) DateTime(org.joda.time.DateTime)

Example 65 with JsonFactory

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonFactory in project service-proxy by membrane.

the class ApiManagementInterceptor method buildJsonErrorMessage.

private byte[] buildJsonErrorMessage(Response res) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonGenerator jgen;
    try {
        jgen = new JsonFactory().createGenerator(os);
        jgen.writeStartObject();
        jgen.writeObjectField("Statuscode", res.getStatusCode());
        jgen.writeObjectField("Message", res.getStatusMessage());
        jgen.writeEndObject();
        jgen.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return os.toByteArray();
}
Also used : JsonFactory(com.fasterxml.jackson.core.JsonFactory) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Aggregations

JsonFactory (com.fasterxml.jackson.core.JsonFactory)266 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)102 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)91 JsonParser (com.fasterxml.jackson.core.JsonParser)78 Test (org.junit.Test)65 IOException (java.io.IOException)62 StringWriter (java.io.StringWriter)60 Map (java.util.Map)27 HashMap (java.util.HashMap)26 ArrayList (java.util.ArrayList)25 JsonNode (com.fasterxml.jackson.databind.JsonNode)21 List (java.util.List)18 ExtensibleJSONWriter (com.instagram.common.json.annotation.processor.support.ExtensibleJSONWriter)16 JsonToken (com.fasterxml.jackson.core.JsonToken)15 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 File (java.io.File)14 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)9 InputStreamReader (java.io.InputStreamReader)9 TypeReference (com.fasterxml.jackson.core.type.TypeReference)8 SimpleParseUUT (com.instagram.common.json.annotation.processor.uut.SimpleParseUUT)8