Java Code Examples for java.net.URLConnection#guessContentTypeFromName()

The following examples show how to use java.net.URLConnection#guessContentTypeFromName() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
/** Get a file from the logo subdirectory of the filestore */
@GetMapping("/logo/{name}.{extension}")
public void getLogo(
    OutputStream out,
    @PathVariable("name") String name,
    @PathVariable("extension") String extension,
    HttpServletResponse response)
    throws IOException {
  File f = fileStore.getFileUnchecked("/logo/" + name + "." + extension);
  if (!f.exists()) {
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
    return;
  }

  // Try to get contenttype from file
  String contentType = URLConnection.guessContentTypeFromName(f.getName());
  if (contentType != null) {
    response.setContentType(contentType);
  }

  FileCopyUtils.copy(new FileInputStream(f), out);
}
 
Example 2
@Override
public void uploadPublicFile(Path filePath, InputStream content) {
    String destFilePathString = filePath.toString();

    ObjectMetadata objectMetadata = new ObjectMetadata();

    String contentType = URLConnection.guessContentTypeFromName(destFilePathString);
    if (contentType != null) {
        objectMetadata.setContentType(contentType);
        if (contentType.startsWith("image/")) {
            objectMetadata.setCacheControl("no-transform,public,max-age=300,s-maxage=900");
        }
    }

    s3.putObject(bucketName, destFilePathString, content, objectMetadata);
}
 
Example 3
Source Project: oxd   File: ApiClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Guess Content-Type header from the given file (defaults to "application/octet-stream").
 *
 * @param file The given file
 * @return The guessed Content-Type
 */
public String guessContentTypeFromFile(File file) {
    String contentType = URLConnection.guessContentTypeFromName(file.getName());
    if (contentType == null) {
        return "application/octet-stream";
    } else {
        return contentType;
    }
}
 
