List of usage examples for java.net URLConnection guessContentTypeFromName
public static String guessContentTypeFromName(String fname)
From source file:com.palantir.stash.disapprove.servlet.StaticContentServlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { final String user = authenticateUser(req, res); if (user == null) { // not logged in, redirect res.sendRedirect(lup.getLoginUri(getUri(req)).toASCIIString()); return;//from w w w. j a v a2 s . c o m } final String pathInfo = req.getPathInfo(); OutputStream os = null; try { // The class loader that found this class will also find the static resources ClassLoader cl = this.getClass().getClassLoader(); InputStream is = cl.getResourceAsStream(PREFIX + pathInfo); if (is == null) { res.sendError(404, "File " + pathInfo + " could not be found"); return; } os = res.getOutputStream(); //res.setContentType("text/html;charset=UTF-8"); String contentType = URLConnection.guessContentTypeFromStream(is); if (contentType == null) { contentType = URLConnection.guessContentTypeFromName(pathInfo); } if (contentType == null) { contentType = "application/binary"; } log.debug("Serving file " + pathInfo + " with content type " + contentType); res.setContentType(contentType); IOUtils.copy(is, os); /* byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = bis.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } */ } finally { if (os != null) { os.close(); } } }
From source file:com.qcadoo.view.internal.resource.module.UniversalResourceModule.java
private String getContentTypeFromURI(final HttpServletRequest request) { String[] arr = request.getRequestURI().split("\\."); String ext = arr[arr.length - 1]; if ("js".equals(ext)) { return "text/javascript"; } else if ("css".equals(ext)) { return "text/css"; } else {/* w w w .j av a 2 s. c o m*/ return URLConnection.guessContentTypeFromName(request.getRequestURL().toString()); } }
From source file:AppMain.java
@Override public void handle(Request request, Response response) { long time = System.currentTimeMillis(); System.out.print(request.getPath().toString() + "\t" + request.getValues("Host") + " "); System.out.println(request.getValues("User-agent") + " "); response.setDate("Date", time); try {/* www . ja v a2 s . c o m*/ //static? send the file if (request.getPath().toString().startsWith("/static/")) { String path = request.getPath().toString().substring("/static/".length()); File requested = new File("static" + File.separatorChar + path.replace('/', File.separatorChar)); if (!requested.getCanonicalPath().startsWith(new File("static").getCanonicalPath())) { System.err.println("Error, path outside the static folder:" + path); return; } if (!requested.isFile()) { System.err.println("Error, file not found:" + path); return; } //valid path, send it String mimet = URLConnection.guessContentTypeFromName(path); if (path.endsWith(".js")) mimet = "application/javascript"; if (path.endsWith(".css")) mimet = "text/css"; System.out.println("sending static resource:'" + path + "' mimetype:" + mimet); response.setDate("Date", requested.lastModified()); try (PrintStream body = response.getPrintStream()) { response.setValue("Content-Type", mimet); FileInputStream fis = new FileInputStream(requested); //copy the stream IOUtils.copy(fis, body); fis.close(); } return; } //main page, show the index if (request.getPath().toString().equals("/")) { try (PrintStream body = response.getPrintStream()) { response.setValue("Content-Type", "text/html;charset=utf-8"); File file = new File("index.html"); System.out.println(file.getAbsolutePath()); byte[] data; try (FileInputStream fis = new FileInputStream(file)) { data = new byte[(int) file.length()]; fis.read(data); } body.write(data); } } if (request.getPath().toString().startsWith("/parse")) { response.setValue("Content-Type", "application/json;charset=utf-8"); try (PrintStream body = response.getPrintStream()) { String text = request.getQuery().get("text"); String pattern = request.getQuery().get("pattern"); if (text == null || pattern == null) { body.write("{'error':'pattern or text not specified'}".getBytes("UTF-8")); body.close(); } System.err.println("request to parse text: " + text + "\nfor pattern: " + pattern); MatchingResults results = null; JSONObject ret = new JSONObject(); try { long start = System.currentTimeMillis(); results = fm.matches(text, pattern, FlexiMatcher.getDefaultAnnotator(), true, false, true); ret.put("time to parse", System.currentTimeMillis() - start); } catch (RuntimeException r) { body.write(("{\"error\":" + JSONObject.quote(r.getMessage()) + "}").getBytes("UTF-8")); body.close(); return; } ret.put("matches", results.isMatching()); ret.put("empty_match", results.isEmptyMatch()); ret.put("text", text); ret.put("pattern", pattern); if (!results.getAnnotations().isPresent()) { body.write(ret.toString().getBytes("UTF-8")); body.close(); return; } for (LinkedList<TextAnnotation> interpretation : results.getAnnotations().get()) { JSONObject addMe = new JSONObject(); for (TextAnnotation v : interpretation) { addMe.append("annotations", new JSONObject(v.toJSON())); } ret.append("interpretations", addMe); } body.write(ret.toString(1).getBytes("UTF-8")); } return; } if (request.getPath().toString().startsWith("/trace")) { response.setValue("Content-Type", "application/json;charset=utf-8"); try (PrintStream body = response.getPrintStream()) { String text = request.getQuery().get("text"); String pattern = request.getQuery().get("pattern"); if (text == null || pattern == null) { body.write("{'error':'pattern or text not specified'}".getBytes("UTF-8")); body.close(); } System.err.println("request to parse text: " + text + "\nfor pattern: " + pattern); JSONObject ret = new JSONObject(); ListingAnnotatorHandler ah; try { long start = System.currentTimeMillis(); ah = new ListingAnnotatorHandler(); fm.matches(text, pattern, ah, true, false, true); ret.put("time", System.currentTimeMillis() - start); } catch (RuntimeException r) { body.write(("{\"error\":" + JSONObject.quote(r.getMessage()) + "}").getBytes("UTF-8")); body.close(); return; } ret.put("text", text); ret.put("pattern", pattern); LinkedList<TextAnnotation> nonOverlappingTA = new LinkedList<>(); JSONObject addMe = new JSONObject(); for (TextAnnotation v : ah.getAnnotations()) { if (nonOverlappingTA.stream().anyMatch(p -> p.getSpan().intersects(v.getSpan()))) { ret.append("interpretations", addMe); addMe = new JSONObject(); addMe.append("annotations", new JSONObject(v.toJSON())); nonOverlappingTA.clear(); } else { addMe.append("annotations", new JSONObject(v.toJSON())); } nonOverlappingTA.add(v); } ret.append("interpretations", addMe); body.write(ret.toString(1).getBytes("UTF-8")); } return; } if (request.getPath().toString().startsWith("/addtag")) { if (tagCount == 0) fwTag.write("\n#tags added from web interface at " + LocalDate.now().toString() + "\n"); tagCount++; response.setValue("Content-Type", "application/json;charset=utf-8"); try (PrintStream body = response.getPrintStream()) { String tag = request.getQuery().getOrDefault("tag", ""); String pattern = request.getQuery().getOrDefault("pattern", ""); if (tag.isEmpty() || pattern.isEmpty()) { body.write("{\"error\":\"tag or pattern not specified\"}".getBytes("UTF-8")); body.close(); return; } String identifier = request.getQuery().getOrDefault("identifier", ""); String annotationTemplate = request.getQuery().getOrDefault("annotation_template", "").trim(); if (identifier.isEmpty()) { identifier = "auto_" + LocalDate.now().toString() + "_" + tagCount; } //check that rule identifiers are known for (String part : ExpressionParser.split(pattern)) { if (!part.startsWith("[")) continue; if (!fm.isBoundRule(ExpressionParser.ruleName(part))) { body.write(("{\"error\":\"rule '" + ExpressionParser.ruleName(part) + "' non known\"}") .getBytes("UTF-8")); body.close(); return; } } fwTag.write(tag + "\t" + pattern + "\t" + identifier + "\t" + annotationTemplate + "\n"); fwTag.flush(); if (annotationTemplate.isEmpty()) fm.addTagRule(tag, pattern, identifier); else fm.addTagRule(tag, pattern, identifier, annotationTemplate); body.write(("{\"identifier\":" + JSONObject.quote(identifier) + "}").getBytes("UTF-8")); } return; } //unknown request try (PrintStream body = response.getPrintStream()) { response.setValue("Content-Type", "text/plain"); response.setDate("Last-Modified", time); response.setCode(401); body.println("HTTP request for page '" + request.getPath().toString() + "' non understood in " + this.getClass().getCanonicalName()); } } catch (IOException | JSONException e) { e.printStackTrace(); System.exit(1); } }
From source file:forseti.MultipartUtility.java
/** * Adds a upload file section to the request * @param fieldName name attribute in <input type="file" name="..." /> * @param uploadFile a File to be uploaded * @throws IOException// ww w.ja v a2s .c om */ public void addFilePart(String fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; 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(); }
From source file:com.personalserver.DirCommandHandler.java
private HttpEntity getEntityFromUri(String uri, HttpResponse response) { String contentType = "text/html"; String filepath = FOLDER_SHARE_PATH; if (uri.equalsIgnoreCase("/") || uri.length() <= 0) { filepath = FOLDER_SHARE_PATH + "/"; } else {/*from ww w .j a v a 2s . c o m*/ filepath = FOLDER_SHARE_PATH + "/" + URLDecoder.decode(uri); } System.out.println("request uri : " + uri); System.out.println("FOLDER SHARE PATH : " + FOLDER_SHARE_PATH); System.out.println("filepath : " + filepath); final File file = new File(filepath); HttpEntity entity = null; if (file.isDirectory()) { entity = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); String resp = getDirListingHTML(file); writer.write(resp); writer.flush(); } }); response.setHeader("Content-Type", contentType); } else if (file.exists()) { contentType = URLConnection.guessContentTypeFromName(file.getAbsolutePath()); entity = new FileEntity(file, contentType); response.setHeader("Content-Type", contentType); } else { entity = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); String resp = "<html>" + "<head><title>ERROR : NOT FOUND</title></head>" + "<body>" + "<center><h1>FILE OR DIRECTORY NOT FOUND !</h1></center>" + "<p>Sorry, file or directory you request not available<br />" + "Contact your administrator<br />" + "</p>" + "</body></html>"; writer.write(resp); writer.flush(); } }); response.setHeader("Content-Type", "text/html"); } return entity; }
From source file:com.joyent.manta.http.ContentTypeLookup.java
/** * Finds the content type set in {@link MantaHttpHeaders} and returns that if it * is not null. Otherwise, it will return the specified default content type. * * @param headers headers to parse for content type * @param filename filename that is being probed for content type * @param defaultContentType content type to default to * @return content type object/* w ww .j a v a 2 s . c om*/ */ public static ContentType findOrDefaultContentType(final MantaHttpHeaders headers, final String filename, final ContentType defaultContentType) { final String headerContentType; if (headers != null) { headerContentType = headers.getContentType(); } else { headerContentType = null; } String type = ObjectUtils.firstNonNull( // Use explicitly set headers if available headerContentType, // Detect based on filename URLConnection.guessContentTypeFromName(filename)); if (type == null) { return defaultContentType; } return ContentType.parse(type); }
From source file:org.mobicents.servlet.restcomm.fax.InterfaxService.java
private URI send(final Object message) throws Exception { final FaxRequest request = (FaxRequest) message; final String to = request.to(); final File file = request.file(); // Prepare the request. final DefaultHttpClient client = new DefaultHttpClient(); final HttpContext context = new BasicHttpContext(); final SSLSocketFactory sockets = new SSLSocketFactory(strategy); final Scheme scheme = new Scheme("https", 443, sockets); client.getConnectionManager().getSchemeRegistry().register(scheme); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password); final HttpPost post = new HttpPost(url + to); final String mime = URLConnection.guessContentTypeFromName(file.getName()); final FileEntity entity = new FileEntity(file, mime); post.addHeader(new BasicScheme().authenticate(credentials, post, context)); post.setEntity(entity);// w w w .j av a 2 s . co m // Handle the response. final HttpResponse response = client.execute(post, context); final StatusLine status = response.getStatusLine(); final int code = status.getStatusCode(); if (HttpStatus.SC_CREATED == code) { EntityUtils.consume(response.getEntity()); final Header[] headers = response.getHeaders(HttpHeaders.LOCATION); final Header location = headers[0]; final String resource = location.getValue(); return URI.create(resource); } else { final StringBuilder buffer = new StringBuilder(); buffer.append(code).append(" ").append(status.getReasonPhrase()); throw new FaxServiceException(buffer.toString()); } }
From source file:ly.count.android.api.ConnectionProcessor.java
URLConnection urlConnectionForEventData(final String eventData) throws IOException { final String urlStr = serverURL_ + "/i?" + eventData; final URL url = new URL(urlStr); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS); conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS); conn.setUseCaches(false);//w ww .j a v a 2 s .c o m conn.setDoInput(true); String picturePath = UserData.getPicturePathFromQuery(url); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Got picturePath: " + picturePath); } if (!picturePath.equals("")) { //Uploading files: //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests File binaryFile = new File(picturePath); conn.setDoOutput(true); // Just generate some unique random value. String boundary = Long.toHexString(System.currentTimeMillis()); // Line separator required by multipart/form-data. String CRLF = "\r\n"; String charset = "UTF-8"; conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream output = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())) .append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); FileInputStream fileInputStream = new FileInputStream(binaryFile); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1) { output.write(buffer, 0, len); } output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. fileInputStream.close(); // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); } else { conn.setDoOutput(false); } return conn; }
From source file:com.necl.core.controller.DownloadFileController.java
@RequestMapping(value = "/downloadTraining", method = RequestMethod.GET) public void downloadFileTraining(HttpServletResponse response, @RequestParam String id) throws IOException, Exception { Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); String keyFind = "PATH"; ConfigSystem configSystem = configSystemService.findByKey(keyFind); String saveDirectory = configSystem.getConfigText() + year + "/"; File file = null;/* w w w .j ava 2 s . com*/ String name = id.replace("/", "_"); String type = ".pdf"; String pathDirectory = saveDirectory + name + type; 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) { mimeType = "application/octet-stream"; } 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.kuali.kfs.module.ar.web.struts.AccountsReceivableTemplateUploadAction.java
/** * Sends the uploaded file contents to the templateService for storage. If errors were encountered, messages will be in * GlobalVariables.errorMap, which is checked and set for display by the request processor. *//* www . ja v a2 s. co m*/ public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { AccountsReceivableTemplateUploadForm newForm = (AccountsReceivableTemplateUploadForm) form; FormFile uploadedFile = newForm.getUploadedFile(); // validations performed on the required values for saving the template String templateCode = newForm.getTemplateCode(); TemplateBase template = getBoService().findBySinglePrimaryKey(newForm.getTemplateClass(), templateCode); String errorPropertyName = newForm.getErrorPropertyName(); String templateType = newForm.getTemplateType(); // check uploaded file if (ObjectUtils.isNull(uploadedFile) || ObjectUtils.isNull(uploadedFile.getInputStream()) || uploadedFile.getInputStream().available() == 0) { GlobalVariables.getMessageMap().putError(errorPropertyName, ArKeyConstants.TemplateUploadErrors.ERROR_TEMPLATE_UPLOAD_NO_TEMPLATE); } else if (!StringUtils.equals(KFSConstants.ReportGeneration.PDF_MIME_TYPE, URLConnection.guessContentTypeFromName(uploadedFile.getFileName()))) { GlobalVariables.getMessageMap().putError(errorPropertyName, ArKeyConstants.TemplateUploadErrors.ERROR_TEMPLATE_UPLOAD_INVALID_FILE_TYPE); } // check template code for null and being empty, and check if org code and COAcode exists for the template if (StringUtils.isBlank(templateCode)) { GlobalVariables.getMessageMap().putError(errorPropertyName, ArKeyConstants.TemplateUploadErrors.ERROR_TEMPLATE_UPLOAD_NO_TEMPLATE_TYPE); } else { if (ObjectUtils.isNotNull(template)) { if (StringUtils.isBlank(template.getBillByChartOfAccountCode()) || StringUtils.isBlank(template.getBilledByOrganizationCode())) { GlobalVariables.getMessageMap().putError(errorPropertyName, ArKeyConstants.TemplateUploadErrors.ERROR_TEMPLATE_UPLOAD_USER_NOT_AUTHORIZED); } else { performAdditionalAuthorizationChecks(template); } } else { GlobalVariables.getMessageMap().putError(errorPropertyName, ArKeyConstants.TemplateUploadErrors.ERROR_TEMPLATE_UPLOAD_TEMPLATE_NOT_AVAILABLE); } } if (GlobalVariables.getMessageMap().hasNoErrors()) { // set filename for the template template.setFilename(newForm.getNewFileNamePrefix() + newForm.getTemplateCode().replaceAll("[\\/]", "-") + KFSConstants.ReportGeneration.PDF_FILE_EXTENSION); String destinationFolderPath = getFinancialSystemModuleConfiguration().getTemplateFileDirectories() .get(KFSConstants.TEMPLATES_DIRECTORY_KEY); String destinationPath = destinationFolderPath + File.separator + template.getFilename(); File destinationFolder = new File(destinationFolderPath); File destinationFile = new File(destinationPath); if (!destinationFolder.exists()) { destinationFolder.mkdirs(); } if (destinationFile.exists()) { destinationFile.delete(); } SimpleDateFormat sdf = new SimpleDateFormat(ArConstants.YEAR_MONTH_DAY_HOUR_MINUTE_SECONDS_DATE_FORMAT); writeInputStreamToFileStorage(uploadedFile.getInputStream(), destinationFile); template.setUploadDate(getDateTimeService().getCurrentTimestamp()); boService.save(template); KNSGlobalVariables.getMessageList().add(KFSKeyConstants.MESSAGE_BATCH_UPLOAD_SAVE_SUCCESSFUL); } return mapping.findForward(KFSConstants.MAPPING_BASIC); }