List of usage examples for java.net URLConnection guessContentTypeFromName
public static String guessContentTypeFromName(String fname)
From source file:org.primefaces.component.imagecropper.ImageCropperRenderer.java
/** * Attempt to obtain the image format used to write the image from the contentType or the image's file extension. *//*from w w w . j a v a 2 s . c o m*/ private String guessImageFormat(String contentType, String imagePath) throws IOException { String format = "png"; if (contentType == null) { contentType = URLConnection.guessContentTypeFromName(imagePath); } if (contentType != null) { format = contentType.replaceFirst("^image/([^;]+)[;]?.*$", "$1"); } else { int queryStringIndex = imagePath.indexOf('?'); if (queryStringIndex != -1) { imagePath = imagePath.substring(0, queryStringIndex); } String[] pathTokens = imagePath.split("\\."); if (pathTokens.length > 1) { format = pathTokens[pathTokens.length - 1]; } } return format; }
From source file:org.shareok.data.webserv.JournalDataController.java
@RequestMapping(value = "/download/dspace/safpackage/{publisher}/{folderName}/{safDirName}/{fileName}") public void safPackageLoadingDataDownload(HttpServletResponse response, @PathVariable("publisher") String publisher, @PathVariable("folderName") String folderName, @PathVariable("safDirName") String safDirName, @PathVariable("fileName") String fileName) { String downloadPath = DspaceJournalDataUtil.getDspaceSafPackageDownloadFilePath(publisher, folderName, safDirName, fileName);// w w w . j a v a 2 s.c o m try { File file = new File(downloadPath); 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"; } 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("attachment; 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()); } catch (IOException ioex) { Logger.getLogger(JournalDataController.class.getName()).log(Level.SEVERE, null, ioex); } }
From source file:io.fabric8.maven.enricher.fabric8.IconEnricher.java
private String convertIconFileToURL(File iconFile, String iconRef) throws IOException { long length = iconFile.length(); int sizeK = Math.round(length / 1024); byte[] bytes = FileUtils.readFileToByteArray(iconFile); byte[] encoded = Base64.encodeBase64(bytes); int base64SizeK = Math.round(encoded.length / 1024); if (base64SizeK < Configs.asInt(getConfig(Config.maximumDataUrlSizeK))) { String mimeType = URLConnection.guessContentTypeFromName(iconFile.getName()); return "data:" + mimeType + ";charset=UTF-8;base64," + new String(encoded); } else {/*from www . j a v a 2 s. c om*/ File iconSourceFile = new File(appConfigDir, iconFile.getName()); if (iconSourceFile.exists()) { File rootProjectFolder = getRootProjectFolder(); if (rootProjectFolder != null) { String relativePath = FileUtil.getRelativePath(rootProjectFolder, iconSourceFile).toString(); String relativeParentPath = FileUtil .getRelativePath(rootProjectFolder, getProject().getBasedir()).toString(); String urlPrefix = getConfig(Config.urlPrefix); if (StringUtils.isBlank(urlPrefix)) { Scm scm = getProject().getScm(); if (scm != null) { String url = scm.getUrl(); if (url != null) { String[] prefixes = { "http://github.com/", "https://github.com/" }; for (String prefix : prefixes) { if (url.startsWith(prefix)) { url = "https://cdn.rawgit.com/" + url.substring(prefix.length()); break; } } if (url.endsWith(relativeParentPath)) { url = url.substring(0, url.length() - relativeParentPath.length()); } urlPrefix = url; } } } if (StringUtils.isBlank(urlPrefix)) { log.warn( "No iconUrlPrefix defined or could be found via SCM in the pom.xml so cannot add an icon URL!"); } else { return String.format("%s/%s/%s", urlPrefix, getConfig(Config.branch), relativePath); } } } else { String embeddedIcon = embeddedIconsInConsole(iconRef, "img/icons/"); if (embeddedIcon != null) { return embeddedIcon; } else { log.warn("Cannot find url for icon to use %s", iconRef); } } } return null; }
From source file:info.guardianproject.otr.app.im.app.MessageView.java
private void showMediaThumbnail(String mimeType, Uri mediaUri, int id, ViewHolder holder) { /* Guess the MIME type in case we received a file that we can display or play*/ if (TextUtils.isEmpty(mimeType) || mimeType.startsWith("application")) { String guessed = URLConnection.guessContentTypeFromName(mediaUri.toString()); if (!TextUtils.isEmpty(guessed)) { if (TextUtils.equals(guessed, "video/3gpp")) mimeType = "audio/3gpp"; else/* w ww. jav a 2 s .com*/ mimeType = guessed; } } holder.setOnClickListenerMediaThumbnail(mimeType, mediaUri); holder.mMediaThumbnail.setVisibility(View.VISIBLE); holder.mTextViewForMessages.setText(lastMessage); holder.mTextViewForMessages.setVisibility(View.GONE); if (mimeType.startsWith("image/")) { setImageThumbnail(getContext().getContentResolver(), id, holder, mediaUri); holder.mMediaThumbnail.setBackgroundColor(Color.TRANSPARENT); // holder.mMediaThumbnail.setBackgroundColor(Color.WHITE); } else if (mimeType.startsWith("audio")) { holder.mMediaThumbnail.setImageResource(R.drawable.media_audio_play); holder.mMediaThumbnail.setBackgroundColor(Color.TRANSPARENT); } else { holder.mMediaThumbnail.setImageResource(R.drawable.ic_file); // generic file icon } holder.mContainer.setBackgroundColor(getResources().getColor(android.R.color.transparent)); }
From source file:org.awesomeapp.messenger.ui.MessageListItem.java
private boolean showMediaThumbnail(String mimeType, Uri mediaUri, int id, MessageViewHolder holder) { this.mediaUri = mediaUri; this.mimeType = mimeType; /* Guess the MIME type in case we received a file that we can display or play*/ if (TextUtils.isEmpty(mimeType) || mimeType.startsWith("application")) { String guessed = URLConnection.guessContentTypeFromName(mediaUri.toString()); if (!TextUtils.isEmpty(guessed)) { if (TextUtils.equals(guessed, "video/3gpp")) mimeType = "audio/3gpp"; else/*w w w . jav a 2s. c o m*/ mimeType = guessed; } } holder.setOnClickListenerMediaThumbnail(mimeType, mediaUri); holder.mTextViewForMessages.setText(lastMessage); holder.mTextViewForMessages.setVisibility(View.GONE); if (mimeType.startsWith("image/")) { setImageThumbnail(getContext().getContentResolver(), id, holder, mediaUri); holder.mMediaThumbnail.setBackgroundResource(android.R.color.transparent); } else { Glide.clear(holder.mMediaThumbnail); try { Glide.with(context).load(R.drawable.ic_file).diskCacheStrategy(DiskCacheStrategy.NONE) .into(holder.mMediaThumbnail); } catch (Exception e) { Log.e(ImApp.LOG_TAG, "unable to load thumbnail", e); } holder.mMediaThumbnail.setImageResource(R.drawable.ic_file); // generic file icon holder.mTextViewForMessages.setText(mediaUri.getLastPathSegment()); holder.mTextViewForMessages.setVisibility(View.VISIBLE); } holder.mMediaContainer.setVisibility(View.VISIBLE); holder.mContainer.setBackgroundResource(android.R.color.transparent); return true; }
From source file:org.wso2.carbon.apimgt.importexport.utils.APIImportUtil.java
/** * This method adds the icon to the API which is to be displayed at the API store. * * @param pathToArchive location of the extracted folder of the API * @param importedApi the imported API object *///from w w w.j a va 2 s. c o m private static void addAPIImage(String pathToArchive, API importedApi) { //Adding image icon to the API if there is any File imageFolder = new File(pathToArchive + APIImportExportConstants.IMAGE_FILE_LOCATION); File[] fileArray = imageFolder.listFiles(); FileInputStream inputStream = null; try { if (imageFolder.isDirectory() && fileArray != null) { //This loop locates the icon of the API for (File imageFile : fileArray) { if (imageFile != null && imageFile.getName().contains(APIImportExportConstants.IMAGE_FILE_NAME)) { String mimeType = URLConnection.guessContentTypeFromName(imageFile.getName()); inputStream = new FileInputStream(imageFile.getAbsolutePath()); ResourceFile apiImage = new ResourceFile(inputStream, mimeType); String thumbPath = APIUtil.getIconPath(importedApi.getId()); String thumbnailUrl = provider.addResourceFile(thumbPath, apiImage); importedApi.setThumbnailUrl( APIUtil.prependTenantPrefix(thumbnailUrl, importedApi.getId().getProviderName())); APIUtil.setResourcePermissions(importedApi.getId().getProviderName(), null, null, thumbPath); provider.updateAPI(importedApi); //the loop is terminated after successfully locating the icon break; } } } } catch (FileNotFoundException e) { //This is logged and process is continued because icon is optional for an API log.error("Icon for API is not found. ", e); } catch (APIManagementException e) { //This is logged and process is continued because icon is optional for an API log.error("Failed to add icon to the API. ", e); } catch (FaultGatewaysException e) { //This is logged and process is continued because icon is optional for an API log.error("Failed to update API after adding icon. ", e); } finally { IOUtils.closeQuietly(inputStream); } }
From source file:apim.restful.importexport.utils.APIImportUtil.java
/** * This method adds the icon to the API which is to be displayed at the API store. * * @param pathToArchive location of the extracted folder of the API * @param importedApi the imported API object *///from w w w . ja v a2 s .co m private static void addAPIImage(String pathToArchive, API importedApi) { //Adding image icon to the API if there is any File imageFolder = new File(pathToArchive + APIImportExportConstants.IMAGE_FILE_LOCATION); File[] fileArray = imageFolder.listFiles(); FileInputStream inputStream = null; try { if (imageFolder.isDirectory() && fileArray != null) { //This loop locates the icon of the API for (File imageFile : fileArray) { if (imageFile != null && imageFile.getName().contains(APIImportExportConstants.IMAGE_FILE_NAME)) { String mimeType = URLConnection.guessContentTypeFromName(imageFile.getName()); inputStream = new FileInputStream(imageFile.getAbsolutePath()); Icon apiImage = new Icon(inputStream, mimeType); String thumbPath = APIUtil.getIconPath(importedApi.getId()); String thumbnailUrl = provider.addIcon(thumbPath, apiImage); importedApi.setThumbnailUrl( APIUtil.prependTenantPrefix(thumbnailUrl, importedApi.getId().getProviderName())); APIUtil.setResourcePermissions(importedApi.getId().getProviderName(), null, null, thumbPath); provider.updateAPI(importedApi); //the loop is terminated after successfully locating the icon break; } } } } catch (FileNotFoundException e) { //This is logged and process is continued because icon is optional for an API log.error("Icon for API is not found. ", e); } catch (APIManagementException e) { //This is logged and process is continued because icon is optional for an API log.error("Failed to add icon to the API. ", e); } catch (FaultGatewaysException e) { //This is logged and process is continued because icon is optional for an API log.error("Failed to update API after adding icon. ", e); } finally { IOUtils.closeQuietly(inputStream); } }
From source file:com.astamuse.asta4d.web.builtin.StaticResourceHandler.java
/** * The header value of Content-Type/*from w w w . java2s . c o m*/ * * @param path * @return a guess of the content type by file name extension, "application/octet-stream" when not matched */ protected String judgContentType(String path) { Context context = Context.getCurrentThreadContext(); String forceContentType = context.getData(WebApplicationContext.SCOPE_PATHVAR, VAR_CONTENT_TYPE); if (forceContentType != null) { return forceContentType; } String fileName = FilenameUtils.getName(path); // guess the type by file name extension String type = URLConnection.guessContentTypeFromName(fileName); if (type == null) { type = MimeTypeMap.get(FilenameUtils.getExtension(fileName)); } if (type == null) { type = "application/octet-stream"; } return type; }
From source file:com.github.mobile.util.HttpImageGetter.java
@Override public Drawable getDrawable(String source) { Bitmap bitmap = null;/* ww w . j a v a 2 s .c o m*/ if (!destroyed) { File output = null; InputStream is = null; HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(source).openConnection(); is = connection.getInputStream(); if (is != null) { String mime = connection.getContentType(); if (mime == null) { mime = URLConnection.guessContentTypeFromName(source); } if (mime == null) { mime = URLConnection.guessContentTypeFromStream(is); } if (mime != null && mime.startsWith("image/svg")) { bitmap = ImageUtils.renderSvgToBitmap(context.getResources(), is, width, height); } else { boolean isGif = mime != null && mime.startsWith("image/gif"); if (!isGif || canLoadGif()) { output = File.createTempFile("image", ".tmp", dir); if (FileUtils.save(output, is)) { if (isGif) { GifDrawable d = new GifDrawable(output); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); return d; } else { bitmap = ImageUtils.getBitmap(output, width, height); } } } } } } catch (IOException e) { // fall through to showing the loading bitmap } finally { if (output != null) { output.delete(); } if (is != null) { try { is.close(); } catch (IOException e) { // ignored } } if (connection != null) { connection.disconnect(); } } } synchronized (this) { if (destroyed && bitmap != null) { bitmap.recycle(); bitmap = null; } else if (bitmap != null) { loadedBitmaps.add(new WeakReference<>(bitmap)); } } if (bitmap == null) { return loading.getDrawable(source); } BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap); drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight()); return drawable; }
From source file:com.cellbots.httpserver.HttpCommandServer.java
public void handle(final HttpServerConnection conn, final HttpContext context) throws HttpException, IOException { HttpRequest request = conn.receiveRequestHeader(); HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"); String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") && !method.equals("PUT")) { throw new MethodNotSupportedException(method + " method not supported"); }//from w w w .j a v a 2 s . c om // Get the requested target. This is the string after the domain name in // the URL. If the full URL was http://mydomain.com/test.html, target // will be /test.html. String target = request.getRequestLine().getUri(); //Log.w(TAG, "*** Request target: " + target); // Gets the requested resource name. For example, if the full URL was // http://mydomain.com/test.html?x=1&y=2, resource name will be // test.html final String resName = getResourceNameFromTarget(target); UrlParams params = new UrlParams(target); //Log.w(TAG, "*** Request LINE: " + request.getRequestLine().toString()); //Log.w(TAG, "*** Request resource: " + resName); if (method.equals("POST") || method.equals("PUT")) { byte[] entityContent = null; // Gets the content if the request has an entity. if (request instanceof HttpEntityEnclosingRequest) { conn.receiveRequestEntity((HttpEntityEnclosingRequest) request); HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { entityContent = EntityUtils.toByteArray(entity); } } response.setStatusCode(HttpStatus.SC_OK); if (serverListener != null) { serverListener.onRequest(resName, params.keys, params.values, entityContent); } } else if (dataMap.containsKey(resName)) { // The requested resource is // a byte array response.setStatusCode(HttpStatus.SC_OK); response.setHeader("Content-Type", dataMap.get(resName).contentType); response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource)); } else { // Resource is a file recognized by the app String fileName = resourceMap.containsKey(resName) ? resourceMap.get(resName).resource : resName; String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType : "text/html"; Log.d(TAG, "*** mapped resource: " + fileName); Log.d(TAG, "*** checking for file: " + rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName); response.setStatusCode(HttpStatus.SC_OK); final File file = new File(rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName); if (file.exists() && !file.isDirectory()) { response.setStatusCode(HttpStatus.SC_OK); FileEntity body = new FileEntity(file, URLConnection.guessContentTypeFromName(fileName)); response.setHeader("Content-Type", URLConnection.guessContentTypeFromName(fileName)); response.setEntity(body); } else if (file.isDirectory()) { response.setStatusCode(HttpStatus.SC_OK); EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); ArrayList<String> fileList = getDirListing(file); String resp = "{ \"list\": ["; for (String fl : fileList) { resp += "\"" + fl + "\","; } resp = resp.substring(0, resp.length() - 1); resp += "]}"; writer.write(resp); writer.flush(); } }); body.setContentType(contentType); response.setEntity(body); } else if (resourceMap.containsKey(resName)) { EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write(resourceMap.get(resName).resource); writer.flush(); } }); body.setContentType(contentType); response.setEntity(body); } else { response.setStatusCode(HttpStatus.SC_NOT_FOUND); response.setEntity(new StringEntity("Not Found")); } } conn.sendResponseHeader(response); conn.sendResponseEntity(response); conn.flush(); conn.shutdown(); }