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

The following examples show how to use javax.ws.rs.core.Response.ResponseBuilder#build() . 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: DcCoreAuthzException.java    From io with Apache License 2.0 6 votes vote down vote up
@Override
public Response createResponse() {
    ResponseBuilder rb = Response.status(HttpStatus.SC_UNAUTHORIZED)
            .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
            .entity(new ODataErrorMessage(code, message));

    // レルム値が設定されていれば、WWW-Authenticateヘッダーを返却する。
    if (null != this.realm) {
        switch (this.authScheme) {
        case BEARER:
            rb = rb.header(HttpHeaders.WWW_AUTHENTICATE, Scheme.BEARER + " realm=\"" + this.realm + "\"");
            break;
        case BASIC:
            rb = rb.header(HttpHeaders.WWW_AUTHENTICATE, Scheme.BASIC + " realm=\"" + this.realm + "\"");
            break;
        default: // デフォルトとして、Bearer/Basicの両方を返却する。
            rb = rb.header(HttpHeaders.WWW_AUTHENTICATE, Scheme.BEARER + " realm=\"" + this.realm + "\"");
            rb = rb.header(HttpHeaders.WWW_AUTHENTICATE, Scheme.BASIC + " realm=\"" + this.realm + "\"");
            break;
        }
    }
    return rb.build();
}
 
Example 2
Source File: ApiExceptionHandler.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
@Produces(MediaType.TEXT_PLAIN)
public Response toResponse(Exception exception) {
	//If the message has already been wrapped in an exception we don't need to `convert` it!
	if(exception instanceof ApiException) {
		return ((ApiException) exception).getResponse();
	}

	ResponseBuilder response = Response.status(Status.INTERNAL_SERVER_ERROR);
	String message = exception.getMessage();

	if(message != null) {
		message = message.replace("\"", "\\\"").replace("\n", " ").replace(System.getProperty("line.separator"), " ");
		Map<String, Object> entity = new HashMap<String, Object>(3);
		entity.put("status", "error");
		entity.put("error", message);
		entity.put("stackTrace", exception.getStackTrace());

		response.entity(entity).type(MediaType.APPLICATION_JSON);
	}

	return response.build();
}
 
Example 3
Source File: DavMoveResource.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * MOVEメソッドの処理.
 * @return JAX-RS応答オブジェクト
 */
public Response doMove() {

    // リクエストヘッダのバリデート
    validateHeaders();

    // 移動先のBox情報を取得する
    BoxRsCmp boxRsCmp = getBoxRsCmp();

    // 移動先の情報を生成
    DavDestination davDestination;
    try {
        davDestination = new DavDestination(destination, this.getAccessContext().getBaseUri(), boxRsCmp);
    } catch (URISyntaxException e) {
        // URI 形式でない
        throw DcCoreException.Dav.INVALID_REQUEST_HEADER.params(org.apache.http.HttpHeaders.DESTINATION,
                destination);
    }

    // データの更新・削除
    ResponseBuilder response = this.davCmp.move(this.ifMatch, this.overwrite, davDestination);

    return response.build();
}
 
Example 4
Source File: BaseController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
private Response handleRedirectException(UriInfo uriInfo, HttpHeaders httpHeaders, String methodName, RedirectException e, String transactionId) {
	this.log.error("Esecuzione del metodo ["+methodName+"] si e' conclusa con un errore: " + e.getMessage() + ", redirect verso la url: " + e.getLocation());
	ResponseBuilder responseBuilder = Response.seeOther(e.getURILocation());
	this.handleEventoOk(responseBuilder, transactionId);
	if(transactionId != null)
		return responseBuilder.header(this.transactionIdHeaderName, transactionId).build();
	else
		return responseBuilder.build();
}
 
