Search in sources :

Example 11 with FileNameMap

use of java.net.FileNameMap in project okhttp-OkGo by jeasonlzy.

the class HttpUtils method guessMimeType.

/**
 * 根据文件名获取MIME类型
 */
public static MediaType guessMimeType(String fileName) {
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    // 解决文件名中含有#号异常的问题
    fileName = fileName.replace("#", "");
    String contentType = fileNameMap.getContentTypeFor(fileName);
    if (contentType == null) {
        return HttpParams.MEDIA_TYPE_STREAM;
    }
    return MediaType.parse(contentType);
}
Also used : FileNameMap(java.net.FileNameMap)

Example 12 with FileNameMap

use of java.net.FileNameMap in project OpenMEAP by OpenMEAP.

the class WebViewServlet method service.

@SuppressWarnings("unchecked")
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    logger.trace("in service");
    ModelManager mgr = getModelManager();
    GlobalSettings settings = mgr.getGlobalSettings();
    String validTempPath = settings.validateTemporaryStoragePath();
    if (validTempPath != null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, validTempPath);
    }
    String pathInfo = request.getPathInfo();
    String[] pathParts = pathInfo.split("[/]");
    if (pathParts.length < 4) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    String remove = pathParts[1] + "/" + pathParts[2] + "/" + pathParts[3];
    String fileRelative = pathInfo.replace(remove, "");
    String applicationNameString = URLDecoder.decode(pathParts[APP_NAME_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    String archiveHash = URLDecoder.decode(pathParts[APP_VER_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    Application app = mgr.getModelService().findApplicationByName(applicationNameString);
    ApplicationArchive arch = mgr.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archiveHash, "MD5");
    String authSalt = app.getProxyAuthSalt();
    String authToken = URLDecoder.decode(pathParts[AUTH_TOKEN_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    try {
        if (!AuthTokenProvider.validateAuthToken(authSalt, authToken)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (DigestException e1) {
        throw new GenericRuntimeException(e1);
    }
    File fileFull = new File(arch.getExplodedPath(settings.getTemporaryStoragePath()).getAbsolutePath() + "/" + fileRelative);
    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(fileFull.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(fileFull.length()).intValue());
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            // response.setStatus(HttpServletResponse.SC_FOUND);
            inputStream = new FileInputStream(fileFull);
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileNotFoundException(java.io.FileNotFoundException) GlobalSettings(com.openmeap.model.dto.GlobalSettings) IOException(java.io.IOException) ModelManager(com.openmeap.model.ModelManager) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) FileNameMap(java.net.FileNameMap) ApplicationArchive(com.openmeap.model.dto.ApplicationArchive) FileInputStream(java.io.FileInputStream) DigestException(com.openmeap.digest.DigestException) Application(com.openmeap.model.dto.Application) File(java.io.File)

Example 13 with FileNameMap

use of java.net.FileNameMap in project robovm by robovm.

the class OldFileNameMapTest method test_getContentTypeFor.

public void test_getContentTypeFor() {
    String[] files = { "text", "txt", "htm", "html" };
    String[] mimeTypes = { "text/plain", "text/plain", "text/html", "text/html" };
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    for (int i = 0; i < files.length; i++) {
        String mimeType = fileNameMap.getContentTypeFor("test." + files[i]);
        assertEquals("getContentTypeFor returns incorrect MIME type for " + files[i], mimeTypes[i], mimeType);
    }
}
Also used : FileNameMap(java.net.FileNameMap)

Example 14 with FileNameMap

use of java.net.FileNameMap in project robovm by robovm.

the class URLConnectionTest method test_setFileNameMapLjava_net_FileNameMap.

/**
     * @throws IOException
     * {@link java.net.URLConnection#setFileNameMap(java.net.FileNameMap)}
     */
public void test_setFileNameMapLjava_net_FileNameMap() throws IOException {
    FileNameMap mapOld = URLConnection.getFileNameMap();
    // nothing happens if set null
    URLConnection.setFileNameMap(null);
    // take no effect
    assertNotNull(URLConnection.getFileNameMap());
    try {
        URLConnection.setFileNameMap(new java.net.FileNameMap() {

            public String getContentTypeFor(String fileName) {
                if (fileName == null || fileName.length() < 1)
                    return null;
                String name = fileName.toLowerCase();
                String type = null;
                if (name.endsWith(".xml"))
                    type = "text/xml";
                else if (name.endsWith(".dtd"))
                    type = "text/dtd";
                else if (name.endsWith(".pdf"))
                    type = "application/pdf";
                else if (name.endsWith(".zip"))
                    type = "application/zip";
                else if (name.endsWith(".gif"))
                    type = "image/gif";
                else
                    type = "application/unknown";
                return type;
            }
        });
        FileNameMap mapNew = URLConnection.getFileNameMap();
        assertEquals("application/pdf", mapNew.getContentTypeFor(".pdf"));
        assertEquals("application/zip", mapNew.getContentTypeFor(".zip"));
        assertEquals("image/gif", mapNew.getContentTypeFor(".gif"));
    } finally {
        URLConnection.setFileNameMap(mapOld);
    }
}
Also used : FileNameMap(java.net.FileNameMap) FileNameMap(java.net.FileNameMap)

Example 15 with FileNameMap

use of java.net.FileNameMap in project HongsCORE by ihongs.

the class UploadHelper method upload.

/**
 * 检查文件对象并写入目标目录
 * 检查当前文件
 * @param file
 * @param subn
 * @return
 * @throws Wrong
 */
public File upload(File file, String subn) throws Wrong {
    if (file == null) {
        setResultName("", null);
        return null;
    }
    if (file.exists() == false) {
        throw new Wrong("core.file.upload.not.exists");
    }
    /**
     * 从文件名中解析类型和提取扩展名
     */
    // type = MimeUtil.getMimeTypes (file).toString(   );
    // extn = MimeUtil.getExtension (file);
    FileNameMap nmap = URLConnection.getFileNameMap();
    String extn = file.getName();
    String type = nmap.getContentTypeFor(extn);
    extn = extn.substring(extn.lastIndexOf('.') + 1);
    chkTypeOrExtn(type, extn);
    setResultName(subn, extn);
    /**
     * 原始文件与目标文件不同才需移动
     */
    File dist = new File(getResultPath());
    if (!dist.equals(file)) {
        File dirt = dist.getParentFile();
        if (!dirt.isDirectory()) {
            dirt.mkdirs();
        }
        file.renameTo(dist);
    }
    return dist;
}
Also used : Wrong(app.hongs.util.verify.Wrong) FileNameMap(java.net.FileNameMap) File(java.io.File)

Aggregations

FileNameMap (java.net.FileNameMap)34 File (java.io.File)7 SimpleDateFormat (java.text.SimpleDateFormat)4 FileInputStream (java.io.FileInputStream)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 DigestException (com.openmeap.digest.DigestException)2 GlobalSettings (com.openmeap.model.dto.GlobalSettings)2 GenericRuntimeException (com.openmeap.util.GenericRuntimeException)2 BufferedInputStream (java.io.BufferedInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 OutputStream (java.io.OutputStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Map (java.util.Map)2 Wrong (app.hongs.util.verify.Wrong)1 Category (com.agiletec.aps.system.services.category.Category)1 BaseResourceDataBean (com.agiletec.plugins.jacms.aps.system.services.resource.model.BaseResourceDataBean)1 ModelManager (com.openmeap.model.ModelManager)1 Application (com.openmeap.model.dto.Application)1 ApplicationArchive (com.openmeap.model.dto.ApplicationArchive)1