Search in sources :

Example 86 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project azure-sdk-for-java by Azure.

the class VirtualMachinesImpl method capture.

@Override
public String capture(String groupName, String name, String containerName, String vhdPrefix, boolean overwriteVhd) {
    VirtualMachineCaptureParametersInner parameters = new VirtualMachineCaptureParametersInner();
    parameters.withDestinationContainerName(containerName);
    parameters.withOverwriteVhds(overwriteVhd);
    parameters.withVhdPrefix(vhdPrefix);
    VirtualMachineCaptureResultInner captureResult = this.inner().capture(groupName, name, parameters);
    ObjectMapper mapper = new ObjectMapper();
    //Object to JSON string
    try {
        return mapper.writeValueAsString(captureResult.output());
    } catch (JsonProcessingException e) {
        throw Exceptions.propagate(e);
    }
}
Also used : JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 87 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project EnrichmentMapApp by BaderLab.

the class AbstractChart method toSerializableString.

@Override
public String toSerializableString() {
    String output = "";
    try {
        final ObjectMapper om = getObjectMapper();
        output = om.writeValueAsString(this.properties);
        output = getId() + ":" + output;
    } catch (JsonProcessingException e) {
        logger.error("Cannot create JSON from custom graphics", e);
    }
    return output;
}
Also used : JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 88 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project EnrichmentMapApp by BaderLab.

the class AbstractChart method set.

public synchronized void set(final String key, Object value) {
    if (key == null)
        throw new IllegalArgumentException("'key' must not be null.");
    final Class<?> type = getSettingType(key);
    if (type != null) {
        if (value != null) {
            // It's OK; just take the value as it is.
            boolean correctType = type == Array.class && value.getClass().isArray() && value.getClass().getComponentType() == getSettingElementType(key);
            correctType = correctType || type.isAssignableFrom(value.getClass());
            if (!correctType) {
                final ObjectMapper om = getObjectMapper();
                String json = value.toString();
                if (type != List.class) {
                    try {
                        json = om.writeValueAsString(value);
                    } catch (JsonProcessingException e) {
                        logger.error("Cannot parse JSON field " + key, e);
                    }
                }
                value = PropertiesJsonDeserializer.readValue(key, json, om, this);
            }
        }
        properties.put(key, value);
    }
}
Also used : JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 89 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project riposte by Nike-Inc.

the class ChannelPipelineFinalizerHandler method finalizeChannelPipeline.

/**
     * This will first check the given state to see if a response was sent to the user. If not then this method will
     * send a generic error to the user so they get some response (so this method is kind of a backstop in case requests
     * somehow slip through our pipeline without being handled, which should never happen, but we have to have this just
     * in case). Then it will clean out the state so that it is ready for the next request.
     * <p/>
     * If the state indicates that a response was already sent then this method will only clean out the state for the
     * next request and will not send an error.
     */
protected void finalizeChannelPipeline(ChannelHandlerContext ctx, Object msg, HttpProcessingState state, Throwable cause) throws JsonProcessingException {
    RequestInfo<?> requestInfo = exceptionHandlingHandler.getRequestInfo(state, msg);
    //      is sent it will update the state.isResponseSent() so that further calls will return true.
    if (!state.isResponseSendingStarted()) {
        String errorMsg = "Discovered a request that snuck through without a response being sent. This should not " + "be possible and indicates a major problem in the channel pipeline.";
        logger.error(errorMsg, new Exception("Wrapper exception", cause));
        // Send a generic unhandled error response with a wrapper exception so that the logging info output by the
        //      exceptionHandlingHandler will have the overview of what went wrong.
        Exception exceptionToUse = new Exception(errorMsg, cause);
        ResponseInfo<ErrorResponseBody> responseInfo = exceptionHandlingHandler.processUnhandledError(state, msg, exceptionToUse);
        responseSender.sendErrorResponse(ctx, requestInfo, responseInfo);
    }
    ctx.flush();
    //      the metrics for this request, so make sure we only do it if appropriate.
    if (metricsListener != null && !state.isRequestMetricsRecordedOrScheduled()) {
        //      conditions), otherwise do it when the response finishes.
        if (!state.isResponseSendingLastChunkSent()) {
            // TODO: Somehow mark the state as a failed request and update the metrics listener to handle it
            metricsListener.onEvent(ServerMetricsEvent.RESPONSE_SENT, state);
        } else {
            // We need to use a copy of the state in case the original state gets cleaned.
            HttpProcessingState stateCopy = new HttpProcessingState(state);
            stateCopy.getResponseWriterFinalChunkChannelFuture().addListener((ChannelFutureListener) channelFuture -> {
                if (channelFuture.isSuccess())
                    metricsListener.onEvent(ServerMetricsEvent.RESPONSE_SENT, stateCopy);
                else {
                    metricsListener.onEvent(ServerMetricsEvent.RESPONSE_WRITE_FAILED, null);
                }
            });
        }
        state.setRequestMetricsRecordedOrScheduled(true);
    }
    // Make sure to clear out request info chunks, multipart data, and any other resources to prevent reference
    //      counting memory leaks (or any other kind of memory leaks).
    requestInfo.releaseAllResources();
    //      channel if it sits unused longer than the timeout value before the next request arrives.
    if (workerChannelIdleTimeoutMillis > 0 && ctx.pipeline().get(IDLE_CHANNEL_TIMEOUT_HANDLER_NAME) == null) {
        ctx.pipeline().addFirst(IDLE_CHANNEL_TIMEOUT_HANDLER_NAME, new IdleChannelTimeoutHandler(workerChannelIdleTimeoutMillis, "ServerWorkerChannel"));
    }
    //      request is broken. We can't do anything except kill the channel.
    if ((cause != null) && state.isResponseSendingStarted() && !state.isResponseSendingLastChunkSent()) {
        runnableWithTracingAndMdc(() -> logger.error("Received an error in ChannelPipelineFinalizerHandler after response sending was started, but " + "before it finished. Closing the channel. unexpected_error={}", cause.toString()), ctx).run();
        ctx.channel().close();
    }
}
Also used : HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) Span(com.nike.wingtips.Span) RequestInfo(com.nike.riposte.server.http.RequestInfo) LoggerFactory(org.slf4j.LoggerFactory) ChannelInboundHandler(io.netty.channel.ChannelInboundHandler) ResponseInfo(com.nike.riposte.server.http.ResponseInfo) Tracer(com.nike.wingtips.Tracer) PipelineContinuationBehavior(com.nike.riposte.server.handler.base.PipelineContinuationBehavior) ErrorResponseBody(com.nike.riposte.server.error.handler.ErrorResponseBody) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ChannelPromise(io.netty.channel.ChannelPromise) MetricsListener(com.nike.riposte.metrics.MetricsListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Logger(org.slf4j.Logger) ChannelOutboundHandler(io.netty.channel.ChannelOutboundHandler) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) BaseInboundHandlerWithTracingAndMdcSupport(com.nike.riposte.server.handler.base.BaseInboundHandlerWithTracingAndMdcSupport) IDLE_CHANNEL_TIMEOUT_HANDLER_NAME(com.nike.riposte.server.channelpipeline.HttpChannelInitializer.IDLE_CHANNEL_TIMEOUT_HANDLER_NAME) LastOutboundMessage(com.nike.riposte.server.channelpipeline.message.LastOutboundMessage) ChannelAttributes(com.nike.riposte.server.channelpipeline.ChannelAttributes) AsyncNettyHelper.runnableWithTracingAndMdc(com.nike.riposte.util.AsyncNettyHelper.runnableWithTracingAndMdc) ResponseSender(com.nike.riposte.server.http.ResponseSender) ProxyRouterProcessingState(com.nike.riposte.server.http.ProxyRouterProcessingState) ServerMetricsEvent(com.nike.riposte.server.metrics.ServerMetricsEvent) HttpProcessingState(com.nike.riposte.server.http.HttpProcessingState) ErrorResponseBody(com.nike.riposte.server.error.handler.ErrorResponseBody) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 90 with JsonProcessingException

