com.gtcgroup.test.restful.helper.JprResponseUtilHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.gtcgroup.test.restful.helper.JprResponseUtilHelper.java

Source

/*
 * [Licensed per the Open Source "MIT License".]
 *
 * Copyright (c) 2006 - 2016 by
 * Global Technology Consulting Group, Inc. at
 * http://gtcGroup.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.gtcgroup.test.restful.helper;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.Response.Status;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gtcgroup.jped.core.helper.JpcLoggingCacheHelper;
import com.gtcgroup.jped.test.core.exception.internal.TestingException;

/**
 * This Util Helper class provides convenience methods for handling
 * {@link ClientRequestContext} instances.
 *
 * <p style="font-family:Verdana; font-size:10px; font-style:italic">
 * Copyright (c) 2006 - 2016 by Global Technology Consulting Group, Inc. at
 * <a href="http://gtcGroup.com">gtcGroup.com </a>.
 * </p>
 *
 * @author Marvin Toll
 * @since v3.0
 */
public class JprResponseUtilHelper {

    private static final String CLASS_NAME = JprResponseUtilHelper.class.getSimpleName();

    /**
     * @param <ENTITY>
     * @param instance
     * @return {@link Response}
     */
    public static <ENTITY> Response buildResponseInstanceOK(final ENTITY instance) {

        final Response response = Response.ok(instance).build();
        return response;
    }

    /**
     * @param entity
     * @param statusAsInt
     * @return {@link Response}
     */
    public static Response buildResponseInstanceWithStatus(final Object entity, final int statusAsInt) {
        return JprResponseUtilHelper.buildResponseInstanceWithStatus(entity, Status.fromStatusCode(statusAsInt));
    }

    /**
     * @param entity
     * @param status
     * @return {@link Response}
     */
    public static Response buildResponseInstanceWithStatus(final Object entity, final Status status) {

        Response response;

        try {
            response = JprResponseUtilHelper.getResponseBuilder(status).entity(entity).build();
        } catch (final Exception e) {
            throw new TestingException("The status is not valid.", e);
        }

        return response;
    }

    /**
     * @param entityList
     * @return {@link Response}
     */
    public static Response buildResponseListOK(final List<?> entityList) {

        final GenericEntity<List<?>> genericEntityList = new GenericEntity<List<?>>(entityList) {
            // Empty Block
        };

        final Response response = Response.ok(genericEntityList).build();
        return response;
    }

    /**
     * @param requestContext
     * @param responseContext
     */
    @SuppressWarnings("resource")
    public static void filterOutgoingResponse(final ClientRequestContext requestContext,
            final ClientResponseContext responseContext) {

        final String methodName = "filterOutgoingResponse";

        InputStream entityStream = null;

        StringBuilder message = new StringBuilder();

        try {

            entityStream = responseContext.getEntityStream();

            message = new StringBuilder();
            message.append("JAX-RS ");
            if (null != requestContext.getEntity()) {

                message.append("\n");
                final ObjectMapper mapper = new ObjectMapper();

                try {
                    message.append(mapper.writerWithDefaultPrettyPrinter()
                            .writeValueAsString(responseContext.getEntityStream()));

                } catch (final Exception e) {
                    throw new TestingException("Unable to log outgoing response.", e);
                }
            }

        } finally {
            JprResponseUtilHelper.closeResources(entityStream);

        }
        JpcLoggingCacheHelper.getLogger().logModeLifecycle(JprResponseUtilHelper.CLASS_NAME, methodName,
                message.toString());

        return;
    }

    /**
     * @param statusAsInt
     * @return {@link ResponseBuilder}
     */
    public static ResponseBuilder getResponseBuilder(final int statusAsInt) {
        return Response.status(statusAsInt);
    }

    /**
     * @param status
     * @return {@link ResponseBuilder}
     */
    public static ResponseBuilder getResponseBuilder(final Status status) {
        return JprResponseUtilHelper.getResponseBuilder(status.getStatusCode());
    }

    /**
     * @param entityStream
     * @param scanner
     * @throws IOException
     */
    private static void closeResources(final InputStream entityStream) {
        try {
            entityStream.close();
        } catch (@SuppressWarnings("unused") final Exception e) {
            // Ignore
        }
    }

}