Example 4
private void showMediaThumbnail (String mimeType, Uri mediaUri, int id)
{
    /* 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
                mimeType = guessed;
        }
    }
    setOnClickListenerMediaThumbnail(mimeType, mediaUri);

    if (mMediaThumbnail.getVisibility() == View.GONE)
        mMediaThumbnail.setVisibility(View.VISIBLE);

    if( mimeType.startsWith("image/") ) {
        setImageThumbnail(context.getContentResolver(), id, mediaUri);
      //  mMediaThumbnail.setBackgroundColor(Color.TRANSPARENT);
        // holder.mMediaThumbnail.setBackgroundColor(Color.WHITE);

    }
    else if (mimeType.startsWith("audio"))
    {
        mMediaThumbnail.setImageResource(R.drawable.media_audio_play);
        mMediaThumbnail.setBackgroundColor(Color.TRANSPARENT);
    }
    else
    {
        mMediaThumbnail.setImageResource(R.drawable.ic_file); // generic file icon

    }

    //mContainer.setBackgroundColor(mContainer.getResources().getColor(android.R.color.transparent));



}
 
Example 5
Source Project: blade   File: StaticFileHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the content type header for the HTTP Response
 *
 * @param response HTTP response
 * @param file     file to extract content type
 */
private static void setContentTypeHeader(HttpResponse response, File file) {
    String contentType = StringKit.mimeType(file.getName());
    if (null == contentType) {
        contentType = URLConnection.guessContentTypeFromName(file.getName());
    }
    response.headers().set(HttpConst.CONTENT_TYPE, contentType);
}
 
Example 6
private void showMediaThumbnail (String mimeType, Uri mediaUri, int id)
{
    /* 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
                mimeType = guessed;
        }
    }
    setOnClickListenerMediaThumbnail(mimeType, mediaUri);

    if (mMediaThumbnail.getVisibility() == View.GONE)
        mMediaThumbnail.setVisibility(View.VISIBLE);

    if( mimeType.startsWith("image/") ) {
        setImageThumbnail(context.getContentResolver(), id, mediaUri);
      //  mMediaThumbnail.setBackgroundColor(Color.TRANSPARENT);
        // holder.mMediaThumbnail.setBackgroundColor(Color.WHITE);

    }
    else if (mimeType.startsWith("audio"))
    {
        mMediaThumbnail.setImageResource(R.drawable.media_audio_play);
        mMediaThumbnail.setBackgroundColor(Color.TRANSPARENT);
    }
    else
    {
        mMediaThumbnail.setImageResource(R.drawable.file_unknown); // generic file icon

    }

    //mContainer.setBackgroundColor(mContainer.getResources().getColor(android.R.color.transparent));



}
 
Example 7
Source Project: feign-form   File: AbstractWriter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Writes file's metadata.
 *
 * @param output      output writer.
 * @param name        name for piece of data.
 * @param fileName    file name.
 * @param contentType type of file content. May be the {@code null}, in that case it will be determined by file name.
 */
@SneakyThrows
protected void writeFileMetadata (Output output, String name, String fileName, String contentType) {
  val contentDespositionBuilder = new StringBuilder()
      .append("Content-Disposition: form-data; name=\"").append(name).append("\"");
  if (fileName != null) {
    contentDespositionBuilder.append("; ").append("filename=\"").append(fileName).append("\"");
  }

  String fileContentType = contentType;
  if (fileContentType == null) {
    if (fileName != null) {
      fileContentType = URLConnection.guessContentTypeFromName(fileName);
    }
    if (fileContentType == null) {
      fileContentType = "application/octet-stream";
    }
  }

  val string = new StringBuilder()
      .append(contentDespositionBuilder.toString()).append(CRLF)
      .append("Content-Type: ").append(fileContentType).append(CRLF)
      .append("Content-Transfer-Encoding: binary").append(CRLF)
      .append(CRLF)
      .toString();

  output.write(string);
}
 
Example 8
Source Project: tutorials   File: MimeTypeUnitTest.java    License: MIT License 5 votes vote down vote up
/**
 * Test method demonstrating the usage of URLConnection to resolve MIME type.
 * 
 */
@Test
public void whenUsingGuessContentTypeFromName_thenSuccess() {
    final File file = new File(FILE_LOC);
    final String mimeType = URLConnection.guessContentTypeFromName(file.getName());
    assertEquals(mimeType, PNG_EXT);
}
 
Example 9
Source Project: openapi-generator   File: ApiClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Guess Content-Type header from the given file (defaults to "application/octet-stream").
 *
 * @param file The given file
 * @return The guessed Content-Type
 */
public String guessContentTypeFromFile(File file) {
    String contentType = URLConnection.guessContentTypeFromName(file.getName());
    if (contentType == null) {
        return "application/octet-stream";
    } else {
        return contentType;
    }
}
 
Example 10
Source Project: openapi-generator   File: ApiClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Guess Content-Type header from the given file (defaults to "application/octet-stream").
 *
 * @param file The given file
 * @return The guessed Content-Type
 */
public String guessContentTypeFromFile(File file) {
    String contentType = URLConnection.guessContentTypeFromName(file.getName());
    if (contentType == null) {
        return "application/octet-stream";
    } else {
        return contentType;
    }
}
 
Example 11
Source Project: htmlunit   File: WebClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tries to guess the content type of the file.<br>
 * This utility could be located in a helper class but we can compare this functionality
 * for instance with the "Helper Applications" settings of Mozilla and therefore see it as a
 * property of the "browser".
 * @param file the file
 * @return "application/octet-stream" if nothing could be guessed
 */
public String guessContentType(final File file) {
    final String fileName = file.getName();
    if (fileName.endsWith(".xhtml")) {
        // Java's mime type map returns application/xml in JDK8.
        return MimeType.APPLICATION_XHTML;
    }

    // Java's mime type map does not know these in JDK8.
    if (fileName.endsWith(".js")) {
        return MimeType.APPLICATION_JAVASCRIPT;
    }
    if (fileName.toLowerCase(Locale.ROOT).endsWith(".css")) {
        return MimeType.TEXT_CSS;
    }

    String contentType = URLConnection.guessContentTypeFromName(fileName);
    if (contentType == null) {
        try (InputStream inputStream = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
            contentType = URLConnection.guessContentTypeFromStream(inputStream);
        }
        catch (final IOException e) {
            // Ignore silently.
        }
    }
    if (contentType == null) {
        contentType = MimeType.APPLICATION_OCTET_STREAM;
    }
    return contentType;
}
 
Example 12
Source Project: HtmlUnit-Android   File: WebClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tries to guess the content type of the file.<br>
 * This utility could be located in a helper class but we can compare this functionality
 * for instance with the "Helper Applications" settings of Mozilla and therefore see it as a
 * property of the "browser".
 * @param file the file
 * @return "application/octet-stream" if nothing could be guessed
 */
public String guessContentType(final File file) {
    final String fileName = file.getName();
    if (fileName.endsWith(".xhtml")) {
        // Java's mime type map returns application/xml in JDK8.
        return "application/xhtml+xml";
    }

    // Java's mime type map does not know these in JDK8.
    if (fileName.endsWith(".js")) {
        return "application/javascript";
    }
    if (fileName.toLowerCase(Locale.ROOT).endsWith(".css")) {
        return "text/css";
    }

    String contentType = URLConnection.guessContentTypeFromName(fileName);
    if (contentType == null) {
        try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
            contentType = URLConnection.guessContentTypeFromStream(inputStream);
        }
        catch (final IOException e) {
            // Ignore silently.
        }
    }
    if (contentType == null) {
        contentType = "application/octet-stream";
    }
    return contentType;
}
 
Example 13
Source Project: teammates   File: MockPart.java    License: GNU General Public License v2.0 5 votes vote down vote up
public MockPart(String filePath) throws IOException {
    File file = new File(filePath);
    this.contentType = URLConnection.guessContentTypeFromName(file.getName());
    this.inputStream = Files.newInputStream(Paths.get(filePath));
    this.size = file.length();
    this.name = file.getName();
}
 
Example 14
@Override
public String getContentType(String fileName) {
  if (fileName != null) {
    return URLConnection.guessContentTypeFromName(fileName);
  }
  return null;
}
 
Example 15
static File renameFile(File file, String newFileName, Context context) {
    String contentType = URLConnection.guessContentTypeFromName(file.getName());
    String generatedName = generateFileName(MediaType.get(contentType), newFileName);
    File newFile = new File(context.getFilesDir(), "sdk_resources/" + generatedName);

    if (!file.renameTo(newFile)) {
        Log.d(FileResourceUtil.class.getCanonicalName(),
                "Fail renaming " + file.getName() + " to " + generatedName);
    }
    return newFile;
}
 
Example 16
synchronized void sendPostponedMessages() {

        if (!sendingPostponed) {
            sendingPostponed = true;

            String[] projection = new String[]{BaseColumns._ID, Imps.Messages.BODY,
                    Imps.Messages.PACKET_ID,
                    Imps.Messages.DATE, Imps.Messages.TYPE, Imps.Messages.IS_DELIVERED};
            String selection = Imps.Messages.TYPE + "=?";

            Cursor c = mContentResolver.query(mMessageURI, projection, selection,
                    new String[]{Integer.toString(Imps.MessageType.QUEUED)}, null);
            if (c == null) {
                RemoteImService.debug("Query error while querying postponed messages");
                return;
            }

            if (c.getCount() > 0) {
                ArrayList<String> messages = new ArrayList<String>();

                while (c.moveToNext())
                    messages.add(c.getString(1));

                removeMessageInDb(Imps.MessageType.QUEUED);

                for (String body : messages) {

                    if (body.startsWith("vfs:/") && (body.split(" ").length == 1))
                    {
                        String offerId = UUID.randomUUID().toString();
                        String mimeType = URLConnection.guessContentTypeFromName(body);
                        if (mimeType != null) {

                            if (mimeType.startsWith("text"))
                                mimeType = "text/plain";

                            offerData(offerId, body, mimeType);
                        }
                    }
                    else {
                        sendMessage(body, false);
                    }
                }
            }

            c.close();

            sendingPostponed = false;
        }
    }
 
Example 17
/**
 * @return the mime type (if any) that is associated with the file
 *         extension. Returns null if no corresponding mime type exists.
 */
@CalledByNative
static public String getMimeTypeFromExtension(String extension) {
    return URLConnection.guessContentTypeFromName("foo." + extension);
}
 
Example 18
Source Project: htmlunit   File: FileReader.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Reads the contents of the specified {@link Blob} or {@link File}.
 * @param object the {@link Blob} or {@link File} from which to read
 * @throws IOException if an error occurs
 */
@JsxFunction
public void readAsDataURL(final Object object) throws IOException {
    readyState_ = LOADING;
    final java.io.File file = ((File) object).getFile();

    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        FileUtils.copyFile(file, bos);

        final byte[] bytes = bos.toByteArray();
        final String value = new String(new Base64().encode(bytes), StandardCharsets.US_ASCII);
        final BrowserVersion browserVersion = getBrowserVersion();

        result_ = "data:";

        String contentType;
        if (value.isEmpty()) {
            contentType = URLConnection.guessContentTypeFromName(file.getName());
        }
        else {
            contentType = Files.probeContentType(file.toPath());
            // this is a bit weak, on linux we get different results
            // e.g. 'application/octet-stream' for a file with random bits
            // instead of null on windows
        }

        if (getBrowserVersion().hasFeature(JS_FILEREADER_EMPTY_NULL)) {
            if (value.isEmpty()) {
                result_ = "null";
            }
            else {
                if (contentType != null) {
                    result_ += contentType;
                }
                result_ += ";base64," + value;
            }
        }
        else {
            final boolean includeConentType = browserVersion.hasFeature(JS_FILEREADER_CONTENT_TYPE);
            if (!value.isEmpty() || includeConentType) {
                if (contentType == null) {
                    contentType = MimeType.APPLICATION_OCTET_STREAM;
                }
                result_ += contentType + ";base64," + value;
            }
        }
    }
    readyState_ = DONE;

    final Event event = new Event(this, Event.TYPE_LOAD);
    fireEvent(event);
}
 