Example 5
Source File: ProbandResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@GET
@Path("{id}/inquiryvalues/signuppdf")
public Response renderInquiriesSignup(@PathParam("id") Long id, @QueryParam("department_id") Long departmentId, @QueryParam("active_signup") Boolean activeSignup)
		throws AuthenticationException,
		AuthorisationException, ServiceException {
	InquiriesPDFVO vo = WebUtil.getServiceLocator().getProbandService().renderInquiriesSignup(auth, departmentId, id, activeSignup);
	// 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 6
Source File: RResourceITSupport.java    From nexus-repository-r 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 7
Source File: DossierActivityResource.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@GET
@Path("/activity/{activityId}/{type}")
public Response downloadPPTExists(@PathParam("activityId") Integer activityId, @PathParam("type") String type,
		@QueryParam("activityName") String activityName) {

	ISbiDossierActivityDAO sdaDAO;
	DossierActivity activity;
	byte[] file;

	Calendar cal = Calendar.getInstance();
	SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
	String formattedDate = format.format(cal.getTime());

	try {
		sdaDAO = DAOFactory.getDossierActivityDao();
		logger.debug("Downloading PPT file with activity id: " + activityId + ". Activity name: " + activityName);
		activity = sdaDAO.loadActivity(activityId);
		file = activity.getBinContent();

		ResponseBuilder response = Response.ok(file);
		response.header("Content-Disposition", "attachment; filename=" + activityName + "_" + formattedDate + "." + type);
		response.header("filename", activityName + "_" + formattedDate + "." + type);
		return response.build();

	} catch (Exception e) {
		logger.error("Error while downloading file with activity id: " + activityId + " for activity: " + activityName, e);
		throw new SpagoBIRestServiceException(getLocale(), e);
	}

}
 
Example 8
Source File: EventResource.java    From XPagesExtensionLibrary with Apache License 2.0 5 votes vote down vote up
@PUT
@Consumes(MEDIA_TYPE_ICALENDAR)
public Response updateEvent(String requestEntity,  @Context UriInfo uriInfo,
                    @PathParam(EVENT) String id, 
                    @QueryParam(URL_PARAM_WORKFLOWCOMMENT) String comments,
                    @QueryParam(URL_PARAM_WORKFLOW) String workflow,
                    @QueryParam(URL_PARAM_LITERALLY) String literally,
                    @QueryParam(URL_PARAM_STRICT_SEQUENCE) String strictSequence) {
    
    String responseEntity = null;

    CALENDAR_SERVICE_LOGGER.traceEntry(this, "updateEvent"); // $NON-NLS-1$
    CalendarService.beforeRequest(FEATURE_REST_API_CALENDAR_EVENT, STAT_UPDATE_EVENT);

    CalendarService.verifyDatabaseContext();

    try {
        if ( StringUtil.isEmpty(requestEntity) ) {
            throw new WebApplicationException(CalendarService.createErrorResponse("Empty request body.", Status.BAD_REQUEST)); // $NLX-EventResource.Emptyrequestbody.2-1$
        }
        
        int flags = getUpdateFlags(workflow, literally, strictSequence);
        responseEntity = StoreFactory.getEventStore().updateEvent(requestEntity, id, null, comments, flags);
    }
    catch(StoreException e) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Utils.mapStatus(e), Utils.getExtraProps(e)));
    }
    
    ResponseBuilder builder = Response.ok();
    builder.type(MEDIA_TYPE_ICALENDAR).entity(responseEntity);
    Response response = builder.build();
    CALENDAR_SERVICE_LOGGER.traceExit(this, "updateEvent", response); // $NON-NLS-1$
    
    return response;
}
 
Example 9
Source File: BaseController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
private Response handleRedirectException(UriInfo uriInfo, HttpHeaders httpHeaders, String methodName, RedirectException e, String transactionId) {
	this.log.error("Esecuzione del metodo ["+methodName+"] si e' conclusa con un errore: " + e.getMessage() + ", redirect verso la url: " + e.getLocation());
	ResponseBuilder responseBuilder = Response.seeOther(e.getURILocation());
	this.handleEventoOk(responseBuilder, transactionId);
	if(transactionId != null)
		return responseBuilder.header(this.transactionIdHeaderName, transactionId).build();
	else
		return responseBuilder.build();
}
 
