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

The following examples show how to use javax.ws.rs.core.Response.ResponseBuilder#header() . 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: AuthzEndPointResource.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * ImplicitFlowでの認証時のエラーのうち以下の状況で、ユーザが設定したredirect_uriへのRedirectを実行する. 1.response_typeが不正・未指定 2
 * @param state
 * @return
 * @throws MalformedURLException
 */
private Response returnErrorRedirect(String redirectUri, String error,
        String errorDesp, String state, String code) {
    // 302でレスポンスし、Locationヘッダを返却
    ResponseBuilder rb = Response.status(Status.FOUND)
            .type(MediaType.APPLICATION_JSON_TYPE);
    // Locationヘッダに付加するフラグメント情報をURLエンコードする
    StringBuilder sbuf = new StringBuilder(redirectUri + "#" + OAuth2Helper.Key.ERROR + "=");
    try {
        sbuf.append(URLEncoder.encode(error, "utf-8"));
        sbuf.append("&" + OAuth2Helper.Key.ERROR_DESCRIPTION + "=");
        sbuf.append(URLEncoder.encode(errorDesp, "utf-8"));
        sbuf.append("&" + OAuth2Helper.Key.STATE + "=");
        sbuf.append(URLEncoder.encode(state, "utf-8"));
        sbuf.append("&" + OAuth2Helper.Key.CODE + "=");
        sbuf.append(URLEncoder.encode(code, "utf-8"));
    } catch (UnsupportedEncodingException e) {
        // エンコード種別は固定でutf-8にしているので、ここに来ることはありえない
        log.warn("Failed to URLencode, fragmentInfo of Location header.");
    }
    rb.header(HttpHeaders.LOCATION, sbuf.toString());
    // レスポンスの返却
    return rb.entity("").build();
}
 
Example 2
Source File: ResponseCorsFilter.java    From nextreports-server with Apache License 2.0 6 votes vote down vote up
@Override
public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) {
 
    ResponseBuilder resp = Response.fromResponse(contResp.getResponse());
    resp.header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
 
    String reqHead = req.getHeaderValue("Access-Control-Request-Headers");
 
    if(null != reqHead && !reqHead.equals("")){
        resp.header("Access-Control-Allow-Headers", reqHead);
    }
 
    contResp.setResponse(resp.build());
    return contResp;
}
 
Example 3
Source File: StateResource.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@GET
@NoAuth
@Timed
public Response getAllServices(@HeaderParam(HttpHeaders.IF_NONE_MATCH) String ifNoneMatch,
                               @HeaderParam(HttpHeaders.ACCEPT_ENCODING) String acceptEncoding) {
  CachedBaragonState state = stateCache.getState();
  String verisonString = Integer.toString(state.getVersion());

  if (ifNoneMatch != null && ifNoneMatch.equals(verisonString.trim())) {
    return Response.notModified()
        .header(HttpHeaders.ETAG, state.getVersion())
        .build();
  }

  ResponseBuilder builder = Response.ok();

  final byte[] entity;
  if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
    builder.header(HttpHeaders.CONTENT_ENCODING, "gzip");
    entity = state.getGzip();
  } else {
    entity = state.getUncompressed();
  }

  return builder
      .entity(entity)
      .header(HttpHeaders.ETAG, state.getVersion())
      .build();
}
 
Example 4
Source File: GetHandler.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Get the standard headers.
 * @param builder the response builder
 * @return the response builder
 */
public ResponseBuilder standardHeaders(final ResponseBuilder builder) {

    // Standard HTTP Headers
    builder.lastModified(from(getResource().getModified()));

    if (syntax != null) {
        builder.type(syntax.mediaType());
    }

    final IRI model;
    if (getRequest().getExt() == null || DESCRIPTION.equals(getRequest().getExt())) {
        model = getResource().getBinaryMetadata().isPresent() && syntax != null
            ? LDP.RDFSource : getResource().getInteractionModel();
        // Link headers from User data
        getResource().getExtraLinkRelations().collect(toMap(Map.Entry::getKey, Map.Entry::getValue))
                .forEach((key, value) -> builder.link(key, join(" ", value)));
    } else {
        model = LDP.RDFSource;
    }

    // Add LDP-required headers
    addLdpHeaders(builder, model);

    // Memento-related headers
    if (isMemento) {
        builder.header(MEMENTO_DATETIME, from(getResource().getModified()));
    }

    return builder;
}
 
