Search in sources :

Example 26 with MimetypesFileTypeMap

use of javax.activation.MimetypesFileTypeMap in project clearth by exactpro.

the class ReportsArchiver method getZipSelectedReports.

public StreamedContent getZipSelectedReports(boolean realtimeSnapshot, ReportsInfo reportInfoPath) {
    try {
        List<File> filesToZip = new ArrayList<>();
        List<String> names = new ArrayList<>();
        getFilesForZipReports(filesToZip, names, getFilteredReports(realtimeSnapshot), reportInfoPath);
        if (filesToZip.size() == 0) {
            return null;
        }
        File result = new File(ClearThCore.tempPath() + UserInfoUtils.getUserName() + "_reports.zip");
        zipFiles(result, filesToZip, names);
        return new DefaultStreamedContent(new FileInputStream(result), new MimetypesFileTypeMap().getContentType(result), "reports.zip");
    } catch (IOException e) {
        MessageUtils.addErrorMessage("Could not download reports", ExceptionUtils.getDetailedMessage(e));
        logger.debug("Could not download reports", e);
        return null;
    }
}
Also used : DefaultStreamedContent(org.primefaces.model.DefaultStreamedContent) MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 27 with MimetypesFileTypeMap

use of javax.activation.MimetypesFileTypeMap in project clearth by exactpro.

the class ReportsArchiver method getZipSelectedReportsWithLogs.

public StreamedContent getZipSelectedReportsWithLogs(File shortLog, ReportsInfo reportPath) throws IOException {
    List<File> filesToZip = new ArrayList<>();
    List<String> names = new ArrayList<>();
    filesToZip.add(shortLog);
    names.add(null);
    getFilesForZipReports(filesToZip, names, getFilteredReports(false), reportPath);
    File result = new File(ClearThCore.tempPath() + UserInfoUtils.getUserName() + "_reports_logs.zip");
    zipFiles(result, filesToZip, names);
    return new DefaultStreamedContent(new FileInputStream(result), new MimetypesFileTypeMap().getContentType(result), "reports_logs.zip");
}
Also used : DefaultStreamedContent(org.primefaces.model.DefaultStreamedContent) MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) ArrayList(java.util.ArrayList) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 28 with MimetypesFileTypeMap

use of javax.activation.MimetypesFileTypeMap in project jiguang-java-client-common by jpush.

the class NativeHttpClient method formUpload.

private String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap, String contentType, String requestMethod) {
    String res = "";
    HttpURLConnection conn = null;
    // boundary就是request头和上传文件内容的分隔符
    String BOUNDARY = "---------------------------" + System.currentTimeMillis();
    try {
        URL url = new URL(urlStr);
        conn = getConnectionByUrl(url);
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(30000);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod(requestMethod);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Authorization", _authCode);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        OutputStream out = new DataOutputStream(conn.getOutputStream());
        // text
        if (textMap != null) {
            StringBuffer strBuf = new StringBuffer();
            Iterator iter = textMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String inputName = (String) entry.getKey();
                String inputValue = (String) entry.getValue();
                if (inputValue == null) {
                    continue;
                }
                strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                strBuf.append(inputValue);
            }
            out.write(strBuf.toString().getBytes());
        }
        // file
        if (fileMap != null) {
            Iterator iter = fileMap.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String inputName = (String) entry.getKey();
                String inputValue = (String) entry.getValue();
                if (inputValue == null) {
                    continue;
                }
                File file = new File(inputValue);
                String filename = file.getName();
                // 没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
                contentType = new MimetypesFileTypeMap().getContentType(file);
                // contentType非空采用filename匹配默认的图片类型
                if (!"".equals(contentType)) {
                    if (filename.endsWith(".png")) {
                        contentType = "image/png";
                    } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
                        contentType = "image/jpeg";
                    } else if (filename.endsWith(".gif")) {
                        contentType = "image/gif";
                    } else if (filename.endsWith(".ico")) {
                        contentType = "image/image/x-icon";
                    }
                }
                if (contentType == null || "".equals(contentType)) {
                    contentType = "application/octet-stream";
                }
                StringBuffer strBuf = new StringBuffer();
                strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
                strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
                out.write(strBuf.toString().getBytes());
                DataInputStream in = new DataInputStream(new FileInputStream(file));
                int bytes = 0;
                byte[] bufferOut = new byte[1024];
                while ((bytes = in.read(bufferOut)) != -1) {
                    out.write(bufferOut, 0, bytes);
                }
                in.close();
            }
        }
        byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
        out.write(endData);
        out.flush();
        out.close();
        // 读取返回数据
        StringBuffer strBuf = new StringBuffer();
        InputStream is = null;
        int responseCode = conn.getResponseCode();
        BufferedReader reader;
        if (responseCode == 200) {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } else {
            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
        }
        String line = null;
        while ((line = reader.readLine()) != null) {
            strBuf.append(line).append("\n");
        }
        res = strBuf.toString();
        reader.close();
        reader = null;
    } catch (FileNotFoundException e) {
        LOG.error("formUpload error", e);
        throw new RuntimeException("formUpload error", e);
    } catch (Exception e) {
        LOG.error("formUpload error", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
            conn = null;
        }
    }
    return res;
}
Also used : MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) CertificateException(java.security.cert.CertificateException) APIConnectionException(cn.jiguang.common.resp.APIConnectionException) APIRequestException(cn.jiguang.common.resp.APIRequestException) Iterator(java.util.Iterator) MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) Map(java.util.Map)

