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

The following examples show how to use javax.ws.rs.core.Response.ResponseBuilder#entity() . 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 File: OAuthUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static Response handleException(MessageContext mc,
                                       Exception e,
                                       int status) {
    ResponseBuilder builder = Response.status(status);
    if (PropertyUtils.isTrue(mc.getContextualProperty(REPORT_FAILURE_DETAILS))) {
        boolean asHeader = PropertyUtils.isTrue(
            mc.getContextualProperty(REPORT_FAILURE_DETAILS_AS_HEADER));
        String text = null;
        if (e instanceof OAuthProblemException) {
            OAuthProblemException problem = (OAuthProblemException)e;
            if (asHeader && problem.getProblem() != null) {
                text = problem.getProblem();
            }
        }
        if (text == null) {
            text = e.getMessage();
        }
        if (asHeader) {
            builder.header("oauth_problem", text);
        } else {
            builder.entity(e.getMessage());
        }
    }
    return builder.build();
}
 
Example 2
Source File: ClientResponseFilterInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected Response getResponse(Message inMessage) {
    Response resp = inMessage.getExchange().get(Response.class);
    if (resp != null) {
        return JAXRSUtils.copyResponseIfNeeded(resp);
    }
    ResponseBuilder rb = JAXRSUtils.toResponseBuilder((Integer)inMessage.get(Message.RESPONSE_CODE));
    rb.entity(inMessage.get(InputStream.class));

    @SuppressWarnings("unchecked")
    Map<String, List<String>> protocolHeaders =
        (Map<String, List<String>>)inMessage.get(Message.PROTOCOL_HEADERS);
    for (Map.Entry<String, List<String>> entry : protocolHeaders.entrySet()) {
        if (null == entry.getKey()) {
            continue;
        }
        if (entry.getValue().size() > 0) {
            for (String val : entry.getValue()) {
                rb.header(entry.getKey(), val);
            }
        }
    }


    return rb.build();
}
 
