List of usage examples for java.net URLConnection guessContentTypeFromName
public static String guessContentTypeFromName(String fname)
From source file:com.necl.core.controller.DownloadFileController.java
@RequestMapping(value = "/downloadApprovalCriteria", method = RequestMethod.GET) public void downloadApprovalCriteria(HttpServletResponse response) throws IOException, Exception { String keyFind = "PATH"; ConfigSystem configSystem = configSystemService.findByKey(keyFind); String saveDirectory = configSystem.getConfigText() + "Manual/"; File file = null;//from ww w .ja v a 2 s. c om String type = ".pdf"; String pathDirectory = saveDirectory + "ApprovalCriteria" + type; System.out.println("pthDi: " + pathDirectory); file = new File(pathDirectory); if (!file.exists()) { String errorMessage = "Sorry. The file you are looking for does not exist"; System.out.println(errorMessage); OutputStream outputStream = response.getOutputStream(); outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8"))); outputStream.close(); return; } String mimeType = URLConnection.guessContentTypeFromName(file.getName()); if (mimeType == null) { System.out.println("mimetype is not detectable, will take default"); mimeType = "application/octet-stream"; } System.out.println("mimetype : " + mimeType); response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/ response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() + "\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/ //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.setContentLength((int) file.length()); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); //Copy bytes from source to destination(outputstream in this example), closes both streams. FileCopyUtils.copy(inputStream, response.getOutputStream()); }
From source file:org.borderstone.tagtags.TTProtocolActivity.java
private void openFile(String filename) { File file = new File(Constants.csv.getFilename().getParent() + "/" + filename); if (file.exists()) { Intent newIntent = new Intent(Intent.ACTION_VIEW); String mimeType = URLConnection.guessContentTypeFromName(filename); newIntent.setDataAndType(Uri.fromFile(file), mimeType); newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try {/*w w w .j av a 2 s . co m*/ this.startActivity(newIntent); } catch (ActivityNotFoundException e) { makeText(this, "No handler for this type of file.", LENGTH_LONG).show(); } } else { makeText(this, "That file does not appear to exist on this device.", LENGTH_LONG).show(); } }
From source file:net.rptools.lib.FileUtil.java
/** * Given a URL this method determines the content type of the URL (if possible) and then returns a Reader with the * appropriate character encoding.//from w w w . ja va 2 s . c o m * * @param url * the source of the data stream * @return String representing the data * @throws IOException */ public static Reader getURLAsReader(URL url) throws IOException { InputStreamReader isr = null; URLConnection conn = null; // We're assuming character here, but it could be bytes. Perhaps we should // check the MIME type returned by the network server? conn = url.openConnection(); if (log.isDebugEnabled()) { String type = URLConnection.guessContentTypeFromName(url.getPath()); log.debug("result from guessContentTypeFromName(" + url.getPath() + ") is " + type); type = getContentType(conn.getInputStream()); // Now make a guess and change 'encoding' to match the content type... } isr = new InputStreamReader(conn.getInputStream(), "UTF-8"); return isr; }
From source file:org.eclipse.sw360.portal.portlets.projects.ProjectPortlet.java
private void downloadLicenseInfo(ResourceRequest request, ResourceResponse response) throws IOException { User user = UserCacheHolder.getUserFromRequest(request); String generatorClassName = request.getParameter(PortalConstants.LICENSE_INFO_SELECTED_OUTPUT_FORMAT); LicenseInfoService.Iface licenseInfoClient = thriftClients.makeLicenseInfoClient(); ProjectService.Iface projectClient = thriftClients.makeProjectClient(); String projectId = request.getParameter(PROJECT_ID); Map<String, Set<String>> selectedReleaseAndAttachmentIds = ProjectPortletUtils .getSelectedReleaseAndAttachmentIdsFromRequest(request); try {/* www . j a va 2s . c om*/ Project project = projectClient.getProjectById(projectId, user); String projectName = project != null ? project.getName() : "Unknown-Project"; String timestamp = SW360Utils.getCreatedOn(); OutputFormatInfo outputFormatInfo = licenseInfoClient .getOutputFormatInfoForGeneratorClass(generatorClassName); String filename = "LicenseInfo-" + projectName + "-" + timestamp + "." + outputFormatInfo.getFileExtension(); if (outputFormatInfo.isOutputBinary) { ByteBuffer licenseInfoByteBuffer = licenseInfoClient.getLicenseInfoFileForProjectAsBinary(projectId, user, generatorClassName, selectedReleaseAndAttachmentIds); byte[] licenseInfoByteArray = new byte[licenseInfoByteBuffer.remaining()]; licenseInfoByteBuffer.get(licenseInfoByteArray); String mimetype = outputFormatInfo.getMimeType(); if (isNullOrEmpty(mimetype)) { mimetype = URLConnection.guessContentTypeFromName(filename); } PortletResponseUtil.sendFile(request, response, filename, licenseInfoByteArray, mimetype); } else { PortletResponseUtil.sendFile( request, response, filename, licenseInfoClient.getLicenseInfoFileForProject(projectId, user, generatorClassName, selectedReleaseAndAttachmentIds).getBytes(), outputFormatInfo.getMimeType()); } } catch (TException e) { log.error("Error getting LicenseInfo file", e); response.setProperty(ResourceResponse.HTTP_STATUS_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); } }
From source file:org.entando.entando.apsadmin.filebrowser.FileBrowserAction.java
public String download() { try {//from w w w . j a va 2 s . co m String validatePath = this.validateFullPath(); if (null != validatePath) return validatePath; String fullPath = this.getCurrentPath() + this.getFilename(); InputStream is = this.getStorageManager().getStream(fullPath, this.getProtectedFolderBoolean()); if (null == is) { this.addActionError(this.getText("error.filebrowser.download.missingFile")); return INPUT; } this.setDownloadInputStream(is); String contentType = URLConnection.guessContentTypeFromName(this.getFilename()); this.setDownloadContentType(contentType); } catch (Throwable t) { _logger.error("error downloading file, fullPath: '{}' file: '{}'", this.getCurrentPath(), this.getFilename(), t); return FAILURE; } return SUCCESS; }
From source file:it.infn.ct.indigo.futuregateway.server.FGServerManager.java
/** * Add files into a resource on FG service. * * @param companyId The id of the instance * @param collection The name of the collection to post the new resource * @param resourceId The resource requiring the files * @param files The files to add to the resource * @param token The token of the user performing the action * @throws PortalException Cannot retrieve the server endpoint * @throws IOException Connect communicate with the server *//*from w w w . j ava2s .c o m*/ public final void submitFilesResource(final long companyId, final String collection, final String resourceId, final Map<String, InputStream> files, final String token) throws PortalException, IOException { String boundary = Long.toHexString(System.currentTimeMillis()); String crlf = "\r\n"; log.info("Adding new files to " + collection + "/" + resourceId); HttpURLConnection connection = getFGConnection(companyId, collection, resourceId + "/input", token, HttpMethods.POST, "multipart/form-data; boundary=" + boundary); try (OutputStream output = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8), true);) { for (String fName : files.keySet()) { writer.append("--" + boundary).append(crlf); writer.append("Content-Disposition: form-data; " + "name=\"file[]\"; filename=\"" + fName + "\"") .append(crlf); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fName)).append(crlf); writer.append("Content-Transfer-Encoding: binary").append(crlf); writer.append(crlf).flush(); IOUtils.copy(files.get(fName), output); writer.append(crlf).flush(); files.get(fName).close(); } writer.append("--" + boundary + "--").append(crlf).flush(); } if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Impossible to post files to the resource " + collection + "/" + resourceId + ". Server response with code: " + connection.getResponseCode()); } }
From source file:net.java.sip.communicator.service.httputil.HttpUtils.java
/** * Posts a <tt>file</tt> to the <tt>address</tt>. * @param address the address to post the form to. * @param fileParamName the name of the param for the file. * @param file the file we will send.//from ww w .j ava 2s.c o m * @param usernamePropertyName the property to use to retrieve/store * username value if protected site is hit, for username * ConfigurationService service is used. * @param passwordPropertyName the property to use to retrieve/store * password value if protected site is hit, for password * CredentialsStorageService service is used. * @return the result or null if send was not possible or * credentials ask if any was canceled. */ public static HTTPResponseResult postFile(String address, String fileParamName, File file, String usernamePropertyName, String passwordPropertyName) { DefaultHttpClient httpClient = null; try { HttpPost postMethod = new HttpPost(address); httpClient = getHttpClient(usernamePropertyName, passwordPropertyName, postMethod.getURI().getHost(), null); String mimeType = URLConnection.guessContentTypeFromName(file.getPath()); if (mimeType == null) mimeType = "application/octet-stream"; FileBody bin = new FileBody(file, mimeType); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart(fileParamName, bin); postMethod.setEntity(reqEntity); HttpEntity resEntity = executeMethod(httpClient, postMethod, null, null); if (resEntity == null) return null; return new HTTPResponseResult(resEntity, httpClient); } catch (Throwable e) { logger.error("Cannot post file to:" + address, e); } return null; }
From source file:edu.mit.mobile.android.locast.data.CastMedia.java
/** * Guesses the mime type from the URL//w ww . j a v a 2 s. co m * * @param url * @return the inferred mime type based on the file extension or null if it can't determine one */ public static String guessMimeTypeFromUrl(String url) { // this was improved in Gingerbread // http://code.google.com/p/android/issues/detail?id=10100 // so we have some pre-defined types here so we can make sure to return SOMETHING. String mimeType = URLConnection.guessContentTypeFromName(url); if (mimeType != null) { return mimeType; } if (url.endsWith(".jpg") || url.endsWith(".jpeg")) { mimeType = "image/jpeg"; } else if (url.endsWith(".3gp")) { mimeType = "video/3gpp"; } else if (url.endsWith(".mp4") || url.endsWith(".mpeg4")) { mimeType = "video/mp4"; } else if (url.endsWith(".png")) { mimeType = "image/png"; } return mimeType; }
From source file:com.myyearbook.hudson.plugins.confluence.ConfluencePublisher.java
protected List<RemoteAttachment> performAttachments(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, ConfluenceSession confluence, final RemotePageSummary pageData) throws IOException, InterruptedException { final long pageId = pageData.getId(); FilePath ws = build.getWorkspace();/* w ww . jav a 2 s . c o m*/ final List<RemoteAttachment> remoteAttachments = new ArrayList<RemoteAttachment>(); if (ws == null) { // Possibly running on a slave that went down log(listener, "Workspace is unavailable."); return remoteAttachments; } String attachmentComment = build.getEnvironment(listener) .expand("Published from Jenkins build: $BUILD_URL"); log(listener, "Uploading attachments to Confluence page: " + pageData.getUrl()); final List<FilePath> files = new ArrayList<FilePath>(); if (this.attachArchivedArtifacts) { final List<FilePath> archived = this.findArtifacts(build.getArtifactsDir()); if (archived.size() == 0) { log(listener, "Attempting to attach the archived artifacts, but there are no" + " archived artifacts from the job! Check job configuration..."); } else { log(listener, "Found " + archived.size() + " archived artifact(s) to upload to Confluence..."); files.addAll(archived); } } final String fileSet = hudson.Util.fixEmptyAndTrim(this.fileSet); if (!StringUtils.isEmpty(fileSet)) { log(listener, "Evaluating fileset pattern: " + fileSet); // Expand environment variables final String artifacts = build.getEnvironment(listener).expand(fileSet); // Obtain a list of all files that match the pattern final FilePath[] workspaceFiles = ws.list(artifacts); if (workspaceFiles.length > 0) { log(listener, "Found " + workspaceFiles.length + " workspace artifact(s) to upload to Confluence..."); for (FilePath file : workspaceFiles) { if (!files.contains(file)) { files.add(file); } else { // Don't include the file twice if it's already in the // list log(listener, " - pattern matched an archived artifact: " + file.getName()); } } } else { log(listener, "No files matched the pattern '" + fileSet + "'."); String msg = null; try { msg = ws.validateAntFileMask(artifacts); } catch (Exception e) { log(listener, "" + e.getMessage()); } if (msg != null) { log(listener, "" + msg); } } } log(listener, "Uploading " + files.size() + " file(s) to Confluence..."); boolean shouldRemoveExistingAttachments = false; List<RemoteAttachment> existingAtachments = null; if (shouldReplaceAttachments()) { RemoteAttachment[] attachments = confluence.getAttachments(pageId); if (attachments != null && attachments.length > 0) { existingAtachments = Arrays.asList(confluence.getAttachments(pageId)); shouldRemoveExistingAttachments = true; } } for (FilePath file : files) { final String fileName = file.getName(); if (shouldRemoveExistingAttachments) { for (RemoteAttachment remoteAttachment : existingAtachments) { if (remoteAttachment.getFileName().equals(fileName)) { try { confluence.removeAttachment(pageId, remoteAttachment); existingAtachments.remove(remoteAttachment); log(listener, "Deleted existing " + remoteAttachment.getFileName() + " from Confluence before upload new..."); break; } catch (RemoteException e) { log(listener, "Deleting error: " + e.toString()); throw e; } } } } String contentType = URLConnection.guessContentTypeFromName(fileName); if (StringUtils.isEmpty(contentType)) { // Confluence does not allow an empty content type contentType = DEFAULT_CONTENT_TYPE; } log(listener, " - Uploading file: " + fileName + " (" + contentType + ")"); try { final RemoteAttachment result = confluence.addAttachment(pageId, file, contentType, attachmentComment); remoteAttachments.add(result); log(listener, " done: " + result.getUrl()); } catch (IOException ioe) { listener.error("Unable to upload file..."); ioe.printStackTrace(listener.getLogger()); } catch (InterruptedException ie) { listener.error("Unable to upload file..."); ie.printStackTrace(listener.getLogger()); } } log(listener, "Done"); return remoteAttachments; }
From source file:foam.starwisp.NetworkManager.java
public List<String> PostFile(String requestURL, File uploadFile) throws IOException { // creates a unique boundary based on time stamp String boundary = "===" + System.currentTimeMillis() + "==="; URL url = new URL(requestURL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false);//from www .j ava2s . c o m httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); httpConn.setRequestProperty("User-Agent", "CodeJava Agent"); httpConn.setRequestProperty("Test", "Bonjour"); OutputStream outputStream = httpConn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true); String fileName = uploadFile.getName(); writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"binary\";" + "filename=\"" + fileName + "\"") .append(LINE_FEED); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); writer.flush(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); List<String> response = new ArrayList<String>(); writer.append(LINE_FEED).flush(); writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); // checks server's status code first int status = httpConn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { response.add(line); } reader.close(); httpConn.disconnect(); } else { throw new IOException("Server returned non-OK status: " + status); } return response; }