use of com.fasterxml.jackson.core.JsonProcessingException in project riposte by Nike-Inc.

the class ResponseSender method sendFullResponse.

/**
     * Outputs the given *full* responseInfo to the user via the given ctx argument. This method only works on full
     * responses (where {@link ResponseInfo#isChunkedResponse()} is false). If the response's {@link
     * ResponseInfo#getContentForFullResponse()} is not null then the given serializer will be used to convert the
     * content to a string (the {@link #defaultResponseContentSerializer} will be used if the given serializer is
     * null).
     * <p/>
     * The given requestInfo argument is used to help determine the Trace ID that should be output to the user in the
     * headers as well as to determine if the user wants the connection kept alive. Once the response is successfully
     * sent, this method sets the channel state's {@link
     * HttpProcessingState#setResponseWriterFinalChunkChannelFuture(ChannelFuture)}
     * to the result of the {@link ChannelHandlerContext#write(Object)} call to indicate that the response was sent for
     * handlers further down the chain and to allow them to attach listeners that are fired when the response is fully
     * sent. {@link ResponseInfo#isResponseSendingStarted()} and {@link ResponseInfo#isResponseSendingLastChunkSent()}
     * will also be set to true (assuming this call is successful).
     * <p/>
     * This will throw an {@link IllegalArgumentException} if {@link ResponseInfo#isChunkedResponse()} is true (since
     * this method is only for full responses). It will log an error and do nothing if the the response has already been
     * sent.
     */
public void sendFullResponse(ChannelHandlerContext ctx, RequestInfo<?> requestInfo, ResponseInfo<?> responseInfo, ObjectMapper serializer) throws JsonProcessingException {
    if (responseInfo.isChunkedResponse()) {
        throw new IllegalArgumentException("sendFullResponse() should only be passed a ResponseInfo where ResponseInfo.isChunkedResponse() is " + "false. This time it was passed one where isChunkedResponse() was true, indicating a chunked " + "(not full) response.");
    }
    if (responseInfo.isResponseSendingLastChunkSent()) {
        runnableWithTracingAndMdc(() -> logger.error("The last response chunk has already been sent. This method should not have been called. Ignoring " + "this method call.", new Exception("This exception and stack trace is for debugging purposes")), ctx).run();
        return;
    }
    if (serializer == null)
        serializer = defaultResponseContentSerializer;
    // There is only one chunk representing the full request, so send it.
    sendFirstChunk(ctx, requestInfo, responseInfo, serializer);
    ctx.flush();
}
Also used : JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)117 IOException (java.io.IOException)28 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)26 ArrayList (java.util.ArrayList)14 HashMap (java.util.HashMap)11 Test (org.junit.Test)11 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 InputStream (java.io.InputStream)7 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)6 ErrorResponseBody (com.nike.riposte.server.error.handler.ErrorResponseBody)6 HttpProcessingState (com.nike.riposte.server.http.HttpProcessingState)6 OutputStreamWriter (java.io.OutputStreamWriter)6 Map (java.util.Map)6 Status (com.ctrip.platform.dal.daogen.domain.Status)5 TaskDTO (com.linkedin.thirdeye.datalayer.dto.TaskDTO)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 List (java.util.List)4 IncorrectRPCMethodException (com.exalttech.trex.remote.exceptions.IncorrectRPCMethodException)3 InvalidRPCResponseException (com.exalttech.trex.remote.exceptions.InvalidRPCResponseException)3