Example 10
Source File: StaffResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@GET
@Path("{id}/files/pdf")
public Response aggregatePDFFiles(@PathParam("id") Long id, @Context UriInfo uriInfo) throws AuthenticationException, AuthorisationException, ServiceException {
	FilePDFVO vo = WebUtil.getServiceLocator().getFileService().aggregatePDFFiles(auth, fileModule, id, null, false, null, null, new PSFUriPart(uriInfo));
	// 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: 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 12
Source File: BookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/bookheaders/simple/")
@CustomHeaderAdded
@PostMatchMode
@Consumes("application/xml")
public Response echoBookByHeaderSimple(Book book,
    @HeaderParam("Content-type") String ct,
    @HeaderParam("BOOK") String headerBook,
    @HeaderParam("Simple") String headerSimple,
    @HeaderParam("ServerReaderInterceptor") String serverInterceptorHeader,
    @HeaderParam("ClientWriterInterceptor") String clientInterceptorHeader,
    @HeaderParam("EmptyRequestStreamDetected") String emptyStreamHeader) throws Exception {
    if (!"application/xml".equals(ct)) {
        throw new RuntimeException();
    }
    ResponseBuilder builder = getBookByHeaderSimpleBuilder(headerBook, headerSimple);
    if (serverInterceptorHeader != null) {
        builder.header("ServerReaderInterceptor", serverInterceptorHeader);
    }
    if (clientInterceptorHeader != null) {
        builder.header("ClientWriterInterceptor", clientInterceptorHeader);
    }
    if (emptyStreamHeader != null) {
        builder.header("EmptyRequestStreamDetected", emptyStreamHeader);
    }
    return builder.build();
}
 
Example 13
Source File: InfoResource.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response performRequest(@Context final UriInfo uriInfo, @PathParam(Routes.NAMESPACE) final String namespace)
		throws JsonException, IOException {
	String jsonEntity = null;
	ResponseBuilder builder = Response.ok();
	ParamMap pm = Parameters.toParamMap(uriInfo);
	StringWriter sw = new StringWriter();
	DFramedTransactionalGraph<?> graph = this.getGraph(namespace);
	JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true, false);
	// writer.outObject(null);
	List<String> items = pm.get(Parameters.ITEM);
	if (items != null && items.size() > 0) {
		IGraphFactory factory = this.getService().getFactory(namespace);
		if (factory != null) {
			for (String item : items) {
				Object curResult = factory.processRequest(namespace, item, uriInfo.getQueryParameters());
				writer.outObject(curResult);
			}
		} else {
			System.err.println("No Factory found for namespace: " + namespace);
		}
	}
	jsonEntity = sw.toString();
	builder.type(MediaType.APPLICATION_JSON_TYPE).entity(jsonEntity);
	Response response = builder.build();
	return response;

}
 
Example 14
Source File: UmaResourceRegistrationWS.java    From oxAuth with MIT License 5 votes vote down vote up
@GET
@Path("{rsid}")
@Produces({UmaConstants.JSON_MEDIA_TYPE})
public Response getResource(
        @HeaderParam("Authorization")
                String authorization,
        @PathParam("rsid")
                String rsid) {
    try {
        final AuthorizationGrant authorizationGrant = umaValidationService.assertHasProtectionScope(authorization);
        umaValidationService.validateRestrictedByClient(authorizationGrant.getClientDn(), rsid);
        log.debug("Getting resource description: '{}'", rsid);

        final org.gluu.oxauth.model.uma.persistence.UmaResource ldapResource = resourceService.getResourceById(rsid);

        final UmaResourceWithId response = new UmaResourceWithId();

        response.setId(ldapResource.getId());
        response.setName(ldapResource.getName());
        response.setDescription(ldapResource.getDescription());
        response.setIconUri(ldapResource.getIconUri());
        response.setScopes(umaScopeService.getScopeIdsByDns(ldapResource.getScopes()));
        response.setScopeExpression(ldapResource.getScopeExpression());
        response.setType(ldapResource.getType());
        response.setIat(ServerUtil.dateToSeconds(ldapResource.getCreationDate()));
        response.setExp(ServerUtil.dateToSeconds(ldapResource.getExpirationDate()));

        final ResponseBuilder builder = Response.ok();
        builder.entity(ServerUtil.asJson(response)); // convert manually to avoid possible conflicts between resteasy providers, e.g. jettison, jackson

        return builder.build();
    } catch (Exception ex) {
        log.error("Exception happened", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        }

        throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, UmaErrorResponseType.SERVER_ERROR, ex.getMessage());
    }
}
 
