Java Code Examples for javax.ws.rs.core.Response.ResponseBuilder#type()

The following examples show how to use javax.ws.rs.core.Response.ResponseBuilder#type() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: apiman   File: RestExceptionMapper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
 */
@Override
public Response toResponse(AbstractEngineException data) {
    int errorCode;
    if (data instanceof IStatusCode) {
        errorCode = ((IStatusCode) data).getStatusCode();
    } else {
        errorCode = mapExceptionToHttpErrorCode(data);
    }
    GatewayApiErrorBean error = new GatewayApiErrorBean();
    error.setErrorType(data.getClass().getSimpleName());
    error.setMessage(data.getMessage());
    error.setStacktrace(getStackTrace(data));
    ResponseBuilder builder = Response.status(errorCode).header("X-API-Gateway-Error", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    builder.type(MediaType.APPLICATION_JSON_TYPE);
    return builder.entity(error).build();
}
 
Example 2
private ResponseBuilder getBuilder(final String jsonEntity, final Date lastMod, final boolean includeEtag, final Request request) {
	String etagSource = DominoUtils.md5(jsonEntity);
	EntityTag etag = new EntityTag(etagSource);
	ResponseBuilder berg = null;
	if (request != null) {
		berg = request.evaluatePreconditions(etag);
	}
	if (berg == null) {
		// System.out.println("TEMP DEBUG creating a new builder");
		berg = Response.ok();
		if (includeEtag) {
			berg.tag(etag);
		}
		berg.type(MediaType.APPLICATION_JSON_TYPE);
		berg.entity(jsonEntity);
		berg.lastModified(lastMod);
		CacheControl cc = new CacheControl();
		cc.setMustRevalidate(true);
		cc.setPrivate(true);
		cc.setMaxAge(86400);
		cc.setNoTransform(true);
		berg.cacheControl(cc);
	}
	return berg;
}
 
Example 3
private ResponseBuilder getBuilder(final String jsonEntity, final Date lastMod, final boolean includeEtag, final Request request) {
	String etagSource = DominoUtils.md5(jsonEntity);
	EntityTag etag = new EntityTag(etagSource);
	ResponseBuilder berg = null;
	if (request != null) {
		berg = request.evaluatePreconditions(etag);
	}
	if (berg == null) {
		berg = Response.ok();
		if (includeEtag) {
			berg.tag(etag);
		}
		berg.type(MediaType.APPLICATION_JSON_TYPE);
		berg.entity(jsonEntity);
		berg.lastModified(lastMod);
		CacheControl cc = new CacheControl();
		cc.setMustRevalidate(true);
		cc.setPrivate(true);
		cc.setMaxAge(86400);
		cc.setNoTransform(true);
		berg.cacheControl(cc);
	}
	return berg;
}
 
Example 4
Source Project: gossip   File: GossipValidateErrorProvider.java    License: MIT License 6 votes vote down vote up
private Response buildViolationReportResponse(ResteasyViolationException exception) {
    ResponseBuilder builder = Response.status(BAD_REQUEST);
    builder.header(VALIDATION_HEADER, "true");
    builder.type(APPLICATION_JSON_TYPE);

    List<ResteasyConstraintViolation> violations = exception.getViolations();

    if (violations.isEmpty()) {
        builder.entity(new ValidateErrorResponse(exception.toString()));
    } else {
        if (log.isDebugEnabled()) {
            try {
                log.debug(objectMapper.writeValueAsString(violations));
            } catch (JsonProcessingException e) {
                log.debug("", e); // Useless, just make sonar and compiler happy w(゚Д゚)w
            }
        }
        builder.entity(new ValidateErrorResponse(violations));
    }

    return builder.build();
}
 
Example 5
Source Project: cxf   File: StatsRestServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@GET
@Path("/static/{resource:.*}")
public Response getResource(@Context UriInfo uriInfo, @PathParam("resource") String resourcePath) {
    if (resourcePath.contains("favicon")) {
        return Response.status(404).build();
    }

    try {
        final URL resourceURL = getClass().getResource("/web-ui/" + resourcePath);
        final ResponseBuilder rb = Response.ok(resourceURL.openStream());
        
        int ind = resourcePath.lastIndexOf('.');
        if (ind != -1 && ind < resourcePath.length()) {
            String ext = resourcePath.substring(ind + 1);
            if ("js".equalsIgnoreCase(ext)) {
                rb.type("application/javascript");
            } else {
                rb.type(MediaType.TEXT_HTML);
            }
        }
        
        return rb.build();
    } catch (IOException ex) {
        throw new NotFoundException(ex);
    }
}
 
Example 6
protected Response buildViolationReportResponse(ResteasyViolationException exception, Status status) {
    ResponseBuilder builder = Response.status(status);
    builder.header(Validation.VALIDATION_HEADER, "true");

    // Check standard media types.
    MediaType mediaType = getAcceptMediaType(exception.getAccept());
    if (mediaType != null) {
        builder.type(mediaType);
        builder.entity(new ViolationReport(exception));
        return builder.build();
    }

    // Default media type.
    builder.type(MediaType.TEXT_PLAIN);
    builder.entity(exception.toString());
    return builder.build();
}
 
Example 7
Source Project: pxf   File: InvalidPathResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns error message
 */
private Response sendErrorMessage(String message) {
    ResponseBuilder b = Response.serverError();
    b.entity(message);
    b.type(MediaType.TEXT_PLAIN_TYPE);
    return b.build();
}
 
Example 8
Source Project: pxf   File: VersionResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the PXF protocol version used currently.
 *
 * @return response with the PXF protocol version
 */
@GET
@Produces("application/json")
public Response getProtocolVersion() {

    ResponseBuilder b = Response.ok();
    b.entity("{ \"version\": \"" + Version.PXF_PROTOCOL_VERSION + "\"}");
    b.type(MediaType.APPLICATION_JSON_TYPE);
    return b.build();
}
 
Example 9
private ResponseBuilder getBuilder(String jsonEntity, Date lastMod, boolean includeEtag, Request request) {
	String etagSource = DominoUtils.md5(jsonEntity);
	EntityTag etag = new EntityTag(etagSource);
	ResponseBuilder berg = null;
	if (request != null) {
		berg = request.evaluatePreconditions(etag);
	}
	if (berg == null) {
		// System.out.println("TEMP DEBUG creating a new builder");
		berg = Response.ok();
		if (includeEtag) {
			berg.tag(etag);
		}
		berg.type(MediaType.APPLICATION_JSON_TYPE);
		berg.entity(jsonEntity);
		if (lastMod != null) {
			berg.lastModified(lastMod);
		}
		CacheControl cc = new CacheControl();
		cc.setMustRevalidate(true);
		cc.setPrivate(true);
		cc.setMaxAge(86400);
		cc.setNoTransform(true);
		berg.cacheControl(cc);
	}
	return berg;
}
 
Example 10
/**
 * @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
 */
@Override
public Response toResponse(ApiValidationException data) {
    ApiError error = new ApiError();
    error.setErrorType(data.getClass().getSimpleName());
    error.setMessage(data.getMessage());
    error.setTrace(getStackTrace(data));
    ResponseBuilder builder = Response.status(400).header("X-API-Error", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    builder.type(MediaType.APPLICATION_JSON_TYPE);
    return builder.entity(error).build();
}
 
Example 11
/**
 * @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
 */
@Override
public Response toResponse(ServerError data) {
    ApiError error = new ApiError();
    error.setErrorType(data.getClass().getSimpleName());
    error.setMessage(data.getMessage());
    error.setTrace(getStackTrace(data));
    ResponseBuilder builder = Response.status(500).header("X-API-Error", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    builder.type(MediaType.APPLICATION_JSON_TYPE);
    return builder.entity(error).build();
}
 
Example 12
Source Project: apiman   File: RestExceptionMapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see javax.ws.rs.ext.ExceptionMapper#toResponse(java.lang.Throwable)
 */
@Override
public Response toResponse(AbstractRestException data) {
    ErrorBean error = new ErrorBean();
    error.setType(data.getClass().getSimpleName());
    error.setErrorCode(data.getErrorCode());
    error.setMessage(data.getMessage());
    error.setMoreInfoUrl(data.getMoreInfoUrl());
    error.setStacktrace(getStackTrace(data));
    ResponseBuilder builder = Response.status(data.getHttpCode()).header("X-Apiman-Error", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    // If CORS is being used, make sure to add X-Apiman-Error to the exposed headers
    builder.type(MediaType.APPLICATION_JSON_TYPE);
    return builder.entity(error).build();
}
 
Example 13
public static Response createErrorResponse(String message, Response.Status status, Map<String, Object> extraProps) {
    DAS_LOGGER.traceEntry("", "createErrorResponse");  //$NON-NLS-1$ $NON-NLS-2$
    ResponseBuilder builder = Response.status(status);
    builder.type(MediaType.APPLICATION_JSON);
    String jsonEntity = null;
    StringWriter writer = new StringWriter();
    Boolean compact = false;
    JsonWriter jWriter = new JsonWriter(writer, compact);
    
    try {
        try {
            jWriter.startObject();
            writeProperty(jWriter, ATTR_CODE, status.getStatusCode());
            writeProperty(jWriter, ATTR_TEXT, status.getReasonPhrase());
            
            // Write extra properties
            
            writeExtraProperties(jWriter, extraProps);
            
            // Write message
            
            if  (message != null)
                writeProperty(jWriter, "message", message); // $NON-NLS-1$
        } 
        finally {
            jWriter.endObject();
        }
        StringBuffer buffer = writer.getBuffer();
        jsonEntity = buffer.toString();
        builder.entity(jsonEntity);
    }
    catch (IOException ex) {
        DAS_LOGGER.warn(ex, "Error creating response.");  //$NON-NLS-1$
    }
    Response response = builder.build();
    DAS_LOGGER.traceExit("", "createErrorResponse", response); //$NON-NLS-1$ $NON-NLS-2$
    
    return response;
}
 
Example 14
public static Response createErrorResponse(Exception e, Response.Status status, Map<String, Object> extraProps) {
    
    DAS_LOGGER.traceEntry("", "createErrorResponse");  //$NON-NLS-1$ $NON-NLS-2$
    ResponseBuilder builder = Response.status(status);
    builder.type(MediaType.APPLICATION_JSON);
    String jsonEntity = null;
    StringWriter writer = new StringWriter();
    Boolean compact = false;
    JsonWriter jWriter = new JsonWriter(writer, compact);
    
    try {
        try {
            jWriter.startObject();
            writeProperty(jWriter, ATTR_CODE, status.getStatusCode());
            writeProperty(jWriter, ATTR_TEXT, status.getReasonPhrase());
            
            // Write extra properties
            
            writeExtraProperties(jWriter, extraProps);
            
            // Write the exception
            
            writeException(jWriter, e);
        } 
        finally {
            jWriter.endObject();
        }
        StringBuffer buffer = writer.getBuffer();
        jsonEntity = buffer.toString();
        builder.entity(jsonEntity);
    }
    catch (IOException ex) {
        DAS_LOGGER.warn(ex, "Error creating response."); // $NLW-ErrorHelper.ErrorCreatingResponse-1$
    }
    Response response = builder.build();
    DAS_LOGGER.traceExit("", "createErrorResponse", response); //$NON-NLS-1$ $NON-NLS-2$
    
    return response;
}
 
Example 15
/**
 * For creating a Response of a single object of the appropriate media type.
 * 
 * @param object
 *            Object to be returned in XML or JSON
 * @return The created response in the proper media type.
 */
public Response createResponse(Object object) {
	// Start building the response
	ResponseBuilder responseBuilder = Response.ok(object);

	// Since this is a truly open API intended to be used by
	// other web pages allow cross-origin requests.
	responseBuilder.header("Access-Control-Allow-Origin", "*");

	// Specify media type of XML or JSON
	responseBuilder.type(getMediaType());

	// Return the response
	return responseBuilder.build();
}
 
Example 16
Source Project: cxf   File: DynamicRegistrationService.java    License: Apache License 2.0 5 votes vote down vote up
private void reportInvalidRequestError(OAuthError entity, MediaType mt) {
    ResponseBuilder rb = JAXRSUtils.toResponseBuilder(400);
    if (mt != null) {
        rb.type(mt);
    }
    throw ExceptionUtils.toBadRequestException(null, rb.entity(entity).build());
}
 
Example 17
Source Project: cxf   File: AbstractOAuthService.java    License: Apache License 2.0 5 votes vote down vote up
protected void reportInvalidRequestError(OAuthError entity, MediaType mt) {
    ResponseBuilder rb = JAXRSUtils.toResponseBuilder(400);
    if (mt != null) {
        rb.type(mt);
    }
    throw ExceptionUtils.toBadRequestException(null, rb.entity(entity).build());
}
 
Example 18
Source Project: cxf   File: SwaggerUiService.java    License: Apache License 2.0 4 votes vote down vote up
@GET
@Path("{resource:.*}")
public Response getResource(@Context UriInfo uriInfo, @PathParam("resource") String resourcePath) {
    if (resourcePath.contains(FAVICON)) {
        return Response.status(404).build();
    }
    
    try {
        final URL resourceURL = locator.locate(resourcePath);
        final String path = resourceURL.getPath();
        
        String mediaType = null;
        int ind = path.lastIndexOf('.');
        if (ind != -1 && ind < path.length()) {
            String resourceExt = path.substring(ind + 1);
            if (mediaTypes != null && mediaTypes.containsKey(resourceExt)) {
                mediaType = mediaTypes.get(resourceExt);
            } else {
                mediaType = DEFAULT_MEDIA_TYPES.get(resourceExt);
            }
        }

        // If there are no query parameters and Swagger UI configuration is
        // provided, let us do temporary redirect with the Swagger UI configuration
        // wrapped into the query string. For example, the request to
        //
        //    http://localhost:8080/services/helloservice/api-docs
        //
        // might be redirect to
        //
        //    http://localhost:8080/services/helloservice/api-docs?url=/services/helloservice/openapi.json
        //
        // in case the "url" configuration parameter is provided for Swagger UI.
        if (config != null && uriInfo.getQueryParameters().isEmpty() && path.endsWith("/index.html")) {
            final Map<String, String> params = config.getConfigParameters();
            
            if (params != null && !params.isEmpty()) {
                final UriBuilder builder = params
                    .entrySet()
                    .stream()
                    .reduce(
                        uriInfo.getRequestUriBuilder(), 
                        (b, e) -> b.queryParam(e.getKey(), e.getValue()),
                        (left, right) -> left
                    );
                return Response.temporaryRedirect(builder.build()).build();
            }
        }
        
        ResponseBuilder rb = Response.ok(resourceURL.openStream());
        if (mediaType != null) {
            rb.type(mediaType);
        }
        return rb.build();
    } catch (IOException ex) {
        throw new NotFoundException(ex);
    }
}
 
Example 19
Source Project: cxf   File: AbstractClient.java    License: Apache License 2.0 4 votes vote down vote up
protected ResponseBuilder setResponseBuilder(Message outMessage, Exchange exchange) throws Exception {
    Response response = exchange.get(Response.class);
    if (response != null) {
        outMessage.getExchange().getInMessage().put(Message.PROTOCOL_HEADERS, response.getStringHeaders());
        return JAXRSUtils.fromResponse(JAXRSUtils.copyResponseIfNeeded(response));
    }

    Integer status = getResponseCode(exchange);
    ResponseBuilder currentResponseBuilder = JAXRSUtils.toResponseBuilder(status);

    Message responseMessage = exchange.getInMessage() != null
        ? exchange.getInMessage() : exchange.getInFaultMessage();
    // if there is no response message, we just send the response back directly
    if (responseMessage == null) {
        return currentResponseBuilder;
    }

    Map<String, List<Object>> protocolHeaders =
        CastUtils.cast((Map<?, ?>)responseMessage.get(Message.PROTOCOL_HEADERS));

    boolean splitHeaders = MessageUtils.getContextualBoolean(outMessage, HEADER_SPLIT_PROPERTY);
    for (Map.Entry<String, List<Object>> entry : protocolHeaders.entrySet()) {
        if (null == entry.getKey()) {
            continue;
        }
        if (entry.getValue().size() > 0) {
            if (HttpUtils.isDateRelatedHeader(entry.getKey())) {
                currentResponseBuilder.header(entry.getKey(), entry.getValue().get(0));
                continue;
            }
            entry.getValue().forEach(valObject -> {
                if (splitHeaders && valObject instanceof String) {
                    String val = (String) valObject;
                    final String[] values;
                    if (val.isEmpty()) {
                        values = new String[]{""};
                    } else if (val.charAt(0) == '"' && val.charAt(val.length() - 1) == '"') {
                        // if the value starts with a quote and ends with a quote, we do a best
                        // effort attempt to determine what the individual values are.
                        values = parseQuotedHeaderValue(val);
                    } else {
                        boolean splitPossible = !(HttpHeaders.SET_COOKIE.equalsIgnoreCase(entry.getKey())
                                && val.toUpperCase().contains(HttpHeaders.EXPIRES.toUpperCase()));
                        values = splitPossible ? val.split(",") : new String[]{val};
                    }
                    for (String s : values) {
                        String theValue = s.trim();
                        if (!theValue.isEmpty()) {
                            currentResponseBuilder.header(entry.getKey(), theValue);
                        }
                    }
                } else {
                    currentResponseBuilder.header(entry.getKey(), valObject);
                }
            });
        }
    }
    String ct = (String)responseMessage.get(Message.CONTENT_TYPE);
    if (ct != null) {
        currentResponseBuilder.type(ct);
    }
    InputStream mStream = responseMessage.getContent(InputStream.class);
    currentResponseBuilder.entity(mStream);

    return currentResponseBuilder;
}
 
Example 20
protected Response buildResponse(Object entity, String mediaType, Status status) {
    ResponseBuilder builder = Response.status(status).entity(entity);
    builder.type(MediaType.TEXT_PLAIN);
    builder.header(Validation.VALIDATION_HEADER, "true");
    return builder.build();
}