Example usage for java.net URLConnection guessContentTypeFromName

List of usage examples for java.net URLConnection guessContentTypeFromName

Introduction

In this page you can find the example usage for java.net URLConnection guessContentTypeFromName.

Prototype

public static String guessContentTypeFromName(String fname) 

Source Link

Document

Tries to determine the content type of an object, based on the specified "file" component of a URL.

Usage

From source file:UploadTest.java

@Test
public void form_test() {
    try {//from w w  w . ja  v  a 2  s  .c  o m
        url = new URL("http://localhost:9000/resource/frl:6376982/data");
        httpCon = (HttpURLConnection) url.openConnection();
        String userpass = user + ":" + password;
        basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        httpCon.setRequestProperty("Authorization", basicAuth);
        String fieldName = "data";
        File uploadFile = new File("/home/raul/test/frl%3A6376982/6376990.pdf");
        String boundary = "" + System.currentTimeMillis() + "";

        httpCon.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        httpCon.setRequestProperty("file", "6376986.pdf");

        httpCon.setUseCaches(false);
        httpCon.setDoOutput(true);
        httpCon.setDoInput(true);

        httpCon.setRequestMethod("PUT");

        OutputStream outputStream = null;
        try {
            outputStream = (httpCon.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String LINE_FEED = "\r\n";
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        System.out.println("--" + boundary + (LINE_FEED));
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        System.out.println("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName
                + "\"" + (LINE_FEED));
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
        System.out.println("Content-Type: " + URLConnection.guessContentTypeFromName(fileName) + (LINE_FEED));
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        System.out.println("Content-Transfer-Encoding: binary" + (LINE_FEED));
        writer.append(LINE_FEED);

        writer.flush();

        fileToOutputStream(uploadFile, outputStream);

        // httpCon.getInputStream();
        try {
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        writer.append(LINE_FEED);
        writer.flush();
        writer.close();
        httpCon.disconnect();

        try {
            System.out.println(httpCon.getResponseCode());
            System.out.println(httpCon.getResponseMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.awesomeapp.messenger.ui.MessageListItem.java

private void showAudioPlayer(String mimeType, Uri mediaUri, int id, MessageViewHolder holder) throws Exception {
    /* 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  . j  av  a  2  s .c o m
                mimeType = guessed;
        }
    }

    holder.setOnClickListenerMediaThumbnail(mimeType, mediaUri);
    mHolder.mTextViewForMessages.setText("");
    mAudioPlayer = new AudioPlayer(getContext(), mediaUri.getPath(), mimeType, mHolder.mVisualizerView,
            mHolder.mTextViewForMessages);
    holder.mContainer.setBackgroundResource(android.R.color.transparent);
}

From source file:edu.umn.cs.spatialHadoop.nasa.ShahedServer.java

/**
 * Tries to load the given resource name frmo class path if it exists.
 * Used to serve static files such as HTML pages, images and JavaScript files.
 * @param target//from w w  w  .  ja  va2 s.c  o m
 * @param response
 * @throws IOException
 */
private void tryToLoadStaticResource(String target, HttpServletResponse response) throws IOException {
    LOG.info("Loading resource " + target);
    // Try to load this resource as a static page
    InputStream resource = getClass().getResourceAsStream("/webapps/static/shahedfrontend" + target);
    if (resource == null) {
        reportError(response, "Cannot load resource '" + target + "'", null);
        return;
    }
    byte[] buffer = new byte[1024 * 1024];
    ServletOutputStream outResponse = response.getOutputStream();
    int size;
    while ((size = resource.read(buffer)) != -1) {
        outResponse.write(buffer, 0, size);
    }
    resource.close();
    outResponse.close();
    response.setStatus(HttpServletResponse.SC_OK);
    if (target.endsWith(".js")) {
        response.setContentType("application/javascript");
    } else if (target.endsWith(".css")) {
        response.setContentType("text/css");
    } else {
        response.setContentType(URLConnection.guessContentTypeFromName(target));
    }
    final DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss ZZZ");
    final long year = 1000L * 60 * 60 * 24 * 365;
    // Expires in a year
    response.addHeader("Expires", format.format(new Date().getTime() + year));
}

From source file:com.pavlospt.rxfile.RxFile.java

public static Observable<String> getFileType(String filePath) {
    logDebug("Filepath in getFileType: " + filePath);
    final String[] parts = filePath.split("/");
    return Observable.fromCallable(new Func0<String>() {
        @Override//w  ww.j a v a2s  . co  m
        public String call() {
            return parts.length > 0 ? URLConnection.guessContentTypeFromName(parts[0]) : null;
        }
    });
}

From source file:com.workfront.api.StreamClient.java

private void addFileToRequest(String boundary, Writer out, OutputStream binaryStream, File file)
        throws IOException {
    out.append("--" + boundary).append(NEW_LINE);
    out.append("Content-Disposition: form-data; name=\"uploadedFile\"; filename=\"" + file.getName() + "\"")
            .append(NEW_LINE);//from  w w w . j  a va2s  .co  m
    out.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append(NEW_LINE);
    out.append("Content-Transfer-Encoding: binary").append(NEW_LINE).append(NEW_LINE);
    out.flush();

    FileInputStream inputStream = new FileInputStream(file);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        binaryStream.write(buffer, 0, bytesRead);
    }
    binaryStream.flush();
    inputStream.close();

    out.append(NEW_LINE);
    out.flush();
    out.append("--").append(boundary).append("--").append(NEW_LINE);
}

From source file:cn.org.once.cstack.controller.FileController.java

/**
 * Edit or Download for FileExplorer feature
 *
 * @param applicationName//from  w  ww . ja va  2s  .  co  m
 * @param containerId
 * @param path
 * @param fileName
 * @param request
 * @param response
 * @param editionMode
 * @throws ServiceException
 * @throws CheckException
 * @throws IOException
 */
private void downloadOrEditFile(final String applicationName, final String containerId, String path,
        final String fileName, HttpServletRequest request, HttpServletResponse response, Boolean editionMode)
        throws ServiceException, CheckException, IOException {

    if (logger.isDebugEnabled()) {
        logger.debug("containerId:" + containerId);
        logger.debug("applicationName:" + applicationName);
        logger.debug("fileName:" + fileName);
    }

    User user = authentificationUtils.getAuthentificatedUser();
    Application application = applicationService.findByNameAndUser(user, applicationName);

    String mimeType = URLConnection.guessContentTypeFromName(fileName);
    String contentDisposition = String.format("attachment; filename=%s", fileName);
    response.setContentType(mimeType);
    response.setHeader("Content-Disposition", contentDisposition);
    if (!editionMode) {
        response.setHeader("Content-Description", "File Transfer");
        response.setContentType("utf-8");
    }

    // We must be sure there is no running action before starting new one
    this.authentificationUtils.canStartNewAction(user, application, locale);
    try (OutputStream stream = response.getOutputStream()) {
        fileService.getFileFromContainer(containerId, "/" + path + "/" + fileName, stream);
        stream.flush(); // commits response!
        stream.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:com.echopf.ECHOQuery.java

/**
 * Sends a HTTP request with optional request contents/parameters.
 * @param path a request url path/*from  www .  ja  va  2 s .  c  om*/
 * @param httpMethod a request method (GET/POST/PUT/DELETE)
 * @param data request contents/parameters
 * @param multipart use multipart/form-data to encode the contents
 * @throws ECHOException
 */
public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart)
        throws ECHOException {
    final String secureDomain = ECHO.secureDomain;
    if (secureDomain == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    String baseUrl = new StringBuilder("https://").append(secureDomain).toString();
    String url = new StringBuilder(baseUrl).append("/").append(path).toString();

    HttpsURLConnection httpClient = null;

    try {
        URL urlObj = new URL(url);

        StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/");

        // Append the QueryString contained in path
        boolean isContainQuery = urlObj.getQuery() != null;
        if (isContainQuery)
            apiUrl.append("?").append(urlObj.getQuery());

        // Append the QueryString from data
        if (httpMethod.equals("GET") && data != null) {
            boolean firstItem = true;
            Iterator<?> iter = data.keys();
            while (iter.hasNext()) {
                if (firstItem && !isContainQuery) {
                    firstItem = false;
                    apiUrl.append("?");
                } else {
                    apiUrl.append("&");
                }
                String key = (String) iter.next();
                String value = data.optString(key);
                apiUrl.append(key);
                apiUrl.append("=");
                apiUrl.append(value);
            }
        }

        URL urlConn = new URL(apiUrl.toString());
        httpClient = (HttpsURLConnection) urlConn.openConnection();
    } catch (IOException e) {
        throw new ECHOException(e);
    }

    final String appId = ECHO.appId;
    final String appKey = ECHO.appKey;
    final String accessToken = ECHO.accessToken;

    if (appId == null || appKey == null)
        throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`.");

    InputStream responseInputStream = null;

    try {
        httpClient.setRequestMethod(httpMethod);
        httpClient.addRequestProperty("X-ECHO-APP-ID", appId);
        httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey);

        // Set access token
        if (accessToken != null && !accessToken.isEmpty())
            httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken);

        // Build content
        if (!httpMethod.equals("GET") && data != null) {

            httpClient.setDoOutput(true);
            httpClient.setChunkedStreamingMode(0); // use default chunk size

            if (multipart == false) { // application/json

                httpClient.addRequestProperty("CONTENT-TYPE", "application/json");
                BufferedWriter wrBuffer = new BufferedWriter(
                        new OutputStreamWriter(httpClient.getOutputStream()));
                wrBuffer.write(data.toString());
                wrBuffer.close();

            } else { // multipart/form-data

                final String boundary = "*****" + UUID.randomUUID().toString() + "*****";
                final String twoHyphens = "--";
                final String lineEnd = "\r\n";
                final int maxBufferSize = 1024 * 1024 * 3;

                httpClient.setRequestMethod("POST");
                httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary);

                final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream());

                try {

                    JSONObject postData = new JSONObject();
                    postData.putOpt("method", httpMethod);
                    postData.putOpt("data", data);

                    new Object() {

                        public void post(JSONObject data, List<String> currentKeys)
                                throws JSONException, IOException {

                            Iterator<?> keys = data.keys();
                            while (keys.hasNext()) {
                                String key = (String) keys.next();
                                List<String> newKeys = new ArrayList<String>(currentKeys);
                                newKeys.add(key);

                                Object val = data.get(key);

                                // convert JSONArray into JSONObject
                                if (val instanceof JSONArray) {
                                    JSONArray array = (JSONArray) val;
                                    JSONObject val2 = new JSONObject();

                                    for (Integer i = 0; i < array.length(); i++) {
                                        val2.putOpt(i.toString(), array.get(i));
                                    }

                                    val = val2;
                                }

                                // build form-data name
                                String name = "";
                                for (int i = 0; i < newKeys.size(); i++) {
                                    String key2 = newKeys.get(i);
                                    name += (i == 0) ? key2 : "[" + key2 + "]";
                                }

                                if (val instanceof ECHOFile) {

                                    ECHOFile file = (ECHOFile) val;
                                    if (file.getLocalBytes() == null)
                                        continue;

                                    InputStream fileInputStream = new ByteArrayInputStream(
                                            file.getLocalBytes());

                                    if (fileInputStream != null) {

                                        String mimeType = URLConnection
                                                .guessContentTypeFromName(file.getFileName());

                                        // write header
                                        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name
                                                + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd);
                                        outputStream.writeBytes("Content-Type: " + mimeType + lineEnd);
                                        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
                                        outputStream.writeBytes(lineEnd);

                                        // write content
                                        int bytesAvailable, bufferSize, bytesRead;
                                        do {
                                            bytesAvailable = fileInputStream.available();
                                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                                            byte[] buffer = new byte[bufferSize];
                                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                                            if (bytesRead <= 0)
                                                break;
                                            outputStream.write(buffer, 0, bufferSize);
                                        } while (true);

                                        fileInputStream.close();
                                        outputStream.writeBytes(lineEnd);
                                    }

                                } else if (val instanceof JSONObject) {

                                    this.post((JSONObject) val, newKeys);

                                } else {

                                    String data2 = null;
                                    try { // in case of boolean
                                        boolean bool = data.getBoolean(key);
                                        data2 = bool ? "true" : "";
                                    } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false".
                                        data2 = val.toString().trim();
                                    }

                                    // write header
                                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                                    outputStream.writeBytes(
                                            "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd);
                                    outputStream
                                            .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
                                    outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd);
                                    outputStream.writeBytes(lineEnd);

                                    // write content
                                    byte[] bytes = data2.getBytes();
                                    for (int i = 0; i < bytes.length; i++) {
                                        outputStream.writeByte(bytes[i]);
                                    }

                                    outputStream.writeBytes(lineEnd);
                                }

                            }
                        }
                    }.post(postData, new ArrayList<String>());

                } catch (JSONException e) {

                    throw new ECHOException(e);

                } finally {

                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.flush();
                    outputStream.close();

                }
            }

        } else {

            httpClient.addRequestProperty("CONTENT-TYPE", "application/json");

        }

        if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) {
            responseInputStream = httpClient.getInputStream();
        }

    } catch (IOException e) {

        // get http response code
        int errorCode = -1;

        try {
            errorCode = httpClient.getResponseCode();
        } catch (IOException e1) {
            throw new ECHOException(e1);
        }

        // get error contents
        JSONObject responseObj;
        try {
            String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream());
            responseObj = new JSONObject(jsonStr);
        } catch (JSONException e1) {
            if (errorCode == 404) {
                throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found.");
            }

            throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format.");
        }

        //
        if (responseObj != null) {
            int code = responseObj.optInt("error_code");
            String message = responseObj.optString("error_message");

            if (code != 0 || !message.equals("")) {
                JSONObject details = responseObj.optJSONObject("error_details");
                if (details == null) {
                    throw new ECHOException(code, message);
                } else {
                    throw new ECHOException(code, message, details);
                }
            }
        }

        throw new ECHOException(e);

    }

    return responseInputStream;
}

From source file:org.kontalk.util.MediaStorage.java

/** Guesses the MIME type of an {@link Uri}. */
public static String getType(Context context, Uri uri) {
    // try Android detection
    String mime = context.getContentResolver().getType(uri);

    // the following methods actually use the same underlying implementation
    // (libcore.net.MimeUtils), but that could change in the future so no
    // hurt in trying them all just in case.
    // Lowercasing the filename seems to help in detecting the correct MIME.

    if (mime == null)
        // try WebKit detection
        mime = MimeTypeMap.getSingleton()
                .getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(uri.toString()).toLowerCase());
    if (mime == null)
        // try Java detection
        mime = URLConnection.guessContentTypeFromName(uri.toString().toLowerCase());
    return mime;// ww w .  j a  v  a2 s .c  o m
}

From source file:com.gh4a.utils.HttpImageGetter.java

private Drawable loadImageForUrl(String source) {
    Bitmap bitmap = null;/*from   w ww  .  j a  v  a2 s.c  o  m*/

    if (!mDestroyed) {
        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 = renderSvgToBitmap(mContext.getResources(), is, mWidth, mHeight);
                } else {
                    boolean isGif = mime != null && mime.startsWith("image/gif");
                    if (!isGif || canLoadGif()) {
                        output = File.createTempFile("image", ".tmp", mCacheDir);
                        if (FileUtils.save(output, is)) {
                            if (isGif) {
                                GifDrawable d = new GifDrawable(output);
                                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                                return d;
                            } else {
                                bitmap = getBitmap(output, mWidth, mHeight);
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            // fall through to showing the error 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 (mDestroyed && bitmap != null) {
            bitmap.recycle();
            bitmap = null;
        }
    }

    if (bitmap == null) {
        return mErrorDrawable;
    }

    BitmapDrawable drawable = new LoadedBitmapDrawable(mContext.getResources(), bitmap);
    drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
    return drawable;
}

From source file:org.mifos.customers.client.struts.actionforms.ClientCustActionForm.java

private void validatePicture(HttpServletRequest request, ActionErrors errors) throws PageExpiredException {
    if (picture != null && StringUtils.isNotBlank(picture.getFileName())) {
        if (picture.getFileSize() > ClientConstants.PICTURE_ALLOWED_SIZE) {
            addInvalidPictureError(errors, "image size should be less then 300K");
        }/*from   w  w  w  . java2 s.c o m*/
        try {
            String contentType = URLConnection.guessContentTypeFromStream(picture.getInputStream());
            if (contentType == null) {
                contentType = URLConnection.guessContentTypeFromName(picture.getFileName());
            }

            if (contentType == null || !(contentType.equals("image/jpeg") || contentType.equals("image/gif")
                    || contentType.equals("image/jpg") || contentType.equals("image/png"))) {
                addInvalidPictureError(errors, "allowed only jpg/gif/png");
            }
        } catch (IOException e) {
            addInvalidPictureError(errors, e.getMessage());
        }
    }
}