Example 29 with MimetypesFileTypeMap

use of javax.activation.MimetypesFileTypeMap in project learn-netty4 by ddean2009.

the class HttpFileServerHandler method setContentTypeHeader.

/**
 * 根据文件的名字设置合适的content-type
 */
private static void setContentTypeHeader(HttpResponse response, File file) {
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath()));
}
Also used : MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap)

Example 30 with MimetypesFileTypeMap

use of javax.activation.MimetypesFileTypeMap in project twitter-2-weibo by rjyo.

the class HttpClient method multPartURL.

public Response multPartURL(String fileParamName, String url, PostParameter[] params, File file, boolean authenticated) throws WeiboException {
    PostMethod post = new PostMethod(url);
    org.apache.commons.httpclient.HttpClient client = getHttpClient();
    try {
        long t = System.currentTimeMillis();
        Part[] parts = null;
        if (params == null) {
            parts = new Part[1];
        } else {
            parts = new Part[params.length + 1];
        }
        if (params != null) {
            int i = 0;
            for (PostParameter entry : params) {
                parts[i++] = new StringPart(entry.getName(), (String) entry.getValue());
            }
        }
        FilePart filePart = new FilePart(fileParamName, file.getName(), file, new MimetypesFileTypeMap().getContentType(file), "UTF-8");
        filePart.setTransferEncoding("binary");
        parts[parts.length - 1] = filePart;
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        List<Header> headers = new ArrayList<Header>();
        if (authenticated) {
            if (oauth == null) {
            }
            String authorization = null;
            if (null != oauth) {
                // use OAuth
                authorization = oauth.generateAuthorizationHeader("POST", url, params, oauthToken);
            } else {
                throw new IllegalStateException("Neither user ID/password combination nor OAuth consumer key/secret combination supplied");
            }
            headers.add(new Header("Authorization", authorization));
            log("Authorization: " + authorization);
        }
        client.getHostConfiguration().getParams().setParameter("http.default-headers", headers);
        client.executeMethod(post);
        Response response = new Response();
        response.setResponseAsString(post.getResponseBodyAsString());
        response.setStatusCode(post.getStatusCode());
        log("multPartURL URL:" + url + ", result:" + response + ", time:" + (System.currentTimeMillis() - t));
        return response;
    } catch (Exception ex) {
        throw new WeiboException(ex.getMessage(), ex, -1);
    } finally {
        post.releaseConnection();
        client = null;
    }
}
Also used : MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) PostMethod(org.apache.commons.httpclient.methods.PostMethod) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) ArrayList(java.util.ArrayList) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) IOException(java.io.IOException) WeiboException(weibo4j.WeiboException) AccessControlException(java.security.AccessControlException) WeiboException(weibo4j.WeiboException) Header(org.apache.commons.httpclient.Header) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part)

Aggregations

MimetypesFileTypeMap (javax.activation.MimetypesFileTypeMap)63 File (java.io.File)19 IOException (java.io.IOException)15 FileInputStream (java.io.FileInputStream)7 InputStream (java.io.InputStream)7 DefaultStreamedContent (org.primefaces.model.DefaultStreamedContent)6 URL (java.net.URL)4 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 FileNotFoundException (java.io.FileNotFoundException)3 FileNameMap (java.net.FileNameMap)3 HttpURLConnection (java.net.HttpURLConnection)3 MimeType (javax.activation.MimeType)3 MimeTypeParseException (javax.activation.MimeTypeParseException)3 Response (javax.ws.rs.core.Response)3 Before (org.junit.Before)3 Test (org.junit.Test)3 Failure (org.junit.runner.notification.Failure)3 InvalidKeyException (java.security.InvalidKeyException)2