List of usage examples for org.springframework.http HttpHeaders setContentLength
public void setContentLength(long contentLength)
From source file:ca.intelliware.ihtsdo.mlds.web.rest.MemberResource.java
private ResponseEntity<?> downloadFile(HttpServletRequest request, File file) throws SQLException, IOException { if (file == null) { return new ResponseEntity<>(HttpStatus.NO_CONTENT); } else if (file.getLastUpdated() != null) { long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long lastUpdatedSecondsFloor = file.getLastUpdated().getMillis() / 1000 * 1000; if (ifModifiedSince != -1 && lastUpdatedSecondsFloor <= ifModifiedSince) { return new ResponseEntity<>(HttpStatus.NOT_MODIFIED); }// w w w . ja v a 2 s . c om } HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.valueOf(file.getMimetype())); httpHeaders.setContentLength(file.getContent().length()); httpHeaders.setContentDispositionFormData("file", file.getFilename()); if (file.getLastUpdated() != null) { httpHeaders.setLastModified(file.getLastUpdated().getMillis()); } byte[] byteArray = IOUtils.toByteArray(file.getContent().getBinaryStream()); org.springframework.core.io.Resource contents = new ByteArrayResource(byteArray); return new ResponseEntity<org.springframework.core.io.Resource>(contents, httpHeaders, HttpStatus.OK); }
From source file:bibibi.controllers.CitationsController.java
@RequestMapping(value = "/export", method = RequestMethod.GET) public HttpEntity<FileSystemResource> getFile() throws IOException { BibWriter bw = new BibWriter("export", this.citationRepository.findAll()); bw.writeFile();// w w w. j ava 2 s . c o m HttpHeaders header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_OCTET_STREAM); header.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + bw.getFile().getName()); header.setContentLength(bw.getFile().length()); return new HttpEntity<>(new FileSystemResource(bw.getFile()), header); }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandlerTest.java
/** * Tests {@link ApiResponseErrorHandler#handleError} in the case where the error response body is empty, e.g. because * it is returned by an intermediate web proxy. * // w w w. j a va 2 s. c om * @throws Exception If an unexpected error occurs. */ @Test public void testHandleErrorWhenResponseBodyEmpty() throws Exception { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentLength(0); String body = null; ClientHttpResponse response = this.createMockClientHttpResponse(HttpStatus.GATEWAY_TIMEOUT, httpHeaders, body); EasyMock.replay(response); try { this.errorHandler.handleError(response); fail("Expected exception to be thrown for error response."); } catch (ApiErrorResponseException e) { ApiError apiError = null; ApiErrorResponseException expectedException = new ApiErrorResponseException(response.getRawStatusCode(), null, httpHeaders, null, new byte[0], apiError); assertApiErrorResponseException(expectedException, e); } }
From source file:org.zlogic.vogon.web.controller.DataController.java
/** * Returns all data//from w w w . j a v a 2s .com * * @param userPrincipal the authenticated user * @return the HTTPEntity for the file download */ @RequestMapping(value = "/export/xml", method = { RequestMethod.GET, RequestMethod.POST }) public HttpEntity<byte[]> exportDataXML(@AuthenticationPrincipal VogonSecurityUser userPrincipal) throws RuntimeException { VogonUser user = userRepository.findByUsernameIgnoreCase(userPrincipal.getUsername()); try { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); XmlExporter exporter = new XmlExporter(outStream); Sort accountSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N Sort transactionSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N exporter.exportData(user, accountRepository.findByOwner(user, accountSort), transactionRepository.findByOwner(user, transactionSort), null); String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()); //NOI18N HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_XML); headers.setContentLength(outStream.size()); headers.setContentDispositionFormData("attachment", "vogon-" + date + ".xml"); //NOI18N //NOI18N return new HttpEntity<>(outStream.toByteArray(), headers); } catch (VogonExportException ex) { throw new RuntimeException(ex); } }
From source file:org.zlogic.vogon.web.controller.DataController.java
/** * Returns all data// www .jav a 2 s . c om * * @param userPrincipal the authenticated user * @return the HTTPEntity for the file download */ @RequestMapping(value = "/export/json", method = { RequestMethod.GET, RequestMethod.POST }) public HttpEntity<byte[]> exportDataJSON(@AuthenticationPrincipal VogonSecurityUser userPrincipal) throws RuntimeException { VogonUser user = userRepository.findByUsernameIgnoreCase(userPrincipal.getUsername()); try { ClassExporter exporter = new ClassExporter(); Sort accountSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N Sort transactionSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));//NOI18N exporter.exportData(user, accountRepository.findByOwner(user, accountSort), transactionRepository.findByOwner(user, transactionSort), null); ExportedData exportedData = exporter.getExportedData(); //Process transactions for JSON List<FinanceTransactionJson> processedTransactions = initializationHelper .initializeTransactions(exportedData.getTransactions()); exportedData.getTransactions().clear(); for (FinanceTransactionJson transaction : processedTransactions) exportedData.getTransactions().add(transaction); //Convert to JSON byte[] output = jsonMapper.writer().withDefaultPrettyPrinter().writeValueAsString(exportedData) .getBytes("utf-8"); //NOI18N String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()); //NOI18N HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.setContentLength(output.length); headers.setContentDispositionFormData("attachment", "vogon-" + date + ".json"); //NOI18N //NOI18N return new HttpEntity<>(output, headers); } catch (VogonExportException | IOException ex) { throw new RuntimeException(ex); } }
From source file:com.iflytek.edu.cloud.frame.spring.RequestResponseBodyMethodProcessorExt.java
private void write(final String content, MediaType contentType, ServletServerHttpResponse outputMessage) throws IOException, HttpMessageNotWritableException { final HttpHeaders headers = outputMessage.getHeaders(); headers.setContentType(contentType); if (headers.getContentLength() == -1) { Long contentLength = getContentLength(content, headers.getContentType()); if (contentLength != null) { headers.setContentLength(contentLength); }/* ww w. j a v a 2 s.c o m*/ } StreamUtils.copy(content, charset, outputMessage.getBody()); outputMessage.getBody().flush(); }
From source file:fr.acxio.tools.agia.alfresco.AlfrescoNodeContentWriter.java
@Override public void write(List<? extends NodeList> sData) throws RemoteException, NodePathException, VersionOperationException, FileNotFoundException { if (!sData.isEmpty()) { init();//from w w w.j av a 2 s . c o m RepositoryServiceSoapBindingStub aRepositoryService = getAlfrescoService().getRepositoryService(); for (NodeList aNodeList : sData) { for (Node aNode : aNodeList) { if (aNode instanceof Document) { Document aDocument = (Document) aNode; if ((aDocument.getContentPath() != null) && (aDocument.getContentPath().length() > 0)) { // If the document has a content path, the file must // exist File aFile = new File(aDocument.getContentPath()); if (aFile.exists() && aFile.isFile()) { String aCurrentNodePath = aNode.getPath(); String aScheme = null; String aAddress = null; String aUUID = null; if ((aNode.getUuid() != null) && !aNode.getUuid().isEmpty()) { aScheme = aNode.getScheme(); aAddress = aNode.getAddress(); aUUID = aNode.getUuid(); } if (aUUID == null) { org.alfresco.webservice.types.Node[] aMatchingNodes = getRepositoryMatchingNodes( aRepositoryService, aCurrentNodePath); if ((aMatchingNodes != null) && (aMatchingNodes.length > 0)) { if (aMatchingNodes.length > 1) { throw new VersionOperationException("Too many matching nodes"); } org.alfresco.webservice.types.Node aRepositoryNode = aMatchingNodes[0]; aScheme = aRepositoryNode.getReference().getStore().getScheme(); aAddress = aRepositoryNode.getReference().getStore().getAddress(); aUUID = aRepositoryNode.getReference().getUuid(); } } if (aUUID != null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Will upload content"); } StringBuilder aURL = new StringBuilder(getAlfrescoService().getWebappAddress()); aURL.append(URL_TEMPLATE_UPLOAD); Map<String, String> aURLVariables = new HashMap<String, String>(); aURLVariables.put(PARAM_SCHEME, aScheme); aURLVariables.put(PARAM_ADDRESS, aAddress); aURLVariables.put(PARAM_UUID, aUUID); aURLVariables.put(PARAM_NAME, aFile.getName()); aURLVariables.put(PARAM_TICKET, getAlfrescoService().getTicket()); aURLVariables.put(PARAM_ENCODING, aDocument.getEncoding()); aURLVariables.put(PARAM_MIMETYPE, aDocument.getMimeType()); HttpHeaders aHeaders = new HttpHeaders(); aHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM); aHeaders.setContentLength(aFile.length()); HttpEntity<FileSystemResource> aEntity = new HttpEntity<FileSystemResource>( new FileSystemResource(aFile), aHeaders); getRestTemplate().put(aURL.toString(), aEntity, aURLVariables); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Content uploaded"); } } else { throw new NodePathException("Cannot find the node: " + aNode.getPath()); } } else if (failIfFileNotFound) { throw new FileNotFoundException(aDocument.getContentPath()); } } } } } cleanup(); } }
From source file:us.polygon4.izzymongo.controller.AppController.java
/** * Exports database schema as FreeMind map * //from w ww . ja v a 2 s.com * @param fileName database name * @return fileName + ".mm" * @throws Exception */ @RequestMapping(value = "/export/{fileName}", method = RequestMethod.GET) public HttpEntity<byte[]> createExport(@PathVariable("fileName") String fileName) throws Exception { byte[] documentBody = null; documentBody = service.getDbSchema(fileName); fileName = fileName + ".mm"; HttpHeaders header = new HttpHeaders(); header.setContentType(new MediaType("application", "xml")); header.set("Content-Disposition", "attachment; filename=" + fileName.replace(" ", "_")); header.setContentLength(documentBody.length); return new HttpEntity<byte[]>(documentBody, header); }
From source file:net.maritimecloud.identityregistry.controllers.ServiceController.java
/** * Returns keycloak.json the service identified by the given ID * * @return a reply.../*from ww w . jav a 2 s . co m*/ * @throws McBasicRestException */ @RequestMapping(value = "/api/org/{orgMrn}/service/{serviceMrn}/jbossxml", method = RequestMethod.GET) @ResponseBody @PreAuthorize("hasRole('SERVICE_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)") public ResponseEntity<String> getServiceJbossXml(HttpServletRequest request, @PathVariable String orgMrn, @PathVariable String serviceMrn) throws McBasicRestException { Organization org = this.organizationService.getOrganizationByMrn(orgMrn); if (org != null) { // Check that the entity being queried belongs to the organization if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn) .equals(MrnUtil.getOrgShortNameFromEntityMrn(serviceMrn))) { throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS, request.getServletPath()); } Service service = this.entityService.getByMrn(serviceMrn); if (service == null) { throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ENTITY_NOT_FOUND, request.getServletPath()); } if (service.getIdOrganization().compareTo(org.getId()) == 0) { // Get the jboss xml for the client the service represents if it exists if (service.getOidcAccessType() != null && !service.getOidcAccessType().trim().isEmpty()) { keycloakAU.init(KeycloakAdminUtil.BROKER_INSTANCE); String jbossXml = keycloakAU.getClientJbossXml(service.getMrn()); HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentLength(jbossXml.length()); responseHeaders.setContentType(MediaType.APPLICATION_XML); return new ResponseEntity<>(jbossXml, responseHeaders, HttpStatus.OK); } throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.OIDC_CONF_FILE_NOT_AVAILABLE, request.getServletPath()); } throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS, request.getServletPath()); } else { throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND, request.getServletPath()); } }
From source file:com.courtalon.gigaMvcGalerie.web.ImageController.java
@RequestMapping(value = "/images/data/{id:[0-9]+}", method = RequestMethod.GET) @ResponseBody//from w w w .j a v a 2s .co m public ResponseEntity<FileSystemResource> downloadImage(@PathVariable("id") int id) { Image img = imageRepository.findOne(id); if (img == null) throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "image not found"); HttpHeaders respHeaders = new HttpHeaders(); respHeaders.setContentType(MediaType.parseMediaType(img.getContentType())); respHeaders.setContentLength(img.getFileSize()); respHeaders.setContentDispositionFormData("attachment", img.getFileName()); Optional<File> f = getImageRepository().getImageFile(img.getId()); if (f.isPresent()) { log.info("fichier pour image no " + id + " trouv"); FileSystemResource fsr = new FileSystemResource(f.get()); return new ResponseEntity<FileSystemResource>(fsr, respHeaders, HttpStatus.OK); } else { log.info("fichier pour image no " + id + " introuvable"); throw new HttpClientErrorException(HttpStatus.NOT_FOUND, "image file not found"); } }