Example 15
Source File: FeedREST.java    From commafeed with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/favicon/{id}")
@UnitOfWork
@ApiOperation(value = "Fetch a feed's icon", notes = "Fetch a feed's icon")
@Timed
public Response getFeedFavicon(@ApiParam(hidden = true) @SecurityCheck User user,
		@ApiParam(value = "subscription id", required = true) @PathParam("id") Long id) {

	Preconditions.checkNotNull(id);
	FeedSubscription subscription = feedSubscriptionDAO.findById(user, id);
	if (subscription == null) {
		return Response.status(Status.NOT_FOUND).build();
	}
	Feed feed = subscription.getFeed();
	Favicon icon = feedService.fetchFavicon(feed);

	ResponseBuilder builder = Response.ok(icon.getIcon(), Optional.ofNullable(icon.getMediaType()).orElse("image/x-icon"));

	CacheControl cacheControl = new CacheControl();
	cacheControl.setMaxAge(2592000);
	cacheControl.setPrivate(false);
	builder.cacheControl(cacheControl);

	Calendar calendar = Calendar.getInstance();
	calendar.add(Calendar.MONTH, 1);
	builder.expires(calendar.getTime());
	builder.lastModified(CommaFeedApplication.STARTUP_TIME);

	return builder.build();
}
 
Example 16
Source File: FramedCollectionResource.java    From org.openntf.domino with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createFramedObject(final String requestEntity, @Context final UriInfo uriInfo,
		@PathParam(Routes.NAMESPACE) final String namespace, @Context final Request request)
				throws JsonException, IOException {
	// org.apache.wink.common.internal.registry.metadata.ResourceMetadataCollector
	// rc;
	@SuppressWarnings("rawtypes")
	DFramedTransactionalGraph graph = this.getGraph(namespace);
	ParamMap pm = Parameters.toParamMap(uriInfo);
	StringWriter sw = new StringWriter();
	JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true, true);
	// System.out.println("TEMP DEBUG Starting new POST...");
	JsonJavaObject jsonItems = null;
	List<Object> jsonArray = null;
	JsonGraphFactory factory = JsonGraphFactory.instance;
	try {
		StringReader reader = new StringReader(requestEntity);
		try {
			Object jsonRaw = JsonParser.fromJson(factory, reader);
			if (jsonRaw instanceof JsonJavaObject) {
				jsonItems = (JsonJavaObject) jsonRaw;
			} else if (jsonRaw instanceof List) {
				jsonArray = (List<Object>) jsonRaw;
				// System.out.println("TEMP DEBUG processing a POST with an
				// array of size " + jsonArray.size());
			} else {
				// System.out.println("TEMP DEBUG Got an unexpected object
				// from parser "
				// + (jsonRaw == null ? "null" :
				// jsonRaw.getClass().getName()));
			}
		} catch (Exception e) {
			throw new WebApplicationException(
					ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
		} finally {
			reader.close();
		}
	} catch (Exception ex) {
		throw new WebApplicationException(
				ErrorHelper.createErrorResponse(ex, Response.Status.INTERNAL_SERVER_ERROR));
	}
	boolean committed = true;
	Map<Object, Object> results = new LinkedHashMap<Object, Object>();
	if (jsonArray != null) {
		writer.startArray();
		for (Object raw : jsonArray) {
			if (raw instanceof JsonJavaObject) {
				writer.startArrayItem();
				committed = processJsonObject((JsonJavaObject) raw, graph, writer, results);
				writer.endArrayItem();
			} else {
				System.err.println("Raw array member isn't a JsonJavaObject. It's a "
						+ (raw == null ? "null" : raw.getClass().getName()));
			}
		}
		writer.endArray();
	} else if (jsonItems != null) {
		committed = processJsonObject(jsonItems, graph, writer, results);
	} else {
		// System.out.println("TEMP DEBUG Nothing to POST. No JSON items
		// found.");
	}

	String jsonEntity = sw.toString();
	ResponseBuilder berg = getBuilder(jsonEntity, new Date(), false, request);
	Response response = berg.build();
	if (!committed) {
		graph.rollback();
	}
	return response;
}
 