Example 5
Source File: StaffResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@GET
@Path("{id}/image")
public Response getStaffImage(@PathParam("id") Long id) throws AuthenticationException, AuthorisationException, ServiceException {
	StaffImageOutVO out = WebUtil.getServiceLocator().getStaffService().getStaffImage(auth, id);
	ResponseBuilder response = javax.ws.rs.core.Response.ok(new ByteArrayInputStream(out.getDatas()), out.getContentType().getMimeType());
	response.header(HttpHeaders.CONTENT_LENGTH, out.getFileSize());
	return response.build();
}
 
Example 6
Source File: StandardParameters.java    From core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 7
Source File: BaseController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
protected ResponseBuilder handleResponseOk(ResponseBuilder responseBuilder, String transactionId) {
	this.handleEventoOk(responseBuilder, transactionId);
	if(transactionId != null)
		return responseBuilder.header(this.transactionIdHeaderName, transactionId);
	else 
		return responseBuilder;
}
 
Example 8
Source File: BulkExtract.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a streaming response for the sample data file.
 *
 * @param request - HTTP servlet request for public bulk extract file
 *
 * @return A response with the sample extract file
 *
 * @throws Exception On Error
 */
@GET
@Path("extract")
@RightsAllowed({ Right.BULK_EXTRACT })
public Response get(@Context HttpServletRequest request) throws Exception {
    LOG.info("Received request to stream sample bulk extract...");

    logSecurityEvent("Received request to stream sample bulk extract");

    validateRequestCertificate(request);

    final InputStream is = this.getClass().getResourceAsStream("/bulkExtractSampleData/" + SAMPLED_FILE_NAME);

    StreamingOutput out = new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            int n;
            byte[] buffer = new byte[1024];
            while ((n = is.read(buffer)) > -1) {
                output.write(buffer, 0, n);
            }
        }
    };

    ResponseBuilder builder = Response.ok(out);
    builder.header("content-disposition", "attachment; filename = " + SAMPLED_FILE_NAME);
    builder.header("last-modified", "Not Specified");
    logSecurityEvent("Successful request to stream sample bulk extract");
    return builder.build();
}
 
Example 9
Source File: BaseController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
protected ResponseBuilder handleResponseOk(ResponseBuilder responseBuilder, String transactionId) {
	this.handleEventoOk(responseBuilder, transactionId);
	if(transactionId != null)
		return responseBuilder.header(this.transactionIdHeaderName, transactionId);
	else 
		return responseBuilder;
}
 
Example 10
Source File: ProbandAddressResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@GET
@Path("{id}/probandletterpdf")
public Response renderProbandLetterPDF(@PathParam("id") Long id) throws AuthenticationException,
		AuthorisationException, ServiceException {
	ProbandLetterPDFVO vo = WebUtil.getServiceLocator().getProbandService().renderProbandLetterPDF(auth, id);
	// http://stackoverflow.com/questions/9204287/how-to-return-a-png-image-from-jersey-rest-service-method-to-the-browser
	// non-streamed
	ResponseBuilder response = Response.ok(vo.getDocumentDatas(), vo.getContentType().getMimeType());
	response.header(HttpHeaders.CONTENT_LENGTH, vo.getSize());
	return response.build();
}
 
Example 11
Source File: JobResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@GET
@Path("{id}/file")
public Response getJobFile(@PathParam("id") Long id) throws AuthenticationException, AuthorisationException, ServiceException {
	JobFileVO out = WebUtil.getServiceLocator().getJobService().getJobFile(auth, id);
	ResponseBuilder response = javax.ws.rs.core.Response.ok(new ByteArrayInputStream(out.getDatas()), out.getContentType().getMimeType());
	response.header(HttpHeaders.CONTENT_LENGTH, out.getFileSize());
	return response.build();
}
 
Example 12
Source File: ServiceJAXRS.java    From blog with MIT License 5 votes vote down vote up
@GET
@Path("/all/csv")
@Produces("application/pdf")
public Response getFile() {
  File file = GenerateCSV.generateCsvFile(datas);
  ResponseBuilder response = Response.ok((Object) file);
  String filename = "export.csv";
  response.header("Content-Disposition", "attachment; filename="+filename);
  return response.build();
}
 
Example 13
Source File: BaseController.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
protected ResponseBuilder handleResponseKo(ResponseBuilder responseBuilder, String transactionId) {
	if(transactionId != null)
		return responseBuilder.header(this.transactionIdHeaderName, transactionId);
	else 
		return responseBuilder;
}
 
