List of usage examples for java.net URLConnection getFileNameMap
public static FileNameMap getFileNameMap()
From source file:de.mpg.mpdl.inge.pubman.web.multipleimport.processor.ZfNProcessor.java
/** * Converts an inputstream into a FileVO. * /* w ww . j ava2 s . c o m*/ * @param file * @param name * @param user * @return FileVO * @throws Exception */ private FileVO createPubFile(InputStream in, AccountUserVO user) throws Exception { this.logger.debug("Creating PubFile: " + this.getCurrentFile()); MdsFileVO mdSet = new MdsFileVO(); FileVO fileVO = new FileVO(); FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(this.getCurrentFile()); URL fileURL = this.uploadFile(in, mimeType, user.getHandle()); if (fileURL != null && !fileURL.toString().trim().equals("")) { fileVO.setStorage(FileVO.Storage.INTERNAL_MANAGED); fileVO.setVisibility(FileVO.Visibility.PUBLIC); fileVO.setDefaultMetadata(mdSet); fileVO.getDefaultMetadata().setTitle(this.getCurrentFile()); fileVO.setMimeType(mimeType); fileVO.setName(this.getCurrentFile()); fileVO.setContent(fileURL.toString()); System.out.println("SIZE:" + this.fileSize); fileVO.getDefaultMetadata().setSize(this.fileSize); String contentCategory = null; if (PubFileVOPresentation.getContentCategoryUri("PUBLISHER_VERSION") != null) { contentCategory = PubFileVOPresentation.getContentCategoryUri("PUBLISHER_VERSION"); } else { Map<String, String> contentCategoryMap = PubFileVOPresentation.getContentCategoryMap(); if (contentCategoryMap != null && !contentCategoryMap.entrySet().isEmpty()) { contentCategory = contentCategoryMap.values().iterator().next(); } else { Logger.getLogger(PubFileVOPresentation.class) .warn("WARNING: no content-category has been defined in Genres.xml"); } } fileVO.setContentCategory(contentCategory); fileVO.getDefaultMetadata().setLicense(this.getConfig().get("License")); FormatVO formatVO = new FormatVO(); formatVO.setType("dcterms:IMT"); formatVO.setValue(mimeType); fileVO.getDefaultMetadata().getFormats().add(formatVO); } this.setCurrentFile(""); this.fileNames.remove(0); return fileVO; }
From source file:edu.umd.cs.submitServer.servlets.UploadSubmission.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { long now = System.currentTimeMillis(); Timestamp submissionTimestamp = new Timestamp(now); // these are set by filters or previous servlets Project project = (Project) request.getAttribute(PROJECT); StudentRegistration studentRegistration = (StudentRegistration) request.getAttribute(STUDENT_REGISTRATION); MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST); boolean webBasedUpload = ((Boolean) request.getAttribute("webBasedUpload")).booleanValue(); String clientTool = multipartRequest.getCheckedParameter("submitClientTool"); String clientVersion = multipartRequest.getOptionalCheckedParameter("submitClientVersion"); String cvsTimestamp = multipartRequest.getOptionalCheckedParameter("cvstagTimestamp"); Collection<FileItem> files = multipartRequest.getFileItems(); Kind kind;/*from ww w. j ava 2s . c o m*/ byte[] zipOutput = null; // zipped version of bytesForUpload boolean fixedZip = false; try { if (files.size() > 1) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos); for (FileItem item : files) { String name = item.getName(); if (name == null || name.length() == 0) continue; byte[] bytes = item.get(); ZipEntry zentry = new ZipEntry(name); zentry.setSize(bytes.length); zentry.setTime(now); zos.putNextEntry(zentry); zos.write(bytes); zos.closeEntry(); } zos.flush(); zos.close(); zipOutput = bos.toByteArray(); kind = Kind.MULTIFILE_UPLOAD; } else { FileItem fileItem = multipartRequest.getFileItem(); if (fileItem == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "There was a problem processing your submission. " + "No files were found in your submission"); return; } // get size in bytes long sizeInBytes = fileItem.getSize(); if (sizeInBytes == 0 || sizeInBytes > Integer.MAX_VALUE) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Trying upload file of size " + sizeInBytes); return; } // copy the fileItem into a byte array byte[] bytesForUpload = fileItem.get(); String fileName = fileItem.getName(); boolean isSpecialSingleFile = OfficeFileName.matcher(fileName).matches(); FormatDescription desc = FormatIdentification.identify(bytesForUpload); if (!isSpecialSingleFile && desc != null && desc.getMimeType().equals("application/zip")) { fixedZip = FixZip.hasProblem(bytesForUpload); kind = Kind.ZIP_UPLOAD; if (fixedZip) { bytesForUpload = FixZip.fixProblem(bytesForUpload, studentRegistration.getStudentRegistrationPK()); kind = Kind.FIXED_ZIP_UPLOAD; } zipOutput = bytesForUpload; } else { // ========================================================================================== // [NAT] [Buffer to ZIP Part] // Check the type of the upload and convert to zip format if // possible // NOTE: I use both MagicMatch and FormatDescription (above) // because MagicMatch was having // some trouble identifying all zips String mime = URLConnection.getFileNameMap().getContentTypeFor(fileName); if (!isSpecialSingleFile && mime == null) try { MagicMatch match = Magic.getMagicMatch(bytesForUpload, true); if (match != null) mime = match.getMimeType(); } catch (Exception e) { // leave mime as null } if (!isSpecialSingleFile && "application/zip".equalsIgnoreCase(mime)) { zipOutput = bytesForUpload; kind = Kind.ZIP_UPLOAD2; } else { InputStream ins = new ByteArrayInputStream(bytesForUpload); if ("application/x-gzip".equalsIgnoreCase(mime)) { ins = new GZIPInputStream(ins); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(bos); if (!isSpecialSingleFile && ("application/x-gzip".equalsIgnoreCase(mime) || "application/x-tar".equalsIgnoreCase(mime))) { kind = Kind.TAR_UPLOAD; TarInputStream tins = new TarInputStream(ins); TarEntry tarEntry = null; while ((tarEntry = tins.getNextEntry()) != null) { zos.putNextEntry(new ZipEntry(tarEntry.getName())); tins.copyEntryContents(zos); zos.closeEntry(); } tins.close(); } else { // Non-archive file type if (isSpecialSingleFile) kind = Kind.SPECIAL_ZIP_FILE; else kind = Kind.SINGLE_FILE; // Write bytes to a zip file ZipEntry zentry = new ZipEntry(fileName); zos.putNextEntry(zentry); zos.write(bytesForUpload); zos.closeEntry(); } zos.flush(); zos.close(); zipOutput = bos.toByteArray(); } // [END Buffer to ZIP Part] // ========================================================================================== } } } catch (NullPointerException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "There was a problem processing your submission. " + "You should submit files that are either zipped or jarred"); return; } finally { for (FileItem fItem : files) fItem.delete(); } if (webBasedUpload) { clientTool = "web"; clientVersion = kind.toString(); } Submission submission = uploadSubmission(project, studentRegistration, zipOutput, request, submissionTimestamp, clientTool, clientVersion, cvsTimestamp, getDatabaseProps(), getSubmitServerServletLog()); request.setAttribute("submission", submission); if (!webBasedUpload) { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println("Successful submission #" + submission.getSubmissionNumber() + " received for project " + project.getProjectNumber()); out.flush(); out.close(); return; } boolean instructorUpload = ((Boolean) request.getAttribute("instructorViewOfStudent")).booleanValue(); // boolean // isCanonicalSubmission="true".equals(request.getParameter("isCanonicalSubmission")); // set the successful submission as a request attribute String redirectUrl; if (fixedZip) { redirectUrl = request.getContextPath() + "/view/fixedSubmissionUpload.jsp?submissionPK=" + submission.getSubmissionPK(); } if (project.getCanonicalStudentRegistrationPK() == studentRegistration.getStudentRegistrationPK()) { redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK=" + project.getProjectPK(); } else if (instructorUpload) { redirectUrl = request.getContextPath() + "/view/instructor/project.jsp?projectPK=" + project.getProjectPK(); } else { redirectUrl = request.getContextPath() + "/view/project.jsp?projectPK=" + project.getProjectPK(); } response.sendRedirect(redirectUrl); }
From source file:com.asto.move.util.qcloud.pic.PicCloud.java
public int Upload(String fileName, String fileid, PicAnalyze flag, UploadResult result) { if ("".equals(fileName)) { return SetError(-1, "invalid file name"); }/*w w w .j a v a2 s .c om*/ String req_url = GetUrl(fileid); String BOUNDARY = "---------------------------abcdefg1234567"; String rsp = ""; //check analyze flag String query_string = ""; if (flag.fuzzy != 0) { query_string += ".fuzzy"; } if (flag.food != 0) { query_string += ".food"; } if ("".equals(query_string) == false) { req_url += "?analyze=" + query_string.substring(1); } // System.out.println("url=" + req_url); // create sign long expired = System.currentTimeMillis() / 1000 + 600; String sign = FileCloudSign.appSignV2(m_appid, m_secret_id, m_secret_key, m_bucket, expired); if (null == sign) { return SetError(-1, "create app sign failed"); } // System.out.println("sign=" + sign); try { URL realUrl = new URL(req_url); HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); // set header connection.setRequestMethod("POST"); connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("Host", "web.image.myqcloud.com"); connection.setRequestProperty("user-agent", "qcloud-java-sdk"); connection.setRequestProperty("Authorization", sign); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(connection.getOutputStream()); StringBuilder strBuf = new StringBuilder(); if (fileName != null) { File file = new File(fileName); String filename = file.getName(); String contentType = URLConnection.getFileNameMap().getContentTypeFor(fileName); strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"FileContent\"; filename=\"").append(fileName) .append("\"\r\n"); strBuf.append("Content-Type:").append(contentType).append("\r\n\r\n"); out.write(strBuf.toString().getBytes()); DataInputStream ins = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = ins.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } } byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); out.write(endData); out.flush(); out.close(); connection.connect(); rsp = GetResponse(connection); } catch (Exception e) { return SetError(-1, "url exception, e=" + e.toString()); } System.out.println("rsp=" + rsp); try { JSONObject jsonObject = new JSONObject(rsp); int code = jsonObject.getInt("code"); String msg = jsonObject.getString("message"); if (0 != code) { return SetError(code, msg); } result.url = jsonObject.getJSONObject("data").getString("url"); result.download_url = jsonObject.getJSONObject("data").getString("download_url"); result.fileid = jsonObject.getJSONObject("data").getString("fileid"); if (jsonObject.getJSONObject("data").has("is_fuzzy")) { result.analyze.fuzzy = jsonObject.getJSONObject("data").getInt("is_fuzzy"); } if (jsonObject.getJSONObject("data").has("is_food")) { result.analyze.food = jsonObject.getJSONObject("data").getInt("is_food"); } } catch (JSONException e) { return SetError(-1, "json exception, e=" + e.toString()); } return SetError(0, "success"); }
From source file:org.fao.unredd.portal.ApplicationController.java
@RequestMapping("/static/**") public void getCustomStaticFile(HttpServletRequest request, HttpServletResponse response) throws IOException { // Get path to file String fileName = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); // Verify file exists File file = new File(config.getDir() + "/static/" + fileName); if (!file.isFile()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;//from w w w . jav a 2s .c o m } // Manage cache headers: Last-Modified and If-Modified-Since long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long lastModified = file.lastModified(); if (ifModifiedSince >= (lastModified / 1000 * 1000)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } response.setDateHeader("Last-Modified", lastModified); // Set content type FileNameMap fileNameMap = URLConnection.getFileNameMap(); String type = fileNameMap.getContentTypeFor(fileName); response.setContentType(type); // Send contents try { InputStream is = new FileInputStream(file); IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); } catch (IOException e) { logger.error("Error reading file", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:se.mithlond.services.content.model.articles.media.BitmapImage.java
/** * Creates a BitmapImage originating from a File. * * @param resourcePath The resource path to an image file. * @return The converted and created BitmapImage. */// w w w. j a v a2 s . c o m public static BitmapImage createFromResourcePath(final String resourcePath) { // Check sanity Validate.notEmpty(resourcePath, "resourcePath"); final URL resource = Thread.currentThread().getContextClassLoader().getResource(resourcePath); if (resource == null) { throw new IllegalArgumentException("No resource found for resourcePath " + resourcePath); } // We will only handle "JAR" or "FILE" protocols. if (FILE_PROTOCOL.equalsIgnoreCase(resource.getProtocol())) { // Delegate return createFromFile(new File(resource.getPath())); } if (!JAR_PROTOCOL.equalsIgnoreCase(resource.getProtocol())) { throw new IllegalArgumentException("Will only handle 'JAR' protocol URLs."); } // // Ensure that the URI targets a single image file. // The typical URI should look like the following: // // jar:file:/some/path/to/images.jar!/images/example_png.png // final String jarProtocolStart = JAR_PROTOCOL + ":"; final String innerProtocolStringForm = resource.toString() .substring(resource.toString().indexOf(jarProtocolStart) + jarProtocolStart.length()); if (!innerProtocolStringForm.trim().toLowerCase().startsWith(FILE_PROTOCOL + ":")) { throw new IllegalArgumentException( "Expected sub-protocol 'file:' within the JAR file., but got: " + innerProtocolStringForm); } final String internalJarPath = innerProtocolStringForm.substring(innerProtocolStringForm.indexOf("!") + 1); // Harmonize and validate the image file name. final String fileName = internalJarPath.substring(internalJarPath.lastIndexOf("/") + 1); final String harmonizedFileName = validateAndHarmonizeName(fileName); // Find the Mime type of the image. final FileNameMap fileNameMap = URLConnection.getFileNameMap(); final String mimeType = fileNameMap.getContentTypeFor(harmonizedFileName); // Read the image data from the JarEntry final byte[] data; final BufferedImage bufferedImage; try { data = IOUtils.toByteArray(resource.openStream()); bufferedImage = ImageIO.read(new ByteArrayInputStream(data)); } catch (IOException e) { throw new IllegalArgumentException("Could not read image data from [" + resource.toString() + "]", e); } // All Done. return new BitmapImage(harmonizedFileName, bufferedImage.getWidth(), bufferedImage.getHeight(), mimeType, data); }
From source file:org.dataconservancy.ui.it.FileHttpAPIIT.java
@Before public void setUp() throws Exception { adminUserLogin = reqFactory.createLoginRequest(adminUser).asHttpPost(); defaultUserLogin = reqFactory.createLoginRequest(defaultUser).asHttpPost(); approvedUserLogin = reqFactory.createLoginRequest(approvedUser).asHttpPost(); logout = reqFactory.createLogoutRequest().asHttpGet(); if (!areObjectsSeeded) { log.trace("Seeding objects ..."); HttpAssert.assertStatus(httpClient, adminUserLogin, 300, 399, "Unable to login as admin user!"); // A generic project with adminUser as a PI project = new Project(); project.setName("FileHttpAPIIT Test Project"); project.setDescription("Test Project For TestHttpAPIIT"); project.addNumber("123456"); project.setFundingEntity("Cash"); project.setStartDate(new DateTime(2012, 6, 13, 0, 0)); project.setEndDate(new DateTime(2013, 6, 13, 0, 0)); project.addPi(adminUser.getId()); project = reqFactory.createProjectApiAddRequest(project).execute(httpClient); log.trace("Seeded Project, id {}", project.getId()); log.trace(project.toString());// ww w. j a v a2 s . c om // A generic collection with approvedUser as a depositor collection = new Collection(); collection.setTitle("FileHttpAPIIT Test Collection"); collection.setSummary("Test Collection for TestHttpAPIIT"); collection.setId(reqFactory.createIdApiRequest(COLLECTION).execute(httpClient)); List<PersonName> creators = new ArrayList<PersonName>(); creators.add(new PersonName("Mr.", "John", "Jack", "Doe", "II")); collection.setCreators(creators); httpClient.execute(reqFactory.createCollectionRequest(collection, project).asHttpPost()).getEntity() .getContent().close(); HttpAssert.assertStatus(httpClient, new HttpGet(urlConfig.getViewCollectionUrl(collection.getId()).toURI()), 200, "Unable to create collection " + collection); log.trace("Seeded Collection, id {}", collection.getId()); log.trace(collection.toString()); httpClient.execute( reqFactory.createSetNewDepositorRequest(approvedUser.getId(), collection.getId()).asHttpPost()) .getEntity().getContent().close(); log.trace("Added depositor {} to Collection {}", approvedUser.getId(), collection.getId()); java.io.File tempFile = new java.io.File(FileHttpAPIIT.class.getResource(LINUX_FILE_ZIP_PATH).toURI()); dataFileContents = IOUtils.toByteArray(new FileInputStream(tempFile)); dataFileLengh = tempFile.length(); dataFile = new DataFile(null, tempFile.getName(), tempFile.toURI().toURL().toExternalForm(), URLConnection.getFileNameMap().getContentTypeFor(tempFile.getName()), tempFile.getPath(), tempFile.length(), new ArrayList<String>()); // A list of data files List<DataFile> dataFileList = new ArrayList<DataFile>(); dataFileList.add(dataFile); // A dataset to contain the data file dataSetDateTime = DateTime.now(); dataItem = new DataItem("FileHttpAPIIT Test DataItem", "Test DataItem for TestHttpAPIIT", reqFactory.createIdApiRequest(DATA_SET).execute(httpClient), approvedUser.getId(), dataSetDateTime, dataFileList, new ArrayList<String>(), collection.getId()); dataItem.setParentId(collection.getId()); dataFile.setParentId(dataItem.getId()); log.trace("Created DataItem with name {} and id {}", dataItem.getName(), dataItem.getId()); log.trace(dataItem.toString()); log.trace("DataItem ({}, {}) files:", dataItem.getName(), dataItem.getId()); for (DataFile f : dataItem.getFiles()) { log.trace("File id {}, name {}", f.getId(), f.getName()); } org.dataconservancy.ui.model.Package thePackage = new org.dataconservancy.ui.model.Package(); updatePackageId = reqFactory.createIdApiRequest(PACKAGE).execute(httpClient); thePackage.setId(updatePackageId); log.trace("Created Package, id {}", thePackage.getId()); log.trace(thePackage.toString()); httpClient.execute(reqFactory .createSingleFileDataItemDepositRequest(thePackage, dataItem, collection.getId(), tempFile) .asHttpPost()).getEntity().getContent().close(); // The Following construct seems suspicious. I am able to pull the // dataset from the archive via pollAndQueryArchiveForDataset, but // still end up making multiple calls to the getDepositStatusUrl // before I get back a deposited response. // I am, however, going to leave it be for now. dataItem = archiveSupport.pollAndQueryArchiveForDataItem(dataItem.getId()); String content; tryCount = 0; do { HttpResponse response = httpClient .execute(new HttpGet(urlConfig.getDepositStatusUrl(thePackage.getId()).toURI())); content = IOUtils.toString(response.getEntity().getContent()); Thread.sleep(1000L); } while (!content.contains("DEPOSITED") && tryCount++ < maxTries); log.trace("Seeded Package {} and DataItem {}, {}", new Object[] { thePackage.getId(), dataItem.getId(), dataItem.getName() }); log.trace(dataItem.toString()); for (DataFile f : dataItem.getFiles()) { log.trace(f.toString()); } // This is the datafile/dataset used in the deprecated file scenario java.io.File tempFileToUpdate = java.io.File.createTempFile("FileToUpdateHttpAPIIT", ".txt"); tempFileToUpdate.deleteOnExit(); PrintWriter updatedOut = new PrintWriter(tempFileToUpdate); dataFileToUpdateContents = "Can haz data? Again."; updatedOut.print(dataFileToUpdateContents); updatedOut.close(); dataFileToUpdate = new DataFile(null, tempFileToUpdate.getName(), tempFileToUpdate.toURI().toURL().toExternalForm(), URLConnection.getFileNameMap().getContentTypeFor(tempFileToUpdate.getName()), tempFileToUpdate.getPath(), tempFileToUpdate.getTotalSpace(), new ArrayList<String>()); // A list of data files List<DataFile> dataFileListToUpdate = new ArrayList<DataFile>(); dataFileListToUpdate.add(dataFileToUpdate); // A dataset to contain the data file dataSetDateTime = DateTime.now(); dataSetToUpdate = new DataItem("FileToUpdateHttpAPIIT Test DataItem", "Test DataItem to update for TestHttpAPIIT", reqFactory.createIdApiRequest(DATA_SET).execute(httpClient), approvedUser.getId(), dataSetDateTime, dataFileListToUpdate, new ArrayList<String>(), collection.getId()); dataSetToUpdate.setParentId(collection.getId()); dataFileToUpdate.setParentId(dataSetToUpdate.getId()); log.trace("Created DataItem with name {} and id {}", dataSetToUpdate.getName(), dataSetToUpdate.getId()); log.trace(dataSetToUpdate.toString()); log.trace("DataItem ({}, {}) files:", dataSetToUpdate.getName(), dataSetToUpdate.getId()); for (DataFile f : dataSetToUpdate.getFiles()) { log.trace("File id {}, name {}", f.getId(), f.getName()); } org.dataconservancy.ui.model.Package packageToUpdate = new org.dataconservancy.ui.model.Package(); packageToUpdate.setId(reqFactory.createIdApiRequest(PACKAGE).execute(httpClient)); httpClient.execute(reqFactory.createSingleFileDataItemDepositRequest(packageToUpdate, dataSetToUpdate, collection.getId(), tempFileToUpdate).asHttpPost()).getEntity().getContent().close(); dataSetToUpdate = archiveSupport.pollAndQueryArchiveForDataItem(dataSetToUpdate.getId()); tryCount = 0; do { HttpResponse response = httpClient .execute(new HttpGet(urlConfig.getDepositStatusUrl(packageToUpdate.getId()).toURI())); content = IOUtils.toString(response.getEntity().getContent()); Thread.sleep(1000L); } while (!content.contains("DEPOSITED") && tryCount++ < maxTries); log.trace("Seeded Package {} and DataItem {}, {}", new Object[] { thePackage.getId(), dataSetToUpdate.getId(), dataSetToUpdate.getName() }); log.trace(dataSetToUpdate.toString()); for (DataFile f : dataSetToUpdate.getFiles()) { log.trace(f.toString()); } httpClient.execute(logout).getEntity().getContent().close(); areObjectsSeeded = true; } }
From source file:com.openmeap.services.ApplicationManagementServlet.java
private Result handleArchiveDownload(HttpServletRequest request, HttpServletResponse response) { Result res = new Result(); Error err = new Error(); res.setError(err);/* www .ja v a2 s .c o m*/ GlobalSettings settings = modelManager.getGlobalSettings(); Map properties = this.getServicesWebProperties(); String nodeKey = (String) properties.get("clusterNodeUrlPrefix"); ClusterNode clusterNode = settings.getClusterNode(nodeKey); if (nodeKey == null || clusterNode == null) { // TODO: create a configuration error code err.setCode(ErrorCode.UNDEFINED); err.setMessage("A configuration is missing. Please consult the error logs."); logger.error( "For each node in the cluster, the property or environment variable OPENMEAP_CLUSTER_NODE_URL_PREFIX must match the \"Service Url Prefix\" value configured in the administrative interface. This value is currently " + nodeKey + "."); return res; } String pathValidation = clusterNode.validateFileSystemStoragePathPrefix(); if (pathValidation != null) { err.setCode(ErrorCode.UNDEFINED); err.setMessage("A configuration is missing. Please consult the error logs."); logger.error( "There is an issue with the location at \"File-system Storage Prefix\". " + pathValidation); return res; } String hash = request.getParameter(UrlParamConstants.APPARCH_HASH); String hashAlg = request.getParameter(UrlParamConstants.APPARCH_HASH_ALG); String fileName = null; if (hash == null || hashAlg == null) { // look in the apps directory for the archive specified String appName = request.getParameter(UrlParamConstants.APP_NAME); String versionId = request.getParameter(UrlParamConstants.APP_VERSION); ApplicationVersion appVersion = modelManager.getModelService().findAppVersionByNameAndId(appName, versionId); if (appVersion == null) { String mesg = "The application version " + versionId + " was not found for application " + appName; err.setCode(ErrorCode.APPLICATION_VERSION_NOTFOUND); err.setMessage(mesg); logger.warn(mesg); return res; } String auth = request.getParameter(UrlParamConstants.AUTH_TOKEN); com.openmeap.model.dto.Application app = appVersion.getApplication(); try { if (auth == null || !AuthTokenProvider.validateAuthToken(app.getProxyAuthSalt(), auth)) { err.setCode(ErrorCode.AUTHENTICATION_FAILURE); err.setMessage("The \"auth\" token presented is not recognized, missing, or empty."); return res; } } catch (DigestException e) { throw new GenericRuntimeException(e); } hash = appVersion.getArchive().getHash(); hashAlg = appVersion.getArchive().getHashAlgorithm(); fileName = app.getName() + " - " + appVersion.getIdentifier(); } else { fileName = hashAlg + "-" + hash; } File file = ApplicationArchive.getFile(clusterNode.getFileSystemStoragePathPrefix(), hashAlg, hash); if (!file.exists()) { String mesg = "The application archive with " + hashAlg + " hash " + hash + " was not found."; // TODO: create an enumeration for this error err.setCode(ErrorCode.UNDEFINED); err.setMessage(mesg); logger.warn(mesg); return res; } try { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(file.toURL().toString()); response.setContentType(mimeType); response.setContentLength(Long.valueOf(file.length()).intValue()); URLCodec codec = new URLCodec(); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".zip\";"); InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(file)); outputStream = response.getOutputStream(); Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream); } finally { if (inputStream != null) { inputStream.close(); } //if(outputStream!=null) {outputStream.close();} } response.flushBuffer(); } catch (FileNotFoundException e) { logger.error("Exception {}", e); } catch (IOException ioe) { logger.error("Exception {}", ioe); } return null; }
From source file:se.mithlond.services.content.model.articles.media.BitmapImage.java
/** * Creates a BitmapImage originating from a File. * * @param imageFile The File pointing to an Image. * @return The converted and created BitmapImage. *///from ww w . j a va 2 s. com public static BitmapImage createFromFile(final File imageFile) { // Check sanity final File file = Validate.notNull(imageFile, "imageFile"); // Replace whitespace with '_' and make the name lowercase. final String harmonizedFileName = validateAndHarmonizeName(file.getName()); // Read the data, and convert it to a BufferedImage. final byte[] bytes; final BufferedImage bufferedImage; try { bytes = Files.readAllBytes(file.toPath()); bufferedImage = ImageIO.read(new ByteArrayInputStream(bytes)); } catch (IOException e) { // Complain. throw new IllegalArgumentException("Could not create a BufferedImage from file [" + imageFile.getName() + "] with the harmonized name [" + harmonizedFileName + "]", e); } // Find the Mime type of the image. final FileNameMap fileNameMap = URLConnection.getFileNameMap(); final String mimeType = fileNameMap.getContentTypeFor(harmonizedFileName); // All Done. return new BitmapImage(harmonizedFileName, bufferedImage.getWidth(), bufferedImage.getHeight(), mimeType, bytes); }
From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceImpl.java
private OwncloudLocalResourceExtension createOwncloudResourceOf(Path path) { Path rootPath = getRootLocationOfAuthenticatedUser(); Path relativePath = rootPath.toAbsolutePath().relativize(path.toAbsolutePath()); URI href = URI.create(UriComponentsBuilder.fromPath("/").path(relativePath.toString()).toUriString()); String name = path.getFileName().toString(); MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM; if (Files.isDirectory(path)) { href = URI.create(UriComponentsBuilder.fromUri(href).path("/").toUriString()); mediaType = OwncloudUtils.getDirectoryMediaType(); } else {/*from w w w. j a v a 2 s. c om*/ FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentType = fileNameMap.getContentTypeFor(path.getFileName().toString()); if (StringUtils.isNotBlank(contentType)) { mediaType = MediaType.valueOf(contentType); } } try { LocalDateTime lastModifiedAt = LocalDateTime.ofInstant(Files.getLastModifiedTime(path).toInstant(), ZoneId.systemDefault()); Optional<String> checksum = checksumService.getChecksum(path); if (Files.isSameFile(rootPath, path)) { name = "/"; checksum = Optional.empty(); } OwncloudLocalResourceExtension resource = OwncloudLocalResourceImpl.builder().href(href).name(name) .eTag(checksum.orElse(null)).mediaType(mediaType).lastModifiedAt(lastModifiedAt).build(); if (Files.isDirectory(path)) { return resource; } return OwncloudLocalFileResourceImpl.fileBuilder().owncloudResource(resource) .contentLength(Files.size(path)).build(); } catch (NoSuchFileException e) { throw new OwncloudResourceNotFoundException(href, getUsername()); } catch (IOException e) { val logMessage = String.format("Cannot create OwncloudResource from Path %s", path); log.error(logMessage, e); throw new OwncloudLocalResourceException(logMessage, e); } }
From source file:org.stirrat.ecm.speedyarchiver.SpeedyArchiverServices.java
/** * Returns a zip to the browser as a download option * /*from ww w . ja v a 2 s. c om*/ * @param file * The zip file * @param httpImpl * The service http object * @throws IOException */ public void attachFileToHttpResponse(File file, HttpImplementor httpImpl, DataBinder binder) throws ServiceException, IOException { String mimeType = URLConnection.getFileNameMap().getContentTypeFor(file.getName()); byte[] byteArray = getFileBytes(file); ByteArrayInputStream fileInputStream = new ByteArrayInputStream(byteArray); DataStreamWrapper dsw = new DataStreamWrapper(); dsw.initWithInputStream(fileInputStream, byteArray.length); dsw.m_clientFileName = file.getName(); if (mimeType != null) { dsw.m_dataType = mimeType; } else { dsw.m_dataType = "attachment"; } binder.putLocal("noSaveAs", "true"); httpImpl.sendStreamResponse(binder, dsw); }