Example 17
Source File: AbstractSLARest.java    From SeaCloudsPlatform with Apache License 2.0 4 votes vote down vote up
protected Response buildResponse(int code, String payload) {

        ResponseBuilder builder = Response.status(code);
        builder.entity(payload);
        return builder.build();
    }
 
Example 18
Source File: KnoxMetadataResource.java    From knox with Apache License 2.0 4 votes vote down vote up
private Response generateSuccessFileDownloadResponse(java.nio.file.Path publicCertFilePath) {
  final ResponseBuilder responseBuilder = Response.ok(publicCertFilePath.toFile());
  responseBuilder.header("Content-Disposition", "attachment;filename=" + publicCertFilePath.getFileName().toString());
  return responseBuilder.build();
}
 
Example 19
Source File: DossierDocumentManagementImpl.java    From opencps-v2 with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Response printFileByPartNo(HttpServletRequest request, HttpHeaders header, Company company, Locale locale,
		User user, ServiceContext serviceContext, String id, String templateNo, String partNo) {

	BackendAuth auth = new BackendAuthImpl();
	long dossierId = GetterUtil.getLong(id);

	try {

		if (!auth.isAuth(serviceContext)) {
			throw new UnauthenticationException();
		}

		List<DossierFile> dossierFileList = DossierFileLocalServiceUtil.getDossierFileByDID_DPNO(dossierId, partNo,
				false);
		if (dossierFileList  != null && dossierFileList.size() > 0) {
			for (DossierFile dossierFile : dossierFileList) {
				if (dossierFile != null && Validator.isNotNull(dossierFile.getFormData())) {
					long docFileId = dossierFile.getFileEntryId();
					if (docFileId > 0) {
						FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(docFileId);

						File file = DLFileEntryLocalServiceUtil.getFile(fileEntry.getFileEntryId(),
								fileEntry.getVersion(), true);

						ResponseBuilder responseBuilder = Response.ok((Object) file);
	
						responseBuilder.header("Content-Disposition",
								"attachment; filename=\"" + fileEntry.getFileName() + "\"");
						responseBuilder.header("Content-Type", fileEntry.getMimeType());
	
						return responseBuilder.build();
					}
				}
			}
		}
	} catch (Exception e) {
		return BusinessExceptionImpl.processException(e);
	}
	return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
}
 
Example 20
Source File: ViewCollectionResource.java    From XPagesExtensionLibrary with Apache License 2.0 4 votes vote down vote up
/**
 * Gets a list of views and folders in a database.
 * 
 * @return
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getViews(@Context final UriInfo uriInfo,
        @QueryParam(PARAM_COMPACT) final boolean compact) {
    
    DAS_LOGGER.traceEntry(this, "getViews"); // $NON-NLS-1$
    DataService.beforeRequest(FEATURE_REST_API_DATA_VIEW_COLLECTION, STAT_VIEW_COLLECTION);

    StreamingOutput streamJsonEntity = new StreamingOutput(){

        //@Override
        public void write(OutputStream outputStream) throws IOException {
            try {
                URI baseURI = UriHelper.copy(uriInfo.getAbsolutePath(),DataService.isUseRelativeUrls());
                
                Database database = getDatabase(DB_ACCESS_VIEWS);
                if ( database == null ) {
                    // This resource should always have a database context
                    throw new WebApplicationException(ErrorHelper.createErrorResponse("URI path must include a database.", Response.Status.BAD_REQUEST)); // $NLX-ViewCollectionResource.URIpathmustincludeadatabase-1$
                }
                
                OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream);
                JsonWriter jwriter = new JsonWriter(streamWriter, compact);
                JsonViewCollectionContent content = new JsonViewCollectionContent(database, baseURI.toString());
                content.writeViewCollection(jwriter);
                
                streamWriter.close();
            }
            catch (ServiceException e) {
                throw new WebApplicationException(ErrorHelper.createErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
            }
        }
    };

    ResponseBuilder builder = Response.ok();
    builder.type(MediaType.APPLICATION_JSON_TYPE).entity(streamJsonEntity);
    
    Response response = builder.build();
    DAS_LOGGER.traceExit(this, "getViews", response); // $NON-NLS-1$

    return response;
}