Search in sources :

Example 26 with FileNameMap

use of java.net.FileNameMap in project collect by opendatakit.

the class FileUtils method getMimeType.

public static String getMimeType(File file) {
    String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath());
    String mimeType = extension != null ? MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) : null;
    if (mimeType == null || mimeType.isEmpty()) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        mimeType = fileNameMap.getContentTypeFor(file.getAbsolutePath());
    }
    if (mimeType == null || mimeType.isEmpty()) {
        mimeType = URLConnection.guessContentTypeFromName(file.getName());
    }
    return mimeType;
}
Also used : LocalizedApplicationKt.getLocalizedString(org.odk.collect.strings.localization.LocalizedApplicationKt.getLocalizedString) FileNameMap(java.net.FileNameMap)

Example 27 with FileNameMap

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

the class ApplicationManagementServlet method handleArchiveDownload.

private Result handleArchiveDownload(HttpServletRequest request, HttpServletResponse response) {
    Result res = new Result();
    Error err = new Error();
    res.setError(err);
    GlobalSettings settings = modelManager.getGlobalSettings();
    Map properties = this.getServicesWebProperties();
    String nodeKey = (String) properties.get("clusterNodeUrlPrefix");
    ClusterNode clusterNode = settings.getClusterNode(nodeKey);
    if (nodeKey == null || clusterNode == null) {
        // TODO: create a configuration error code
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage("A configuration is missing.  Please consult the error logs.");
        logger.error("For each node in the cluster, the property or environment variable OPENMEAP_CLUSTER_NODE_URL_PREFIX must match the \"Service Url Prefix\" value configured in the administrative interface.  This value is currently " + nodeKey + ".");
        return res;
    }
    String pathValidation = clusterNode.validateFileSystemStoragePathPrefix();
    if (pathValidation != null) {
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage("A configuration is missing.  Please consult the error logs.");
        logger.error("There is an issue with the location at \"File-system Storage Prefix\".  " + pathValidation);
        return res;
    }
    String hash = request.getParameter(UrlParamConstants.APPARCH_HASH);
    String hashAlg = request.getParameter(UrlParamConstants.APPARCH_HASH_ALG);
    String fileName = null;
    if (hash == null || hashAlg == null) {
        // look in the apps directory for the archive specified
        String appName = request.getParameter(UrlParamConstants.APP_NAME);
        String versionId = request.getParameter(UrlParamConstants.APP_VERSION);
        ApplicationVersion appVersion = modelManager.getModelService().findAppVersionByNameAndId(appName, versionId);
        if (appVersion == null) {
            String mesg = "The application version " + versionId + " was not found for application " + appName;
            err.setCode(ErrorCode.APPLICATION_VERSION_NOTFOUND);
            err.setMessage(mesg);
            logger.warn(mesg);
            return res;
        }
        String auth = request.getParameter(UrlParamConstants.AUTH_TOKEN);
        com.openmeap.model.dto.Application app = appVersion.getApplication();
        try {
            if (auth == null || !AuthTokenProvider.validateAuthToken(app.getProxyAuthSalt(), auth)) {
                err.setCode(ErrorCode.AUTHENTICATION_FAILURE);
                err.setMessage("The \"auth\" token presented is not recognized, missing, or empty.");
                return res;
            }
        } catch (DigestException e) {
            throw new GenericRuntimeException(e);
        }
        hash = appVersion.getArchive().getHash();
        hashAlg = appVersion.getArchive().getHashAlgorithm();
        fileName = app.getName() + " - " + appVersion.getIdentifier();
    } else {
        fileName = hashAlg + "-" + hash;
    }
    File file = ApplicationArchive.getFile(clusterNode.getFileSystemStoragePathPrefix(), hashAlg, hash);
    if (!file.exists()) {
        String mesg = "The application archive with " + hashAlg + " hash " + hash + " was not found.";
        // TODO: create an enumeration for this error
        err.setCode(ErrorCode.UNDEFINED);
        err.setMessage(mesg);
        logger.warn(mesg);
        return res;
    }
    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(file.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(file.length()).intValue());
        URLCodec codec = new URLCodec();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".zip\";");
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        // if(outputStream!=null) {outputStream.close();}
        }
        response.flushBuffer();
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
    }
    return null;
}
Also used : ClusterNode(com.openmeap.model.dto.ClusterNode) ApplicationVersion(com.openmeap.model.dto.ApplicationVersion) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileNotFoundException(java.io.FileNotFoundException) Error(com.openmeap.protocol.dto.Error) GlobalSettings(com.openmeap.model.dto.GlobalSettings) IOException(java.io.IOException) GenericRuntimeException(com.openmeap.util.GenericRuntimeException) FileNameMap(java.net.FileNameMap) FileInputStream(java.io.FileInputStream) Result(com.openmeap.protocol.dto.Result) URLCodec(org.apache.commons.codec.net.URLCodec) BufferedInputStream(java.io.BufferedInputStream) DigestException(com.openmeap.digest.DigestException) FileNameMap(java.net.FileNameMap) Map(java.util.Map) File(java.io.File)

Example 28 with FileNameMap

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

the class FileHandlingHttpRequestExecuterImpl method postData.

@Override
public HttpResponse postData(String url, Hashtable getParams, Hashtable postParams) throws HttpRequestException {
    // test to determine whether this is a file upload or not.
    Boolean isFileUpload = false;
    for (Object o : postParams.values()) {
        if (o instanceof File) {
            isFileUpload = true;
            break;
        }
    }
    if (isFileUpload) {
        try {
            HttpPost httpPost = new HttpPost(createUrl(url, getParams));
            httpPost.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (Object o : postParams.entrySet()) {
                Map.Entry<String, Object> entry = (Map.Entry<String, Object>) o;
                if (entry.getValue() instanceof File) {
                    // For File parameters
                    File file = (File) entry.getValue();
                    FileNameMap fileNameMap = URLConnection.getFileNameMap();
                    String type = fileNameMap.getContentTypeFor(file.toURL().toString());
                    entity.addPart(entry.getKey(), new FileBody(((File) entry.getValue()), type));
                } else {
                    // For usual String parameters
                    entity.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), "text/plain", Charset.forName(FormConstants.CHAR_ENC_DEFAULT)));
                }
            }
            httpPost.setEntity(entity);
            return execute(httpPost);
        } catch (Exception e) {
            throw new HttpRequestException(e);
        }
    } else {
        return super.postData(url, getParams, postParams);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) FileNameMap(java.net.FileNameMap) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File) FileNameMap(java.net.FileNameMap) Map(java.util.Map)

Example 29 with FileNameMap

use of java.net.FileNameMap in project Fast-Android-Networking by amitshekhariitbhu.

the class Utils method getMimeType.

public static String getMimeType(String path) {
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String contentTypeFor = fileNameMap.getContentTypeFor(path);
    if (contentTypeFor == null) {
        contentTypeFor = "application/octet-stream";
    }
    return contentTypeFor;
}
Also used : FileNameMap(java.net.FileNameMap)

Example 30 with FileNameMap

use of java.net.FileNameMap in project AndroidFrame by tongxiaoyun.

the class UploadBuilder method guessMimeType.

// 获取mime type
private String guessMimeType(String path) {
    FileNameMap fileNameMap = URLConnection.getFileNameMap();
    String contentTypeFor = fileNameMap.getContentTypeFor(path);
    if (contentTypeFor == null) {
        contentTypeFor = "application/octet-stream";
    }
    return contentTypeFor;
}
Also used : FileNameMap(java.net.FileNameMap)

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