Example usage for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap

List of usage examples for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap

Introduction

In this page you can find the example usage for javax.activation MimetypesFileTypeMap MimetypesFileTypeMap.

Prototype

public MimetypesFileTypeMap() 

Source Link

Document

The default constructor.

Usage

From source file:com.liferay.sync.engine.lan.server.file.LanFileServerHandler.java

protected void sendFile(final ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest,
        SyncFile syncFile) throws Exception {

    Path path = Paths.get(syncFile.getFilePathName());

    if (Files.notExists(path)) {
        _syncTrafficShapingHandler.decrementConnectionsCount();

        if (_logger.isTraceEnabled()) {
            Channel channel = channelHandlerContext.channel();

            _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path);
        }//from  ww  w.ja  va2 s  .  c  o  m

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    if (_logger.isDebugEnabled()) {
        Channel channel = channelHandlerContext.channel();

        _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path);
    }

    long modifiedTime = syncFile.getModifiedTime();
    long previousModifiedTime = syncFile.getPreviousModifiedTime();

    if (OSDetector.isApple()) {
        modifiedTime = modifiedTime / 1000 * 1000;
        previousModifiedTime = previousModifiedTime / 1000 * 1000;
    }

    FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS);

    long currentTime = currentFileTime.toMillis();

    if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) {

        _syncTrafficShapingHandler.decrementConnectionsCount();

        Channel channel = channelHandlerContext.channel();

        _logger.error(
                "Client {}: file modified {}, currentTime {}, modifiedTime " + "{}, previousModifiedTime {}",
                channel.remoteAddress(), path, currentTime, modifiedTime, previousModifiedTime);

        _sendError(channelHandlerContext, NOT_FOUND);

        return;
    }

    HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK);

    long size = Files.size(path);

    HttpUtil.setContentLength(httpResponse, size);

    HttpHeaders httpHeaders = httpResponse.headers();

    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    httpHeaders.set(HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName()));

    if (HttpUtil.isKeepAlive(fullHttpRequest)) {
        httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
    }

    channelHandlerContext.write(httpResponse);

    SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime);

    ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new HttpChunkedInput(syncChunkedFile),
            channelHandlerContext.newProgressivePromise());

    channelFuture.addListener(new ChannelFutureListener() {

        @Override
        public void operationComplete(ChannelFuture channelFuture) throws Exception {

            _syncTrafficShapingHandler.decrementConnectionsCount();

            if (channelFuture.isSuccess()) {
                return;
            }

            Throwable exception = channelFuture.cause();

            Channel channel = channelHandlerContext.channel();

            _logger.error("Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception);

            channelHandlerContext.close();
        }

    });

    if (!HttpUtil.isKeepAlive(fullHttpRequest)) {
        channelFuture.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.mediaworx.intellij.opencmsplugin.sync.VfsAdapter.java

/**
 * pushes a file from the RFS to the VFS
 * @param entity    the sync entity representing the file to be pushed
 * @return  a CMIS document of the newly created VFS file
 * @throws CmsPushException//from w w w .  j  av  a2 s  .  c om
 */
public Document pushFile(SyncEntity entity) throws CmsPushException {
    if (!connected) {
        LOG.info("not connected");
        return null;
    }

    File rfsFile = entity.getFile();
    FileInputStream rfsFileInputStream = null;
    Document vfsFile = null;
    long vfsFileModifiedTime = 0;

    try {
        rfsFileInputStream = new FileInputStream(rfsFile);
        String mimetype = new MimetypesFileTypeMap().getContentType(rfsFile);

        ContentStream contentStream = session.getObjectFactory().createContentStream(rfsFile.getName(),
                rfsFile.length(), mimetype, rfsFileInputStream);

        // if the file already exists in the VFS ...
        if (entity.replaceExistingEntity()) {
            // ... update its content
            vfsFile = (Document) entity.getVfsObject();
            vfsFile.setContentStream(contentStream, true, true);
        }
        // if the file doesn't exist in the VFS
        else {
            // ... get the parent folder object from the VFS
            String parentPath = entity.getVfsPath().substring(0, entity.getVfsPath().lastIndexOf("/"));
            Folder parent = getOrCreateFolder(parentPath);

            // ... and create the file as Document Object under the parent folder
            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put(PropertyIds.OBJECT_TYPE_ID, BaseTypeId.CMIS_DOCUMENT.value());
            properties.put(PropertyIds.NAME, rfsFile.getName());
            vfsFile = parent.createDocument(properties, contentStream, VersioningState.NONE);
        }

        // Set file modification date in the VFS to the RFS file date
        // This does not work when using OpenCms since OpenCms always sets the date of the CMIS change event
        // That's why the file date in the RFS has to be set to the VFS date (see finally block)
        /*
        Map<String, Object> dateProperties = new HashMap<String, Object>(1);
        GregorianCalendar modifiedGC = new GregorianCalendar();
        modifiedGC.setTime(new Date(rfsFile.lastModified()));
        dateProperties.put(PropertyIds.LAST_MODIFICATION_DATE, modifiedGC);
        vfsFile.updateProperties(dateProperties, false);
        */

        vfsFileModifiedTime = vfsFile.getLastModificationDate().getTimeInMillis();
    } catch (FileNotFoundException e) {
        LOG.info("File not found.");
    } catch (CmisNameConstraintViolationException e) {
        throw new CmsPushException("Could not push entity " + entity.getVfsPath()
                + ", there was a problem with the resource name.\n" + e.getMessage(), e);
    } catch (CmisRuntimeException e) {
        throw new CmsPushException("Could not push entity " + entity.getVfsPath()
                + ", there may be an issue with a lock or an XML validation issue. Look at the OpenCms log file to find out what went wrong.\n"
                + e.getMessage(), e);
    } finally {
        try {
            if (rfsFileInputStream != null) {
                rfsFileInputStream.close();
            }

            if (vfsFileModifiedTime > 0) {
                // Since setting the modification Date on the VFS file ain't possible, set the date for the RFS file
                if (rfsFile.setLastModified(vfsFileModifiedTime)) {
                    LOG.info("Setting lastModificationDate successful");
                } else {
                    LOG.info("Setting lastModificationDate NOT successful");
                }
            }
        } catch (IOException e) {
            // do nothing
        }
    }

    return vfsFile;
}

From source file:org.wso2.carbon.appmgt.rest.api.publisher.impl.AppsApiServiceImpl.java

/**
 * Retrieve mobile binary from storage// w w w  .  j av  a2  s .  com
 *
 * @param fileName          binary file name
 * @param ifMatch
 * @param ifUnmodifiedSince
 * @return
 */
@Override
public Response appsMobileBinariesFileNameGet(String fileName, String ifMatch, String ifUnmodifiedSince) {
    File binaryFile = null;
    String contentType = null;
    try {
        if (!RestApiUtil.isValidFileName(fileName)) {
            RestApiUtil.handleBadRequest("Invalid filename '" + fileName + "' is provided", log);
        }

        String fileExtension = FilenameUtils.getExtension(fileName);
        if (AppMConstants.MOBILE_APPS_ANDROID_EXT.equals(fileExtension)
                || AppMConstants.MOBILE_APPS_IOS_EXT.equals(fileExtension)) {

            binaryFile = RestApiUtil.readFileFromStorage(fileName);
            contentType = new MimetypesFileTypeMap().getContentType(binaryFile);
            if (!contentType.startsWith("application")) {
                RestApiUtil.handleBadRequest(
                        "Invalid file '" + fileName + "' with unsupported file type requested", log);
            }
        } else {
            RestApiUtil.handleBadRequest(
                    "Invalid file '" + fileName + "' with unsupported media type is requested", log);
        }
    } catch (AppManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError("Static Content", fileName, e, log);
        } else {
            RestApiUtil.handleInternalServerError(
                    "Error occurred while retrieving mobile binary : " + fileName + "from storage", e, log);
        }
    }
    Response.ResponseBuilder response = Response.ok((Object) binaryFile);
    response.header(RestApiConstants.HEADER_CONTENT_DISPOSITION, RestApiConstants.CONTENT_DISPOSITION_ATTACHMENT
            + "; " + RestApiConstants.CONTENT_DISPOSITION_FILENAME + "=\"" + fileName + "\"");
    response.header(RestApiConstants.HEADER_CONTENT_TYPE, contentType);
    return response.build();
}

From source file:fedorax.server.module.storage.IrodsExternalContentManager.java

/**
 * @param params//from  ww w. j  a  v a 2s .  c o  m
 * @return
 */
private MIMETypedStream getFromIrods(URI uri, String mimeType)
        throws HttpServiceNotFoundException, GeneralException {
    try {
        LOG.debug("uri: " + uri);
        IRODSFileFactory ff = IRODSFileSystem.instance().getIRODSFileFactory(irodsAccount);
        IRODSFile file = ff.instanceIRODSFile(URLDecoder.decode(uri.getRawPath(), "UTF-8"));
        InputStream result = ff.instanceIRODSFileInputStream(file);
        final long start = System.currentTimeMillis();
        result = new BufferedInputStream(result, this.irodsReadBufferSize) {
            int bytes = 0;

            @Override
            public void close() throws IOException {
                if (LOG.isInfoEnabled()) {
                    long time = System.currentTimeMillis() - start;
                    if (time > 0) {
                        LOG.info("closed irods stream: " + bytes + " bytes at " + (bytes / time) + " kb/sec");
                    }
                }
                super.close();
            }

            @Override
            public synchronized int read() throws IOException {
                bytes++;
                return super.read();
            }

            @Override
            public synchronized int read(byte[] b, int off, int len) throws IOException {
                bytes = bytes + len;
                return super.read(b, off, len);
            }

        };

        // if mimeType was not given, try to determine it automatically
        if (mimeType == null || mimeType.equalsIgnoreCase("")) {
            String irodsFilename = file.getName();
            if (irodsFilename != null) {
                mimeType = new MimetypesFileTypeMap().getContentType(irodsFilename);
            }
            if (mimeType == null || mimeType.equalsIgnoreCase("")) {
                mimeType = DEFAULT_MIMETYPE;
            }
        }
        return new MIMETypedStream(mimeType, result, getPropertyArray(mimeType), file.length());
        /*
         * } catch (AuthzException ae) { LOG.error(ae.getMessage(), ae);
         * throw new
         * HttpServiceNotFoundException("Policy blocked datastream resolution"
         * , ae); } catch (GeneralException me) { LOG.error(me.getMessage(),
         * me); throw me; }
         */

    } catch (JargonException e) {
        throw new GeneralException("Problem getting iRODS input stream", e);
    } catch (Throwable th) {
        th.printStackTrace(System.err);
        // catch anything but generalexception
        LOG.error(th.getMessage(), th);
        throw new HttpServiceNotFoundException(
                "[FileExternalContentManager] " + "returned an error.  The underlying error was a "
                        + th.getClass().getName() + "  The message " + "was  \"" + th.getMessage() + "\"  .  ",
                th);
    }
}

From source file:coral.service.ExpServable.java

public static String getMime(File file) {

    String mime = "text/plain";
    try {// w w  w . j a  va  2 s  .  c  om
        mime = new MimetypesFileTypeMap().getContentType(file);
    } catch (Error ex) {
        logger.error("Problem with mime type resolution.", ex);

        String n = file.getName();
        String e = n.substring(n.lastIndexOf('.') + 1).toLowerCase();

        String[][] types = new String[][] { new String[] { "pdf", "application/pdf" },
                new String[] { "html", "text/html" }, new String[] { "png", "image/png" },
                new String[] { "anytable", "text/anytable" }, new String[] { "jpg", "image/jpg" } };

        for (String[] r : types) {
            if (r[0].equals(e)) {
                mime = r[1];
            }
        }
    }

    return mime;
}

From source file:org.betaconceptframework.astroboa.model.factory.CmsRepositoryEntityFactory.java

/**
 * Creates a new unmanaged {@link BinaryChannel} from the provided path, 
 * relative to UnmanagedDataStore directory which is located under repository home directory.
 * //from  ww w  .  j a  va 2  s  .c om
 * @return Resource path relative to UnmanagedDataStore directory
 */
public BinaryChannel newUnmanagedBinaryChannel(String relativePathToBinaryContent) {
    BinaryChannelImpl binaryChannel = new BinaryChannelImpl();
    binaryChannel.setAuthenticationToken(getAuthenticationToken());
    binaryChannel.setRelativeFileSystemPath(relativePathToBinaryContent);
    binaryChannel.setUnmanaged(true);

    RepositoryContext repositoryContext = AstroboaClientContextHolder
            .getRepositoryContextForClient(getAuthenticationToken());
    CmsRepository activeCmsRepository = repositoryContext != null ? repositoryContext.getCmsRepository() : null;

    if (activeCmsRepository == null || StringUtils.isBlank(activeCmsRepository.getRepositoryHomeDirectory())) {
        throw new CmsException("Could not find repository home directory."
                + (activeCmsRepository == null ? "Found no active repository"
                        : "Active repository " + activeCmsRepository.getId()
                                + " does not provide its home directory."));
    }

    String unmanagedDataStorePath = activeCmsRepository.getRepositoryHomeDirectory() + File.separator
            + CmsConstants.UNMANAGED_DATASTORE_DIR_NAME;

    String absoluteBinaryChanelContentPath = unmanagedDataStorePath + File.separator
            + relativePathToBinaryContent;

    ((BinaryChannelImpl) binaryChannel).setAbsoluteBinaryChannelContentPath(absoluteBinaryChanelContentPath);

    File binaryFile = new File(absoluteBinaryChanelContentPath);

    if (binaryFile.exists()) {

        binaryChannel.setSize(binaryFile.length());

        binaryChannel.setSourceFilename(binaryFile.getName());

        binaryChannel.setMimeType(new MimetypesFileTypeMap().getContentType(binaryFile));

        //Encoding ???
        //binaryChannel.setEncoding();

        Calendar lastModifiedDate = Calendar.getInstance();
        lastModifiedDate.setTimeInMillis(binaryFile.lastModified());

        binaryChannel.setModified(lastModifiedDate);

    }

    ((BinaryChannelImpl) binaryChannel).setRepositoryId(activeCmsRepository.getId());

    return binaryChannel;
}

From source file:de.mprengemann.intellij.plugin.androidicons.dialogs.AndroidMultiDrawableImporter.java

private void importZipArchive(VirtualFile virtualFile) {
    final String filePath = virtualFile.getCanonicalPath();
    if (filePath == null) {
        return;//from   ww  w .  j  a  v  a  2s  .co  m
    }
    final File tempDir = new File(ImageInformation.getTempDir(), virtualFile.getNameWithoutExtension());
    final String archiveName = virtualFile.getName();
    new Task.Modal(project, "Importing Archive...", true) {
        @Override
        public void run(@NotNull final ProgressIndicator progressIndicator) {
            progressIndicator.setIndeterminate(true);
            try {
                FileUtils.forceMkdir(tempDir);
                ZipUtil.extract(new File(filePath), tempDir, new FilenameFilter() {
                    @Override
                    public boolean accept(File dir, String name) {
                        final String mimeType = new MimetypesFileTypeMap().getContentType(name);
                        final String type = mimeType.split("/")[0];
                        return type.equals("image");
                    }
                }, true);
                progressIndicator.checkCanceled();

                final Iterator<File> fileIterator = FileUtils.iterateFiles(tempDir, TrueFileFilter.INSTANCE,
                        TrueFileFilter.INSTANCE);
                while (fileIterator.hasNext()) {
                    File file = fileIterator.next();
                    if (file.isDirectory() || file.isHidden()) {
                        continue;
                    }
                    final String fileRoot = file.getParent().toUpperCase();
                    final String name = FilenameUtils.getBaseName(file.toString());
                    if (name.startsWith(".") || fileRoot.contains("__MACOSX")) {
                        continue;
                    }
                    for (Resolution resolution : RESOLUTIONS) {
                        if (name.toUpperCase().contains("-" + resolution)
                                || name.toUpperCase().contains("_" + resolution)
                                || fileRoot.contains(resolution.toString())) {
                            controller.addZipImage(file, resolution);
                            break;
                        }
                    }
                }
                progressIndicator.checkCanceled();

                final Map<Resolution, List<ImageInformation>> zipImages = controller.getZipImages();
                final List<Resolution> foundResolutions = new ArrayList<Resolution>();
                int foundAssets = 0;
                for (Resolution resolution : zipImages.keySet()) {
                    final List<ImageInformation> assetInformation = zipImages.get(resolution);
                    if (assetInformation != null && assetInformation.size() > 0) {
                        foundAssets += assetInformation.size();
                        foundResolutions.add(resolution);
                    }
                }
                progressIndicator.checkCanceled();

                final int finalFoundAssets = foundAssets;
                UIUtil.invokeLaterIfNeeded(new DumbAwareRunnable() {
                    public void run() {
                        final String title = String.format("Import '%s'", archiveName);
                        if (foundResolutions.size() == 0 || finalFoundAssets == 0) {
                            Messages.showErrorDialog("No assets found.", title);
                            FileUtils.deleteQuietly(tempDir);
                            return;
                        }
                        final String[] options = new String[] { "Import", "Cancel" };
                        final String description = String.format("Import %d assets for %s to %s.",
                                finalFoundAssets, StringUtils.join(foundResolutions, ", "),
                                controller.getTargetRoot());
                        final int selection = Messages.showDialog(description, title, options, 0,
                                Messages.getQuestionIcon());
                        if (selection == 0) {
                            controller.getZipTask(project, tempDir).queue();
                            close(0);
                        } else {
                            FileUtils.deleteQuietly(tempDir);
                        }
                    }
                });
            } catch (ProcessCanceledException e) {
                FileUtils.deleteQuietly(tempDir);
            } catch (IOException e) {
                LOGGER.error(e);
            }
        }
    }.queue();
}

From source file:org.sakaiproject.importer.impl.handlers.ResourcesHandler.java

protected void addAllResources(InputStream archive, String path, int notifyOption) {
    ZipInputStream zipStream = new ZipInputStream(archive);
    ZipEntry entry;//  w  w  w . ja v  a 2 s  .co m
    String contentType;
    if (path.charAt(0) == '/') {
        path = path.substring(1);
    }
    if (!path.endsWith("/")) {
        path = path + "/";
    }
    try {
        while ((entry = zipStream.getNextEntry()) != null) {
            Map resourceProps = new HashMap();
            contentType = new MimetypesFileTypeMap().getContentType(entry.getName());
            String title = entry.getName();
            if (title.lastIndexOf("/") > 0) {
                title = title.substring(title.lastIndexOf("/") + 1);
            }
            resourceProps.put(ResourceProperties.PROP_DISPLAY_NAME, title);
            resourceProps.put(ResourceProperties.PROP_COPYRIGHT, COPYRIGHT);
            if (m_log.isDebugEnabled()) {
                m_log.debug("import ResourcesHandler about to add file entitled '" + title + "'");
            }

            int count;
            ByteArrayOutputStream contents = new ByteArrayOutputStream();
            byte[] data = new byte[BUFFER];

            while ((count = zipStream.read(data, 0, BUFFER)) != -1) {
                contents.write(data, 0, count);
            }

            if (entry.isDirectory()) {

                addContentCollection(path + entry.getName(), resourceProps);
                addAllResources(new ByteArrayInputStream(contents.toByteArray()), path + entry.getName(),
                        notifyOption);
            } else {
                addContentResource(path + entry.getName(), contentType,
                        new ByteArrayInputStream(contents.toByteArray()), resourceProps, notifyOption);
            }

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

From source file:ro.ieugen.fileserver.http.HttpStaticFileServerHandler.java

/**
 * Sets the content type header for the HTTP Response
 *
 * @param response HTTP response/*from w ww. j  a va  2 s  .  c om*/
 * @param file     file to extract content type
 */
private static void setContentTypeHeader(HttpResponse response, File file) {
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    response.setHeader(CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath()));
}

From source file:ru.redcraft.pinterest4j.core.api.CoreAPI.java

protected FormDataBodyPart createImageBodyPart(File imgFile) {
    String[] mimeInfo = new MimetypesFileTypeMap().getContentType(imgFile).split("/");
    MediaType imageType = new MediaType(mimeInfo[0], mimeInfo[1]);
    FormDataBodyPart f = new FormDataBodyPart(
            FormDataContentDisposition.name("img").fileName(imgFile.getName()).build(), imgFile, imageType);
    return f;/*from  w  w  w  .  j a v  a 2s. com*/
}