Example 14
Source File: DominiController.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
public Response dominiIdDominioLogoGET(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders, String idDominio) {
  	String methodName = "getLogo";  
String transactionId = ContextThreadLocal.get().getTransactionId();
this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_IN_CORSO, methodName)); 
try{
	// autorizzazione sulla API
	this.isAuthorized(user, Arrays.asList(TIPO_UTENZA.ANONIMO, TIPO_UTENZA.CITTADINO, TIPO_UTENZA.APPLICAZIONE), Arrays.asList(Servizio.API_PAGAMENTI), Arrays.asList(Diritti.LETTURA));
	
	ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
	validatoreId.validaIdDominio("idDominio", idDominio);
	
	// Parametri - > DTO Input
	
	GetDominioDTO getDominioDTO = new GetDominioDTO(user, idDominio);

	// INIT DAO
	
	DominiDAO dominiDAO = new DominiDAO();
	
	// CHIAMATA AL DAO
	
	byte[] logo = dominiDAO.getLogo(getDominioDTO);
	
	MimeUtil.registerMimeDetector(eu.medsea.mimeutil.detector.MagicMimeMimeDetector.class.getName());
	
	Collection<?> mimeTypes = MimeUtil.getMimeTypes(logo);
	
	String mimeType = MimeUtil.getFirstMimeType(mimeTypes.toString()).toString();

	this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_COMPLETATA, methodName)); 
	ResponseBuilder entity = Response.status(Status.OK).entity(logo);
	entity.header("CacheControl", "max-age: "+ GovpayConfig.getInstance().getCacheLogo().intValue());
	entity.header("Content-Type", mimeType);
	return this.handleResponseOk(entity,transactionId).build();
	
}catch (Exception e) {
	return this.handleException(uriInfo, httpHeaders, methodName, e, transactionId);
} finally {
	this.log(ContextThreadLocal.get());
}
  }
 
Example 15
Source File: RowResource.java    From hbase with Apache License 2.0 4 votes vote down vote up
@GET
@Produces(MIMETYPE_BINARY)
public Response getBinary(final @Context UriInfo uriInfo) {
  if (LOG.isTraceEnabled()) {
    LOG.trace("GET " + uriInfo.getAbsolutePath() + " as "+ MIMETYPE_BINARY);
  }
  servlet.getMetrics().incrementRequests(1);
  // doesn't make sense to use a non specific coordinate as this can only
  // return a single cell
  if (!rowspec.hasColumns() || rowspec.getColumns().length > 1) {
    servlet.getMetrics().incrementFailedGetRequests(1);
    return Response.status(Response.Status.BAD_REQUEST).type(MIMETYPE_TEXT)
        .entity("Bad request: Default 'GET' method only works if there is exactly 1 column " +
                "in the row. Using the 'Accept' header with one of these formats lets you " +
                "retrieve the entire row if it has multiple columns: " +
                // Same as the @Produces list for the get method.
                MIMETYPE_XML + ", " + MIMETYPE_JSON + ", " +
                MIMETYPE_PROTOBUF + ", " + MIMETYPE_PROTOBUF_IETF +
                CRLF).build();
  }
  MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
  try {
    ResultGenerator generator =
      ResultGenerator.fromRowSpec(tableResource.getName(), rowspec, null,
        !params.containsKey(NOCACHE_PARAM_NAME));
    if (!generator.hasNext()) {
      servlet.getMetrics().incrementFailedGetRequests(1);
      return Response.status(Response.Status.NOT_FOUND)
        .type(MIMETYPE_TEXT).entity("Not found" + CRLF)
        .build();
    }
    Cell value = generator.next();
    ResponseBuilder response = Response.ok(CellUtil.cloneValue(value));
    response.header("X-Timestamp", value.getTimestamp());
    servlet.getMetrics().incrementSucessfulGetRequests(1);
    return response.build();
  } catch (Exception e) {
    servlet.getMetrics().incrementFailedGetRequests(1);
    return processException(e);
  }
}
 