Example 3
Source File: NexusITSupport.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Preform a get request
 *
 * @param baseUrl               (nexusUrl in most tests)
 * @param path                  to the resource
 * @param headers               {@link Header}s
 * @param useDefaultCredentials use {@link NexusITSupport#clientBuilder(URL, boolean)} for using credentials
 * @return the response object
 */
protected Response get(final URL baseUrl,
                       final String path,
                       final Header[] headers,
                       final boolean useDefaultCredentials) throws Exception
{
  HttpGet request = new HttpGet();
  request.setURI(UriBuilder.fromUri(baseUrl.toURI()).path(path).build());
  request.setHeaders(headers);

  try (CloseableHttpClient client = clientBuilder(nexusUrl, useDefaultCredentials).build()) {

    try (CloseableHttpResponse response = client.execute(request)) {
      ResponseBuilder responseBuilder = Response.status(response.getStatusLine().getStatusCode());
      Arrays.stream(response.getAllHeaders()).forEach(h -> responseBuilder.header(h.getName(), h.getValue()));

      HttpEntity entity = response.getEntity();
      if (entity != null) {
        responseBuilder.entity(new ByteArrayInputStream(IOUtils.toByteArray(entity.getContent())));
      }
      return responseBuilder.build();
    }
  }
}
 
Example 4
Source File: ThrowableMapper.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public Response toResponse(Throwable throwable)
{
    if (throwable instanceof WebApplicationException) {
        return ((WebApplicationException) throwable).getResponse();
    }

    log.warn(throwable, "Request failed for %s", request.getRequestURI());

    ResponseBuilder responseBuilder = Response.serverError()
            .header(CONTENT_TYPE, TEXT_PLAIN);
    if (includeExceptionInResponse) {
        responseBuilder.entity(Throwables.getStackTraceAsString(throwable));
    }
    else {
        responseBuilder.entity("Exception processing request");
    }
    return responseBuilder.build();
}
 
Example 5
Source File: BasicRESTClient.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Override
public Response connect(final String authorizationCode) throws OAuthException, MalformedURLException,
        URISyntaxException {
    OAuthService service = new ServiceBuilder().provider(SliApi.class).apiKey(config.getApiKey())
            .apiSecret(config.getApiSecret()).callback(config.getCallback()).build();
    Verifier verifier = new Verifier(authorizationCode);
    SliApi.TokenResponse r = ((SliApi.SLIOauth20ServiceImpl) service).getAccessToken(
            new Token(config.getApiSecret(), authorizationCode), verifier, null);

    if (r != null && r.getToken() != null) {
        accessToken = r.getToken();
        sessionToken = accessToken.getToken();
    }

    ResponseBuilder builder = Response.status(r.getOauthResponse().getCode());
    for (Map.Entry<String, String> entry : r.getOauthResponse().getHeaders().entrySet()) {
        if (entry.getKey() == null) {
            builder.header("Status", entry.getValue());
        } else {
            builder.header(entry.getKey(), entry.getValue());
        }
    }
    builder.entity(r.getOauthResponse().getBody());

    return builder.build();
}
 
Example 6
Source File: ResteasyViolationExceptionMapper.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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 File: TermsResource.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
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 8
Source File: ResourceITSupport.java    From nexus-repository-helm with Eclipse Public License 1.0 5 votes vote down vote up
private Response execute(HttpEntityEnclosingRequestBase request) throws Exception {
  try (CloseableHttpResponse response = clientBuilder().build().execute(request)) {
    ResponseBuilder responseBuilder = Response.status(response.getStatusLine().getStatusCode());
    Arrays.stream(response.getAllHeaders()).forEach(h -> responseBuilder.header(h.getName(), h.getValue()));

    HttpEntity entity = response.getEntity();
    if (entity != null) {
      responseBuilder.entity(new ByteArrayInputStream(IOUtils.toByteArray(entity.getContent())));
    }
    return responseBuilder.build();
  }
}
 
Example 9
Source File: InvalidPathResource.java    From pxf with 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 10
Source File: ApiException.java    From iaf with Apache License 2.0 5 votes vote down vote up
private static Response formatException(String message, Status status, String mediaType) {
	ResponseBuilder response = Response.status(status).type(mediaType);

	if(message != null) {
		message = message.replace("\"", "\\\"").replace("\n", " ").replace(System.getProperty("line.separator"), " ");

		response.entity(("{\"status\":\"error\", \"error\":\"" + message + "\"}"));
	}
	return response.build();
}
 
Example 11
Source File: ServiceHandler.java    From servicemix with Apache License 2.0 5 votes vote down vote up
private void delete(int id){
    if (persons.remove(id) == null) {
        ResponseBuilder builder = Response.status(Status.NOT_FOUND);
        builder.entity("Person with ID " + id + " not found.");
        throw new WebApplicationException(builder.build());
    }
}
 
Example 12
Source File: GetHandler.java    From trellis with Apache License 2.0 5 votes vote down vote up
private ResponseBuilder getLdpRs(final ResponseBuilder builder, final RDFSyntax syntax,
        final IRI profile) {
    final Prefer prefer = getRequest().getPrefer();

    // Check for a cache hit
    final EntityTag etag = generateEtag(getResource(), weakEtags);
    checkCache(getResource().getModified(), etag);

    builder.tag(etag);
    addAllowHeaders(builder);

    if (prefer != null) {
        builder.header(PREFERENCE_APPLIED,
                PREFER_RETURN + "=" + prefer.getPreference().orElse(PREFER_REPRESENTATION));
        if (prefer.getPreference().filter(PREFER_MINIMAL::equals).isPresent()) {
            return builder.status(NO_CONTENT);
        }
    }

    // Short circuit HEAD requests
    if (HEAD.equals(getRequest().getMethod())) {
        return builder;
    }

    // Stream the rdf content
    return builder.entity((StreamingOutput) out -> {
        try (final Stream<Quad> stream = getResource().stream(getPreferredGraphs(prefer))) {
            getServices().getIOService().write(stream.map(Quad::asTriple)
                            .map(unskolemizeTriples(getServices().getResourceService(), getBaseUrl())), out,
                    syntax, getIdentifier(), getJsonLdProfile(profile, syntax));
        }
    });
}
 
Example 13
Source File: ReferenceResource.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
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 14
Source File: RestServiceExceptionMapper.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static ResponseBuilder getSyncopeClientExceptionResponse(final SyncopeClientException ex) {
    ResponseBuilder builder = Response.status(ex.getType().getResponseStatus());
    builder.header(RESTHeaders.ERROR_CODE, ex.getType().name());

    ErrorTO error = new ErrorTO();
    error.setStatus(ex.getType().getResponseStatus().getStatusCode());
    error.setType(ex.getType());

    ex.getElements().forEach(element -> {
        builder.header(RESTHeaders.ERROR_INFO, ex.getType().getInfoHeaderValue(element));
        error.getElements().add(element);
    });

    return builder.entity(error);
}
 
Example 15
Source File: ErrorHelper.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
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 16
Source File: BrooklynSecurityProviderFilterHelper.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
SecurityProviderDeniedAuthentication abort(String msg, boolean requiresUserPass) throws SecurityProviderDeniedAuthentication {
    ResponseBuilder response = Response.status(Status.UNAUTHORIZED);
    if (requiresUserPass) {
        response.header(HttpHeader.WWW_AUTHENTICATE.asString(), BASIC_REALM_HEADER_VALUE);
    }
    response.header(HttpHeader.CONTENT_TYPE.asString(), MediaType.TEXT_PLAIN);
    response.entity(msg);
    throw new SecurityProviderDeniedAuthentication(response.build());
}
 
Example 17
Source File: Delete.java    From FHIR with Apache License 2.0 5 votes vote down vote up
private Response buildResponse(FHIRRestOperationResponse ior) {
    ResponseBuilder response = Response.status(ior.getStatus());

    if (ior.getOperationOutcome() != null) {
        response.entity(ior.getOperationOutcome());
    }

    if (ior.getResource() != null) {
        addHeaders(response, ior.getResource());
    }
    return response.build();
}
 
Example 18
Source File: AbstractClient.java    From cxf with 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 19
Source File: RestUtil.java    From olingo-odata2 with Apache License 2.0 3 votes vote down vote up
public static Response convertResponse(final ODataResponse odataResponse, final boolean omitResponseBody) {
  try {
    ResponseBuilder responseBuilder =
        Response.noContent().status(odataResponse.getStatus().getStatusCode());
    if(!omitResponseBody) {
      responseBuilder.entity(odataResponse.getEntity());
    }

    for (final String name : odataResponse.getHeaderNames()) {
      responseBuilder = responseBuilder.header(name, odataResponse.getHeader(name));
    }

    return responseBuilder.build();
  } catch (RuntimeException e) {
    if (odataResponse != null) {
      try {
        odataResponse.close();
      } catch (IOException inner) {
        // if close throw an exception we ignore these and re-throw our exception
        throw e;
      }
    }
    throw e;
  }
}
 
Example 20
Source File: ErrorResponseBuilder.java    From teamengine with Apache License 2.0 3 votes vote down vote up
/**
 * Builds a response message that indicates some kind of error has occurred.
 * The error message is included as the content of the xhtml:body/xhtml:p
 * element.
 * 
 * @param statusCode
 *            The relevant HTTP error code (4xx, 5xx).
 * @param msg
 *            A brief description of the error condition.
 * @return A <code>Response</code> instance containing an XHTML entity.
 */
public Response buildErrorResponse(int statusCode, String msg) {
    ResponseBuilder rspBuilder = Response.status(statusCode);
    rspBuilder.type("application/xhtml+xml; charset=UTF-8");
    rspBuilder.entity(createErrorEntityAsString(statusCode, msg));
    return rspBuilder.build();
}