@PUT @Produces(MediaType.APPLICATION_JSON) @Path("/put/books") public Response postView( @FormParam("username") String username, @FormParam("password") String password, @FormParam("schema") String schema, @FormParam("collection") String collection, @FormParam("json") String json) { System.out.println("STORE BOOKS"); System.out.println(schema); System.out.println(collection); System.out.println(json); try { System.out.println(json); Gson g = new Gson(); saveJson(schema, collection, json); String out = g.toJson("JSON successfully stored."); ResponseBuilder builder = Response.ok(out); builder.header("Access-Control-Allow-Origin", "*"); builder.header("Access-Control-Max-Age", "3600"); builder.header("Access-Control-Allow-Methods", "PUT"); builder.header( "Access-Control-Allow-Headers", "X-Requested-With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin"); return builder.build(); } catch (Exception e) { return Response.status(500).entity("Error in 'getView' service: " + e.getMessage()).build(); } }
@POST @Produces(MediaType.APPLICATION_JSON) @Path("/get/books") public Response getBooksTitle( @FormParam("title") String title, @FormParam("author") String author, @FormParam("isbn") String isbn, @FormParam("schema") String schema, @FormParam("collection") String collection) { System.out.println("library"); System.out.println(schema); System.out.println(collection); System.out.println(title); System.out.println(author); try { Gson g = new Gson(); String view = selectBooks(schema, collection, title, author, isbn); ResponseBuilder builder = Response.ok(view); builder.header("Access-Control-Allow-Origin", "*"); builder.header("Access-Control-Max-Age", "3600"); builder.header("Access-Control-Allow-Methods", "POST"); builder.header( "Access-Control-Allow-Headers", "X-Requested-With,Host,User-Agent,Accept,Accept-Language,Accept-Encoding,Accept-Charset,Keep-Alive,Connection,Referer,Origin"); return builder.build(); } catch (Exception e) { return Response.status(500).entity("Error in 'getView' service: " + e.getMessage()).build(); } }
/* * (non-Javadoc) * * @see org.slc.sli.api.client.impl.IRESTClient#connect(java.lang.String, java.lang.String) */ @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); Token t = null; SliApi.TokenResponse r = ((SliApi.SLIOauth20ServiceImpl) service) .getAccessToken(new Token(config.getApiSecret(), authorizationCode), verifier, t); 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(); }
@GET @Produces(MIMETYPE_BINARY) public Response getBinary(final @Context UriInfo uriInfo) { if (LOG.isDebugEnabled()) { LOG.debug("GET " + uriInfo.getAbsolutePath() + " as " + MIMETYPE_BINARY); } servlet.getMetrics().incrementRequests(1); try { KeyValue value = generator.next(); if (value == null) { LOG.info("generator exhausted"); return Response.noContent().build(); } ResponseBuilder response = Response.ok(value.getValue()); response.cacheControl(cacheControl); response.header("X-Row", Base64.encodeBytes(value.getRow())); response.header( "X-Column", Base64.encodeBytes(KeyValue.makeColumn(value.getFamily(), value.getQualifier()))); response.header("X-Timestamp", value.getTimestamp()); return response.build(); } catch (IllegalStateException e) { ScannerResource.delete(id); throw new WebApplicationException(Response.Status.GONE); } }
private void preflight(final String origin, final ContainerRequestContext requestContext) throws IOException { checkOrigin(requestContext, origin); final ResponseBuilder builder = Response.ok(); builder.header(ACCESS_CONTROL_ALLOW_ORIGIN, origin); if (allowCredentials) builder.header(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); String requestMethods = requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_METHOD); if (requestMethods != null) { if (allowedMethods != null) { requestMethods = this.allowedMethods; } builder.header(ACCESS_CONTROL_ALLOW_METHODS, requestMethods); } String allowHeaders = requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_HEADERS); if (allowHeaders != null) { if (allowedHeaders != null) { allowHeaders = this.allowedHeaders; } builder.header(ACCESS_CONTROL_ALLOW_HEADERS, allowHeaders); } if (corsMaxAge > -1) { builder.header(ACCESS_CONTROL_MAX_AGE, corsMaxAge); } requestContext.abortWith(builder.build()); }
private void putDeviceCountIntoResponseHeaders(PushApplication app, ResponseBuilder response) { long appCount = 0; for (Variant variant : app.getVariants()) { long variantCount = installationDao.getNumberOfDevicesForVariantID(variant.getVariantID()); appCount += variantCount; response.header("deviceCount_variant_" + variant.getVariantID(), variantCount); } response.header("deviceCount_app_" + app.getPushApplicationID(), appCount); }
private void putActivityIntoResponseHeaders(PushApplication app, ResponseBuilder response) { response.header( "activity_app_" + app.getPushApplicationID(), metricsService.countMessagesForPushApplication(app.getPushApplicationID())); for (Variant variant : app.getVariants()) { response.header( "activity_variant_" + variant.getVariantID(), metricsService.countMessagesForVariant(variant.getVariantID())); } }
/** * @param req * @param returnMethod * @return a cors-ed response object. */ private static Response toCORS(final ResponseBuilder req, final String returnMethod) { final ResponseBuilder rb = req.header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Methods", "GET, PUT, OPTIONS"); if (returnMethod != null && !returnMethod.isEmpty()) rb.header("Access-Control-Allow-Headers", returnMethod); return rb.build(); }
protected Response accepted(ResponseBody rb, URI jobUri, URI newItemUri) { ResponseBuilder bldr = Response.status(Status.ACCEPTED).entity(rb); if (jobUri != null) { bldr.header("Location", jobUri); } if (newItemUri != null) { bldr.header("X-Location", newItemUri); } return bldr.build(); }
private Response makeCORS(ResponseBuilder req, String returnMethod) { ResponseBuilder rb = req.header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); // if the CORS headers are set, use these or overwrite the settings from // above respectively if (!"".equals(returnMethod)) { rb.header("Access-Control-Allow-Headers", returnMethod); } return rb.build(); }
@GET @Path("printlog/{logfileId}") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_OCTET_STREAM}) public Response logFile(@PathParam("logfileId") final Long id) { final DataUpload uploadStatus = this.dataUploadRepository.findOne(id); final String printFilePath = uploadStatus.getUploadFilePath(); final String printFileName = printFilePath.replace("csv", "log"); final File file = new File(printFileName); ResponseBuilder response = Response.ok(file); response.header("Content-Disposition", "attachment; filename=\"" + printFileName + "\""); response.header( "Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); return response.build(); }
private Response appendAllowOriginHeader(ResponseBuilder rb, HttpServletRequest request) { return rb.header( "Access-Control-Allow-Origin", request.getHeader("Origin")) // return submitted origin .header("Access-Control-Allow-Credentials", "true") .build(); }
/** * List Push Applications * * @param page page number * @param pageSize number of items per page * @param includeDeviceCount put device count into response headers, default {@code false} * @param includeActivity put activity into response headers, default {@code false} * @return list of {@link PushApplication}s * @responseheader total Total count of items * @responseheader activity_app_{pushApplicationID} Count number of messages for Push Application * @responseheader activity_variant_{variantID} Count number of messages for Variant * @responseheader deviceCount_app_{pushApplicationID} Count number of devices for Push * Application * @responseheader deviceCount_variant_{variantID} Count number of devices for Variant */ @GET @Produces(MediaType.APPLICATION_JSON) @ReturnType("java.util.List<org.jboss.aerogear.unifiedpush.api.PushApplication>") public Response listAllPushApplications( @QueryParam("page") Integer page, @QueryParam("per_page") Integer pageSize, @QueryParam("includeDeviceCount") @DefaultValue("false") boolean includeDeviceCount, @QueryParam("includeActivity") @DefaultValue("false") boolean includeActivity) { if (pageSize != null) { pageSize = Math.min(MAX_PAGE_SIZE, pageSize); } else { pageSize = DEFAULT_PAGE_SIZE; } if (page == null) { page = 0; } final PageResult<PushApplication, Count> pageResult = getSearch().findAllPushApplicationsForDeveloper(page, pageSize); ResponseBuilder response = Response.ok(pageResult.getResultList()); response.header("total", pageResult.getAggregate().getCount()); for (PushApplication app : pageResult.getResultList()) { if (includeActivity) { putActivityIntoResponseHeaders(app, response); } if (includeDeviceCount) { putDeviceCountIntoResponseHeaders(app, response); } } return response.build(); }
/** * @param entityType * @param entityId * @param documentId * @return */ @GET @Path("{documentId}/attachment") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) public Response downloadFile( @PathParam("entityType") String entityType, @PathParam("entityId") Long entityId, @PathParam("documentId") Long documentId) { DocumentData documentData = this.documentReadPlatformService.retrieveDocument(entityType, entityId, documentId); File file = new File(documentData.getLocation()); ResponseBuilder response = Response.ok(file); response.header( "Content-Disposition", "attachment; filename=\"" + documentData.getFileName() + "\""); response.header("Content-Type", documentData.getType()); return response.build(); }
@Override public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { ResponseBuilder responseBuilder = Response.fromResponse(response.getResponse()); responseBuilder.header(ACCESS_CONTROL_ALLOW_ORIGIN, this.origin); response.setResponse(responseBuilder.build()); return response; }
@GET @Path("{documentId}/attachment") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_OCTET_STREAM}) public Response downloadFile( @PathParam("entityType") final String entityType, @PathParam("entityId") final Long entityId, @PathParam("documentId") final Long documentId) { this.context.authenticatedUser().validateHasReadPermission(this.SystemEntityType); // final DocumentData documentData = // this.documentReadPlatformService.retrieveDocument(entityType, entityId, documentId); final FileData fileData = this.documentReadPlatformService.retrieveFileData(entityType, entityId, documentId); final ResponseBuilder response = Response.ok(fileData.file()); response.header("Content-Disposition", "attachment; filename=\"" + fileData.name() + "\""); response.header("Content-Type", fileData.contentType()); return response.build(); }
@GET @Path("/download/{fileName}") public Response downloadFile(@PathParam("fileName") String fileName) { try { File file = new File(Constants.fileLocation + fileName); ResponseBuilder builder = Response.ok((Object) file); builder.header("Content-Disposition", "attachment; filename=" + fileName); return builder.build(); } catch (Exception e) { return Response.status(404).build(); } }
@Override public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) { LOGGER.info("Enter CORS filter"); LOGGER.info("Request= { path:" + req.getPath() + ", method:" + req.getMethod() + " }"); ResponseBuilder resp = Response.fromResponse(contResp.getResponse()); resp.header("Access-Control-Allow-Origin", "*"); resp.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); String reqHead = req.getHeaderValue("Access-Control-Request-Headers"); if (null != reqHead && !reqHead.equals(null)) { resp.header("Access-Control-Allow-Headers", reqHead); } contResp.setResponse(resp.build()); LOGGER.info("Exit CORS filter"); return contResp; }
private Response prepareResourceSetPermissionTicketResponse( HttpServletRequest request, ResourceSetPermission resourceSetPermissions) { ResponseBuilder builder = Response.status(Response.Status.CREATED); builder.entity(new ResourceSetPermissionTicket(resourceSetPermissions.getTicket())); // Add location StringBuffer location = request.getRequestURL().append("/").append(resourceSetPermissions.getConfigurationCode()); builder.header("Location", location); return builder.build(); }
@GET // http://localhost:8080/RESTfulWS-web/rest/university/get @Path("/get") @Produces("text/plain") // pdf - application/pdf, image- image/png public Response getStudentFile() { File file = new File("d:\\AplikacjeProsteNaukowe\\RESTfulWS\\DemoFile.txt"); ResponseBuilder response = Response.ok((Object) file); response.header( "Content-Disposition", "attachment; filename=DisplayName-DemoFile.txt"); // pod taka nazwa DisplayName-DemoFile.txt // pobierzemy plik return response.build(); }
/** * @param branchGuid -- the GUID of the branch to apply the test to * @param selectedTypes -- a list of the Low level Artifact types that will be used for the report * @return -- An Excel sheet (in XML format) containing the two reports */ @GET @Produces(MediaType.APPLICATION_XML) public Response getLowHighReqReport( @QueryParam("branch") long branchUuid, @QueryParam("selected_types") String selectedTypes) { Conditions.checkNotNull(branchUuid, "branch query param"); Conditions.checkNotNull(selectedTypes, "selected_types query param"); StreamingOutput streamingOutput = new PublishLowHighReqStreamingOutput(logger, orcsApi, branchUuid, selectedTypes); String fileName = "Requirement_Trace_Report.xml"; ResponseBuilder builder = Response.ok(streamingOutput); builder.header("Content-Disposition", "attachment; filename=" + fileName); return builder.build(); }
private synchronized boolean doCancel(String retryAfterHeader) { if (cancelled) { return true; } if (!isSuspended()) { return false; } ResponseBuilder rb = Response.status(503); if (retryAfterHeader != null) { rb.header(HttpHeaders.RETRY_AFTER, retryAfterHeader); } cancelled = true; doResumeFinal(rb.build()); return cancelled; }
public Response build() { String origin = request.getHttpHeaders().getRequestHeaders().getFirst(ORIGIN_HEADER); if (origin == null) { return builder.build(); } if (!preflight && (allowedOrigins == null || (!allowedOrigins.contains(origin) && !allowedOrigins.contains(ACCESS_CONTROL_ALLOW_ORIGIN_WILDCARD)))) { return builder.build(); } builder.header(ACCESS_CONTROL_ALLOW_ORIGIN, origin); if (preflight) { if (allowedMethods != null) { builder.header(ACCESS_CONTROL_ALLOW_METHODS, CollectionUtil.join(allowedMethods)); } else { builder.header(ACCESS_CONTROL_ALLOW_METHODS, DEFAULT_ALLOW_METHODS); } } if (!preflight && exposedHeaders != null) { builder.header(ACCESS_CONTROL_EXPOSE_HEADERS, CollectionUtil.join(exposedHeaders)); } builder.header(ACCESS_CONTROL_ALLOW_CREDENTIALS, Boolean.toString(auth)); if (preflight) { if (auth) { builder.header( ACCESS_CONTROL_ALLOW_HEADERS, String.format("%s, %s", DEFAULT_ALLOW_HEADERS, AUTHORIZATION_HEADER)); } else { builder.header(ACCESS_CONTROL_ALLOW_HEADERS, DEFAULT_ALLOW_HEADERS); } } if (preflight) { builder.header(ACCESS_CONTROL_MAX_AGE, DEFAULT_MAX_AGE); } return builder.build(); }
@GET @Path("info.zip") @Produces("application/zip") public Response doGet() throws Exception { ServerInfoCollector serverInfoCollector = Framework.getLocalService(ServerInfoCollector.class); // TODO: find a way to delete the File after written in the response by // JAX-RS File serverInfoZip = serverInfoCollector.collectInfoAsZip(); ResponseBuilder responseBuilder = Response.ok(serverInfoZip); responseBuilder.type(MediaType.APPLICATION_OCTET_STREAM); responseBuilder.header( "Content-Disposition", String.format("attachment; filename=\"%s\"", SERVER_INFO_ZIP_FILENAME)); return responseBuilder.build(); }
private ResponseBuilder appendPreflightResponseHeaders( HttpHeaders headers, ResponseBuilder response) { // add response headers for the preflight request // required response .header( "Access-Control-Allow-Origin", headers.getRequestHeader("Origin").get(0)) // return submitted origin .header("Access-Control-Allow-Methods", "POST, DELETE") // only POST/DELETE are allowed .header( "Access-Control-Allow-Headers", "accept, origin, content-type, authorization") // explicit Headers! .header("Access-Control-Allow-Credentials", "true") // indicates how long the results of a preflight request can be cached (in seconds) .header("Access-Control-Max-Age", "604800"); // for now, we keep it for seven days return response; }
@Path("/any-file-type/{type}") @GET public Response anyFileType(@PathParam("type") String fileType) { /* * We are loading file kept in resources/static/ folder using Spring * ResourceLoader classpath mechanism. We have following files: 1. * sample.doc 2. sample.jpg 3. sample.pdf 4. sample.png Based on type * passed, we load sample.<type> from resources folder. We are using * Spring ResourceLoader to load file. */ File file = null; String mimeType; try { file = resourceLoader.getResource("classpath:static/sample." + fileType).getFile(); /* * We can also use normal File constructor to load a file. For e.g. * File file = new File("C:\sample.pdf"); */ if (!file.exists()) { throw new WebApplicationException(404); } } catch (IOException e) { e.printStackTrace(); } /* Finding MIME type for explicitly setting MIME */ mimeType = new MimetypesFileTypeMap().getContentType(file); ResponseBuilder rb = Response.ok(file, mimeType); /* * Setting file name and making sure file download instead of showing in * browser */ rb.header("Content-Disposition", "inline; filename=sample." + fileType); return rb.build(); }
@GET @Path("/report/{accessKey}") @Produces("application/pdf") public Response getFileInPDFFormat(@PathParam("accessKey") String accessKey) { // System.out.println("File requested is : " + fileName); log.info("************OBTIENE REPORTE PARA KEY: " + accessKey); // Put some validations here such as invalid file name or missing file name if (accessKey == null || accessKey.isEmpty()) { ResponseBuilder response = Response.status(Status.BAD_REQUEST); return response.build(); } // Prepare a file object with file to return File file = new File("/Users/santteegt/Desktop/FACTURAELECTRONICA.pdf"); ResponseBuilder response = Response.ok((Object) file); response.header( "Content-Disposition", "attachment; filename=\"COMPROBANTE-" + accessKey + "\""); return response.build(); }
/* * Setting MIME type explicitly using @Produces annotation. Content will * displayed in browser if possible. */ @Path("/png-file/") @GET @Produces("image/png") public Response pngFileType() { File file = null; try { file = resourceLoader.getResource("classpath:static/sample.png").getFile(); if (!file.exists()) { throw new WebApplicationException(404); } } catch (IOException e) { e.printStackTrace(); } ResponseBuilder rb = Response.ok(file); /* Setting file name */ rb.header("Content-Disposition", "attachment; filename=sample.png"); return rb.build(); }
@POST @Path("{csid}") public Response invokeReport( @Context UriInfo ui, @PathParam("csid") String csid, InvocationContext invContext) { Response response = null; try { StringBuffer outMimeType = new StringBuffer(); StringBuffer outFileName = new StringBuffer(); ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext(); InputStream reportInputStream = invokeReport(ctx, csid, invContext, outMimeType, outFileName); // Need to set response type for what is requested... ResponseBuilder builder = Response.ok(reportInputStream, outMimeType.toString()); builder = builder.header( "Content-Disposition", "inline;filename=\"" + outFileName.toString() + "\""); response = builder.build(); } catch (Exception e) { throw bigReThrow(e, ServiceMessages.POST_FAILED); } return response; }
@Path("download") @GET @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) public Response retriveDataForDownload( @Context final UriInfo uriInfo, @QueryParam("source") final String source, @QueryParam("status") final String status, @QueryParam("fromDate") final Long start, @QueryParam("toDate") final Long end) throws IOException { this.context.authenticatedUser().validateHasReadPermission(resourceNameForPermissions); /** have to convert from and to date to format like 2014-06-15 */ Date fDate = new Date(start); Date tDate = new Date(end); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String fromDate = df.format(fDate); String toDate = df.format(tDate); List<PaymentGatewayDownloadData> paymentData = readPlatformService.retriveDataForDownload(source, fromDate, toDate, status); /** receiptNo serialNumber paymentDate amountPaid PhoneMSISDN Remarks status */ boolean statusSuccess = false; if (status.equalsIgnoreCase("Success")) statusSuccess = true; StringBuilder builder = new StringBuilder(); if (statusSuccess) { builder.append( "Receipt No, Serial No, Payment Date, Amount Paid, Payment Id, Phone MSISDN, Remarks, Status \n"); } else { builder.append( "Receipt No, Serial No, Payment Date, Amount Paid, Phone MSISDN, Remarks, Status \n"); } for (PaymentGatewayDownloadData data : paymentData) { builder.append(data.getReceiptNo() + ","); builder.append(data.getSerialNo() + ","); builder.append(data.getPaymendDate() + ","); builder.append(data.getAmountPaid() + ","); if (statusSuccess) { builder.append(data.getPaymentId() + ","); } builder.append(data.getPhoneMSISDN() + ","); builder.append(data.getRemarks() + ","); builder.append(data.getStatus()); builder.append("\n"); } statusSuccess = false; String fileLocation = System.getProperty("java.io.tmpdir") + File.separator + "billing" + File.separator + "" + source + "" + System.currentTimeMillis() + status + ".csv"; String dirLocation = System.getProperty("java.io.tmpdir") + File.separator + "billing"; File dir = new File(dirLocation); if (!dir.exists()) { dir.mkdir(); } File file = new File(fileLocation); if (!file.exists()) { file.createNewFile(); } FileUtils.writeStringToFile(file, builder.toString()); final ResponseBuilder response = Response.ok(file); response.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); response.header("Content-Type", "application/csv"); return response.build(); /*String toJson = gson.toJson(paymentData); JSONArray arry = null; try { arry = new JSONArray(toJson); } catch (JSONException e) { e.printStackTrace(); } System.out.println(arry); String json = this.toApiJsonSerializer.serialize(paymentData); File file=new File("/home/rakesh/Desktop/demo.csv"); String csv = null; try { csv = CDL.toString(arry); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } FileUtils.writeStringToFile(file, csv);*/ // return this.toApiJsonSerializer.serialize(paymentData); }