Example 16
Source File: DominiController.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
public Response dominiIdDominioLogoGET(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders, String idDominio) {
  	String methodName = "getLogo";  
String transactionId = ContextThreadLocal.get().getTransactionId();
this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_IN_CORSO, methodName)); 
try{
	// autorizzazione sulla API
	this.isAuthorized(user, Arrays.asList(TIPO_UTENZA.ANONIMO, TIPO_UTENZA.CITTADINO, TIPO_UTENZA.APPLICAZIONE), Arrays.asList(Servizio.API_PAGAMENTI), Arrays.asList(Diritti.LETTURA));
	
	ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
	validatoreId.validaIdDominio("idDominio", idDominio);
	
	// Parametri - > DTO Input
	
	GetDominioDTO getDominioDTO = new GetDominioDTO(user, idDominio);

	// INIT DAO
	
	DominiDAO dominiDAO = new DominiDAO();
	
	// CHIAMATA AL DAO
	
	byte[] logo = dominiDAO.getLogo(getDominioDTO);
	
	MimeUtil.registerMimeDetector(eu.medsea.mimeutil.detector.MagicMimeMimeDetector.class.getName());
	
	Collection<?> mimeTypes = MimeUtil.getMimeTypes(logo);
	
	String mimeType = MimeUtil.getFirstMimeType(mimeTypes.toString()).toString();

	this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_COMPLETATA, methodName)); 
	ResponseBuilder entity = Response.status(Status.OK).entity(logo);
	entity.header("CacheControl", "max-age: "+ GovpayConfig.getInstance().getCacheLogo().intValue());
	entity.header("Content-Type", mimeType);
	return this.handleResponseOk(entity,transactionId).build();
	
}catch (Exception e) {
	return this.handleException(uriInfo, httpHeaders, methodName, e, transactionId);
} finally {
	this.log(ContextThreadLocal.get());
}
  }
 
Example 17
Source File: ResteasyViolationExceptionMapper.java    From quarkus with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example 18
Source File: FedizRedirectBindingFilter.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
private boolean isLogoutRequest(ContainerRequestContext context, FedizContext fedConfig,
                                Message message, MultivaluedMap<String, String> params) {

    boolean signout = false;
    String logoutUrl = fedConfig.getLogoutURL();
    if (params != null && fedConfig.getProtocol() instanceof FederationProtocol
        && FederationConstants.ACTION_SIGNOUT.equals(
            params.getFirst(FederationConstants.PARAM_ACTION))) {
        signout = true;
    } else if (logoutUrl != null && !logoutUrl.isEmpty()) {
        String requestPath = "/" + context.getUriInfo().getPath();
        if (requestPath.equals(logoutUrl) || requestPath.equals(logoutUrl + "/")) {
            signout = true;
        }
    }

    if (signout) {
        cleanupContext(message);

        try {
            FedizProcessor processor =
                FedizProcessorFactory.newFedizProcessor(fedConfig.getProtocol());

            HttpServletRequest request = messageContext.getHttpServletRequest();
            RedirectionResponse redirectionResponse =
                processor.createSignOutRequest(request, null, fedConfig); //TODO
            String redirectURL = redirectionResponse.getRedirectionURL();
            if (redirectURL != null) {
                ResponseBuilder response = Response.seeOther(new URI(redirectURL));
                Map<String, String> headers = redirectionResponse.getHeaders();
                if (!headers.isEmpty()) {
                    for (Entry<String, String> entry : headers.entrySet()) {
                        response.header(entry.getKey(), entry.getValue());
                    }
                }

                context.abortWith(response.build());

                return true;
            }
        } catch (Exception ex) {
            LOG.debug(ex.getMessage(), ex);
            throw ExceptionUtils.toInternalServerErrorException(ex, null);
        }
    }

    return false;
}
 
Example 19
Source File: TemplateResource.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Download template from database with specified id (in progress)
 **/
@GET
@Path("/{templateId}/{filetype}/file")
public Response downloadTemplate(@PathParam("templateId") Integer templateId, @PathParam("filetype") FILETYPE filetype) {
	logger.debug("IN");
	ResponseBuilder response = Response.ok();
	try {
		IObjTemplateDAO templateDAO = DAOFactory.getObjTemplateDAO();

		templateDAO.setUserProfile(getUserProfile());

		ObjTemplate template = new ObjTemplate();

		template = templateDAO.loadBIObjectTemplate(templateId);
		template.getContent();
		String filename = template.getName();
		int typePos = filename.lastIndexOf(".");
		if (typePos > 0) {
			filename = filename.substring(0, typePos) + "." + filetype.name().toLowerCase();
		}
		byte[] byteContent = null;
		switch (filetype) {
		case json:
		case xml:
		case bin:
		case jrxml:
		case rptdesign:
		case sbicockpit:
			byteContent = template.getContent();
			response = Response.ok(byteContent);
			response.header("Content-Disposition", "attachment; filename=" + filename);
			break;
		default:
			response = Response.ok(new JSError().addError("Not valid filetype [" + filetype + "]"));
			break;
		}
	} catch (Exception e) {
		logger.debug("Template could not be downloaded", e);
		throw new SpagoBIRestServiceException("Template could not be downloaded", buildLocaleFromSession(), e);
	}
	logger.debug("OUT");
	return response.build();
}
 
Example 20
Source File: ValidationExceptionMapper.java    From jaxrs-beanvalidation-javaee7 with Apache License 2.0 4 votes vote down vote up
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();
}