Example 19
Source Project: SmartIM4IntelliJ   File: WXChatConsole.java    License: Apache License 2.0 4 votes vote down vote up
@Override public void sendFileInternal(final String file) {
    // error("暂不支持,敬请关注 https://github.com/Jamling/SmartIM 或
    // https://github.com/Jamling/SmartQQ4IntelliJ 最新动态");
    final File f = new File(file);
    final WechatClient client = getClient();
    if (!checkClient(client)) {
        return;
    }

    String ext = FileUtils.getExtension(f.getPath()).toLowerCase();
    String mimeType = URLConnection.guessContentTypeFromName(f.getName());
    String media = "pic";
    int type = WechatMessage.MSGTYPE_IMAGE;
    String content = "";
    if (Arrays.asList("png", "jpg", "jpeg", "bmp").contains(ext)) {
        type = WechatMessage.MSGTYPE_IMAGE;
        media = "pic";
    } else if ("gif".equals(ext)) {
        type = WechatMessage.MSGTYPE_EMOTICON;
        media = "doc";
    } else {
        type = WechatMessage.MSGTYPE_FILE;
        media = "doc";
    }

    final UploadInfo uploadInfo = client.uploadMedia(f, mimeType, media);

    if (uploadInfo == null) {
        error("上传失败");
        return;
    }
    String link = StringUtils.file2url(file);
    String label = file.replace('\\', '/');
    String input = null;
    if (type == WechatMessage.MSGTYPE_EMOTICON || type == WechatMessage.MSGTYPE_IMAGE) {
        input = String.format("<img src=\"%s\" border=\"0\" alt=\"%s\"", link, label);
        if (uploadInfo.CDNThumbImgWidth > 0) {
            input += " width=\"" + uploadInfo.CDNThumbImgWidth + "\"";
        }
        if (uploadInfo.CDNThumbImgHeight > 0) {
            input += " height=\"" + uploadInfo.CDNThumbImgHeight + "\"";
        }
        input = String.format("<a href=\"%s\" title=\"%s\">%s</a>", link, link, input);
    } else {
        input = String.format("<a href=\"%s\" title=\"%s\">%s</a>", link, label, label);
        content = client.createFileMsgContent(f, uploadInfo.MediaId);
    }

    final WechatMessage m = client.createMessage(type, content, contact);
    m.text = input;
    m.MediaId = uploadInfo.MediaId;

    client.sendMessage(m, contact);
    if (!hideMyInput()) {
        String name = client.getAccount().getName();
        String msg = WXUtils.formatHtmlOutgoing(name, m.text, false);
        insertDocument(msg);
        IMHistoryManager.getInstance().save(getHistoryDir(), getHistoryFile(), msg);
    }
}
 
Example 20
protected static String writeFileToGcs(String googleId, String filename) throws IOException {
    byte[] image = FileHelper.readFileAsBytes(filename);
    String contentType = URLConnection.guessContentTypeFromName(filename);
    return GoogleCloudStorageHelper.writeImageDataToGcs(googleId, image, contentType);
}