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:org.jwebsocket.plugins.filesystem.FileSystemPlugIn.java

/**
 * Load a file from a given alias.//w ww. j a v a 2 s.  c om
 *
 * @param aConnector
 * @param aToken
 */
protected void load(WebSocketConnector aConnector, Token aToken) {
    TokenServer lServer = getServer();
    String lMsg;

    if (mLog.isDebugEnabled()) {
        mLog.debug("Processing 'load'...");
    }

    // check if user is allowed to run 'load' command
    if (!hasAuthority(aConnector, NS_FILESYSTEM + ".load")) {
        if (mLog.isDebugEnabled()) {
            mLog.debug("Returning 'Access denied'...");
        }
        lServer.sendToken(aConnector, lServer.createAccessDenied(aToken));
        return;
    }

    // obtain required parameters for file load operation
    String lFilename = aToken.getString("filename");
    String lAlias = aToken.getString("alias", PRIVATE_ALIAS_DIR_KEY);
    String lData;

    // instantiate response token
    Token lResponse = lServer.createResponse(aToken);

    String lBaseDir = getAliasPath(aConnector, lAlias);
    if (null == lBaseDir) {
        sendErrorToken(aConnector, aToken, -1, "The given alias '" + lAlias + "' does not exist!");
        return;
    }

    File lFile = new File(lBaseDir + lFilename);
    String lEncoding = aToken.getString("encoding", "base64");

    byte[] lBA;
    try {
        if (!isPathInFS(lFile, lBaseDir)) {
            sendErrorToken(aConnector, aToken, -1,
                    "The file '" + lFilename + "' is out of the file-system location!");
            return;
        }

        if (!lFile.exists()) {
            sendErrorToken(aConnector, aToken, -1,
                    "The file '" + lFilename + "' does not exist in the given alias!");
            return;
        }

        if (aConnector instanceof HTTPConnector) {
            // supporting HTTP download
            ServletUtils.sendFile(((HTTPConnector) aConnector).getHttpResponse(), lFile);
            ((HTTPConnector) aConnector).setHttpResponse(null);
            if (mLog.isDebugEnabled()) {
                mLog.debug("File '" + lFilename + "' sent in the HTTP response!");
            }
        } else {

            lBA = FileUtils.readFileToByteArray(lFile);

            // populating the response data field according to the file type
            String lFileType = new MimetypesFileTypeMap().getContentType(lFile);
            boolean lIsBinary;
            try {
                lIsBinary = Tools.isBinaryFile(lFile);
            } catch (IOException aEx) {
                lIsBinary = lFileType.contains("text") || lFileType.contains("json")
                        || lFileType.contains("javascript");
            }
            if (!lIsBinary) {
                lData = new String(lBA);
                lResponse.setString("data", lData);
            } else {
                lResponse.getMap().put("data", lBA);
                lResponse.setBoolean("isBinary", Boolean.TRUE);
            }
            // setting the file MIME type
            lResponse.setString("mime", lFileType);

            // send response to requester
            lResponse.setMap("enc", new MapAppender().append("data", lEncoding).getMap());
            lResponse.setString("filename", lFilename);
            lServer.sendToken(aConnector, lResponse);
        }
    } catch (Exception lEx) {
        lResponse.setInteger("code", -1);
        lMsg = lEx.getClass().getSimpleName() + " on load: " + lEx.getMessage();
        lResponse.setString("msg", lMsg);
        lServer.sendToken(aConnector, lResponse);
    }
}

From source file:org.sakaiproject.scorm.content.impl.ZipCHH.java

protected ContentResourceEdit makeResource(ContentEntity ce, String path, String name, byte[] content) {
    String[] fields = path.split(Entity.SEPARATOR);

    if (null == name) {
        name = "[error]";

        if (null != fields && fields.length >= 1) {
            // Grab the last item as a name for this collection
            name = fields[fields.length - 1];
        }/*from  w  ww . j  a va2s. c  om*/
    }

    ContentResourceEdit resource = (ContentResourceEdit) resolver.newResourceEdit(newId(ce.getId(), path));

    if (null != content) {
        resource.setContent(content);
        resource.setContentLength(content.length);
    }

    resource.setResourceType(ResourceType.TYPE_HTML);
    resource.setContentType(new MimetypesFileTypeMap().getContentType(name));

    ResourcePropertiesEdit props = resource.getPropertiesEdit();
    props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
    props.addProperty(ContentHostingHandlerResolver.CHH_BEAN_NAME, getContentHostingHandlerName());
    props.addProperty(VIRTUAL_ZIP_ENTITY_PROPERTY, "true");
    props.addProperty(REAL_PARENT_ENTITY_PROPERTY, ce.getId());

    //resource.setVirtualContentEntity(resource);

    resource.setContentHandler(this);

    return resource;
}

From source file:org.mycore.common.xml.MCRXMLFunctions.java

/**
 * Determines the mime type for the file given by its name.
 *
 * @param f//from w ww. j  a v  a 2  s  . c om
 *            the name of the file
 * @return the mime type of the given file
 */
public static String getMimeType(String f) {
    if (f == null) {
        return "application/octet-stream";
    }
    MimetypesFileTypeMap mTypes = new MimetypesFileTypeMap();
    return mTypes.getContentType(f.toLowerCase(Locale.ROOT));
}

From source file:com.edgenius.core.repository.SimpleRepositoryServiceImpl.java

@SuppressWarnings("unchecked")
public List<FileNode> saveFile(ITicket ticket, FileNode attachment, boolean md5DigestRequired,
        boolean discardSaveDiffMd5)
        throws RepositoryException, RepositoryTiemoutExcetpion, RepositoryQuotaException {
    List<FileNode> checkedIn = new ArrayList<FileNode>();
    if (!attachment.isBulkZip()) {
        //TODO: does it need return only check-in successfully?
        checkedIn.add(attachment);/*from www  .  java  2 s .  com*/
    } else {
        //process bulk upload
        String dir = null;
        try {
            dir = FileUtil.createTempDirectory(TMP_BULK_CHECKIN);
            ZipFileUtil.expandZipToFolder(attachment.getFile(), dir);

            //retrieve all files and check-in

            Collection<File> files = FileUtils.listFiles(new File(dir), null, true);
            if (files != null) {
                MimetypesFileTypeMap mineMap = new MimetypesFileTypeMap();
                for (File file : files) {
                    try {
                        FileNode node = new FileNode();
                        //use same comment for all upload
                        node.setComment(attachment.getComment());
                        node.setShared(attachment.isShared());
                        node.setFile(new FileInputStream(file));
                        node.setFilename(FileUtil.getFileName(file.getName()));
                        node.setContentType(mineMap.getContentType(file));
                        node.setType(RepositoryService.TYPE_ATTACHMENT);
                        node.setIdentifier(attachment.getIdentifier());
                        node.setCreateor(attachment.getCreateor());
                        node.setStatus(attachment.getStatus());
                        node.setSize(file.length());
                        node.setBulkZip(false);

                        checkedIn.addAll(saveFile(ticket, node, md5DigestRequired, discardSaveDiffMd5));

                    } catch (Exception e) {
                        log.error("Unable process some files in bulk zip", e);
                    }
                }
            }
        } catch (FileUtilException e) {
            throw new RepositoryException("Unable create temp dir for bulk upload", e);
        } catch (ZipFileUtilException e) {
            throw new RepositoryException("Unable unzip bulk uploaded file", e);
        } finally {
            if (dir != null) {
                try {
                    FileUtil.deleteDir(dir);
                } catch (IOException e) {
                    log.error("Unable to delete directory " + dir);
                }
            }
        }

        return checkedIn;
    }

    //TODO: consider thread-safe
    if (!ticket.isAllowWrite()) {
        String error = "Workspace has not write permission " + ticket.getSpacename() + " for identifierUuid "
                + attachment.getIdentifier();
        log.warn(error);
        throw new RepositoryException("Permission denied: " + error);
    }
    checkSpaceQuota(ticket, attachment.getSize());
    try {
        //lock at identifier level so that multiple users upload will still keep version works.
        acquireLock(ticket.getSpacename(), attachment.getIdentifier(), null);
        CrWorkspace crW = getCrWorkspace(ticket);
        List<CrFileNode> nodes = getBaseNodes(attachment.getType(), attachment.getIdentifier());
        CrFileNode existFile = null, filenode = new CrFileNode();

        log.info("File is going to save to " + ticket.getSpacename() + "");

        //page->attachment->file->resource
        for (Iterator<CrFileNode> iter = nodes.iterator(); iter.hasNext();) {
            CrFileNode node = iter.next();
            //if file is under same Identifier(page), and file name is same, then version the item.
            if (StringUtils.equalsIgnoreCase(node.getFilename(), attachment.getFilename())) {
                existFile = node;
                break;
            }
        }
        if (existFile != null) {
            //increase version
            filenode.setVersion(existFile.getVersion() + 1);
            filenode.setNodeUuid(existFile.getNodeUuid());
            log.info("FileNode is appending version to a existed node :" + filenode.getNodeUuid()
                    + " with new version " + filenode.getVersion());
        } else {
            //this node name is useless now, so just create a random unique one
            filenode.setVersion(1);
            filenode.setNodeUuid(UUID.randomUUID().toString());
            //TODO: encoding is important for lucene index building and search, here just set empty.
            filenode.setEncoding("");
            File id = new File(FileUtil.getFullPath(homeDir, crW.getSpaceUuid(), attachment.getType(),
                    attachment.getIdentifier(), filenode.getNodeUuid()));
            if (id.exists()) {
                throw new RepositoryException("Node uuid directory already exist");
            }
            if (!id.mkdirs()) {
                throw new RepositoryException(
                        "Node uuid directory create failed. Full path is " + id.getAbsolutePath());
            }
            log.info("FileNode is creating a new node :" + filenode.getNodeUuid());
        }
        filenode.setSpaceUname(ticket.getSpacename());

        resetMetaData(attachment, filenode);

        String verRootDir = FileUtil.getFullPath(homeDir, crW.getSpaceUuid(), filenode.getNodeType(),
                filenode.getIdentifierUuid(), filenode.getNodeUuid(),
                new Integer(filenode.getVersion()).toString());
        File verFile = new File(verRootDir);
        if (!verFile.mkdirs()) {
            //this is just ensure the case if MD5 is duplicated, system try to delete that version directory but failed...
            //at that case, only empty directory left there.
            if (verFile.exists() && verFile.list().length > 0) {
                throw new RepositoryException(
                        "Node uuid " + filenode.getNodeUuid() + " can not create version directory "
                                + Integer.valueOf(filenode.getVersion()).toString());
            }
        }

        OutputStream file = null;
        File ofile = new File(verRootDir, DEFAULT_FILE_NAME);
        try {
            file = new FileOutputStream(ofile);
            //save physical file
            byte[] content = new byte[1024 * 1024];
            int len;

            md5DigestRequired = md5DigestRequired && (md5Digest != null);
            while ((len = attachment.getFile().read(content)) != -1) {
                if (md5DigestRequired) {
                    md5Digest.update(content, 0, len);
                }
                file.write(content, 0, len);
            }
            file.flush();

            if (md5DigestRequired) {
                filenode.setMd5Digest(new String(Hex.encodeHex(md5Digest.digest())));
            }
            if (discardSaveDiffMd5 && filenode.getVersion() > 1) {
                //compare
                if (filenode.getMd5Digest().equals(existFile.getMd5Digest())) {
                    //tell to delete version directory as well in finally{}!
                    checkedIn = null;
                    log.info("MD5 is same and ignore checked in");
                    return null;
                }
            }
            //create new record in DB
            crFileNodeDAO.saveOrUpdate(filenode);

            //set back NodeUuid and Version to attachment
            attachment.setNodeUuid(filenode.getNodeUuid());
            attachment.setVersion(Integer.valueOf(filenode.getVersion()).toString());
            attachment.setDate(filenode.getModifiedDate().getTime());

            log.debug("File node create on " + filenode.getModifiedDate() + " by version "
                    + attachment.getVersion());
        } catch (Exception e) {
            throw new RepositoryException("Failed save node " + e);
        } finally {
            if (file != null) {
                try {
                    file.close();
                } catch (Exception e) {
                    log.error("Unable to close uploaded file");
                }
                if (checkedIn == null) {
                    if (!ofile.delete()) {
                        log.error("Version file {} deleted failed when MD5 duplicated case",
                                ofile.getAbsolutePath());
                        ofile.deleteOnExit();
                    }
                }
            }
            if (checkedIn == null) {
                //ignored check-in
                if (!verFile.delete()) {
                    log.error("Version directory {} deleted failed when MD5 duplicated case", verRootDir);
                }
            }
        }
    } finally {
        releaseLock(ticket.getSpacename(), attachment.getIdentifier(), null);
        if (attachment.getFile() != null) {
            try {
                attachment.getFile().close();
            } catch (Exception e) {
            }
        }
    }
    return checkedIn;
}

From source file:org.opencastproject.capture.impl.CaptureAgentImpl.java

/**
 * Generates the manifest.xml file from the files specified in the properties
 * //from   w ww .j  a v a 2  s  .  c  om
 * @param recID
 *          The ID for the recording whose manifest will be created
 * @return A state boolean
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public boolean createManifest(String recID) throws NoSuchAlgorithmException, IOException {

    AgentRecording recording = pendingRecordings.get(recID);
    if (recording == null) {
        logger.error("[createManifest] Recording {} not found!", recID);
        setRecordingState(recID, RecordingState.MANIFEST_ERROR);
        return false;
    } else {
        logger.debug("Generating manifest for recording {}", recID);
        setRecordingState(recording.getID(), RecordingState.MANIFEST);
    }

    // Get the list of device names so we can attach all the files appropriately (re: flavours, etc)
    String[] friendlyNames = recording.getProperty(CaptureParameters.CAPTURE_DEVICE_NAMES).split(",");
    if (friendlyNames.length == 1 && StringUtils.isBlank(friendlyNames[0])) {
        // Idiot check against blank name lists.
        logger.error("Unable to build mediapackage for recording {} because the device names list is blank!",
                recID);
        return false;
    }

    MediaPackageElementBuilder elemBuilder = MediaPackageElementBuilderFactory.newInstance()
            .newElementBuilder();
    MediaPackageElementFlavor flavor = null;
    // Includes the tracks in the MediaPackage
    try {

        // Adds the files present in the Properties
        for (String friendlyName : friendlyNames) {
            String name = friendlyName.trim();

            String flavorPointer = CaptureParameters.CAPTURE_DEVICE_PREFIX + name
                    + CaptureParameters.CAPTURE_DEVICE_FLAVOR;
            String flavorString = recording.getProperty(flavorPointer);
            flavor = MediaPackageElementFlavor.parseFlavor(flavorString);

            String outputProperty = CaptureParameters.CAPTURE_DEVICE_PREFIX + name
                    + CaptureParameters.CAPTURE_DEVICE_DEST;
            if (null == recording.getProperty(outputProperty)) {
                logger.error(CaptureParameters.CAPTURE_DEVICE_PREFIX + name
                        + CaptureParameters.CAPTURE_DEVICE_DEST
                        + "does not exist in the recording's properties.  Your CA's configuration file, or the configuration "
                        + "received from the core is missing information.  This should be checked ASAP.");
                // FIXME: Is the admin reading the agent logs? (jt)
                // FIXME: Who will find out why one of the tracks is missing from the media package? (jt)
                // FIXME: Think about a notification scheme, this looks like an emergency to me (jt)
                setRecordingState(recording.getID(), RecordingState.MANIFEST_ERROR);
                return false;
            }
            File outputFile = new File(recording.getBaseDir(), recording.getProperty(outputProperty));

            // Adds the file to the MediaPackage
            if (outputFile.exists()) {
                // TODO: This should really be Track rather than TrackImpl
                // but otherwise a bunch of functions we need disappear...
                TrackImpl t = (TrackImpl) elemBuilder.elementFromURI(outputFile.toURI(),
                        MediaPackageElement.Type.Track, flavor);
                t.setSize(outputFile.length());
                String[] detectedMimeType = new MimetypesFileTypeMap().getContentType(outputFile).split("/");
                t.setMimeType(mimeType(detectedMimeType[0], detectedMimeType[1]));
                t.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, outputFile));
                if (recording.getProperty(CaptureParameters.RECORDING_DURATION) != null) {
                    t.setDuration(Long.parseLong(recording.getProperty(CaptureParameters.RECORDING_DURATION)));
                }

                // Commented out because this does not work properly with mock captures.
                // Also doesn't do much when it does work...
                /*
                 * if (name.contains("hw:")) { AudioStreamImpl stream = new AudioStreamImpl(outputFile.getName());
                 * t.addStream(stream); } else { VideoStreamImpl stream = new VideoStreamImpl(outputFile.getName());
                 * t.addStream(stream); }
                 */
                if (recording.getMediaPackage() == null) {
                    logger.error("Recording media package is null!");
                    return false;
                }
                recording.getMediaPackage().add(t);
            } else {
                // FIXME: Is the admin reading the agent logs? (jt)
                // FIXME: Who will find out why one of the tracks is missing from the media package? (jt)
                // FIXME: Think about a notification scheme, this looks like an emergency to me (jt)
                logger.error("Required file {} not found, aborting manifest creation!", outputFile.getName());
                setRecordingState(recording.getID(), RecordingState.MANIFEST_ERROR);
                return false;
            }
        }

    } catch (UnsupportedElementException e) {
        logger.error("Unsupported Element Exception: {}.", e);
        setRecordingState(recording.getID(), RecordingState.MANIFEST_ERROR);
        return false;
    }

    // Serialize the metadata file and the MediaPackage
    FileOutputStream fos = null;
    try {
        logger.debug("Serializing metadata and MediaPackage...");

        // Gets the manifest.xml as a Document object and writes it to a file
        MediaPackageSerializer serializer = new DefaultMediaPackageSerializerImpl(recording.getBaseDir());
        File manifestFile = new File(recording.getBaseDir(), CaptureParameters.MANIFEST_NAME);

        MediaPackage mp = recording.getMediaPackage();
        for (MediaPackageElement element : mp.elements()) {
            if (element.getURI() != null) {
                element.setURI(new URI(serializer.encodeURI(element.getURI())));
            }
        }
        fos = new FileOutputStream(manifestFile);
        MediaPackageParser.getAsXml(mp, fos, true);

    } catch (MediaPackageException e) {
        logger.error("MediaPackage Exception: {}.", e);
        setRecordingState(recording.getID(), RecordingState.MANIFEST_ERROR);
        return false;
    } catch (IOException e) {
        logger.error("I/O Exception: {}.", e);
        setRecordingState(recording.getID(), RecordingState.MANIFEST_ERROR);
        return false;
    } catch (URISyntaxException e) {
        logger.error("URI Syntax Exception: {}.", e);
        setRecordingState(recording.getID(), RecordingState.MANIFEST_ERROR);
        return false;
    } finally {
        IOUtils.closeQuietly(fos);
    }

    setRecordingState(recording.getID(), RecordingState.MANIFEST_FINISHED);
    return true;
}

From source file:org.jwebsocket.plugins.filesystem.FileSystemPlugIn.java

/**
 * Gets the file list from a given alias an optionally from a sub path.
 *
 * @param aUsername The requester client username.
 * @param aToken/*from  w  w w. j  a v  a2 s. co m*/
 * @return
 */
private Token mGetFilelist(WebSocketConnector aConnector, Token aToken) {

    String lAlias = aToken.getString("alias");
    boolean lRecursive = aToken.getBoolean("recursive", false);
    boolean lIncludeDirs = aToken.getBoolean("includeDirs", false);
    List<Object> lFilemasks = aToken.getList("filemasks", new FastList<Object>());
    String lSubPath = aToken.getString("path", null);
    Object lObject;
    String lBaseDir;
    Token lToken = TokenFactory.createToken();

    lObject = mSettings.getAliasPath(lAlias);
    if (lObject != null) {
        lBaseDir = (String) lObject;
        lBaseDir = replaceAliasVars(aConnector, lBaseDir);
        /*
         lBaseDir = JWebSocketConfig.expandEnvVarsAndProps(lBaseDir).
         replace("{username}", aConnector.getUsername());
         */
        File lDir;
        if (null != lSubPath) {
            lDir = new File(lBaseDir + File.separator + lSubPath);
        } else {
            lDir = new File(lBaseDir + File.separator);
        }

        if (!isPathInFS(lDir, lBaseDir)) {
            lToken.setInteger("code", -1);
            lToken.setString("msg", "The path '" + lSubPath + "' is out of the file-system location!");

            return lToken;
        } else if (!(lDir.exists() && lDir.isDirectory())) {
            lToken.setInteger("code", -1);
            lToken.setString("msg",
                    "The path '" + lSubPath + "' is not directory on target '" + lAlias + "' alias!");

            return lToken;
        }
        // IOFileFilter lFileFilter = FileFilterUtils.nameFileFilter(lFilemask);
        String[] lFilemaskArray = new String[lFilemasks.size()];
        int lIdx = 0;
        for (Object lMask : lFilemasks) {
            lFilemaskArray[lIdx] = (String) lMask;
            lIdx++;
        }
        IOFileFilter lFileFilter = new WildcardFileFilter(lFilemaskArray);
        IOFileFilter lDirFilter = null;
        if (lRecursive) {
            lDirFilter = FileFilterUtils.directoryFileFilter();
        }
        Collection<File> lFiles = FileUtils.listFilesAndDirs(lDir, lFileFilter, lDirFilter);
        List<Map> lFileList = new FastList<Map>();
        File lBasePath = new File(lBaseDir);
        MimetypesFileTypeMap lMimesMap = new MimetypesFileTypeMap();
        String lRelativePath;
        for (File lFile : lFiles) {
            if (lFile == lDir
                    // we don't want directories to be returned
                    // except explicitely requested
                    || (!lIncludeDirs && lFile.isDirectory())) {
                continue;
            }
            Map<String, Object> lFileData = new FastMap<String, Object>();
            String lFilename = lFile.getAbsolutePath().replace(lBasePath.getAbsolutePath() + File.separator,
                    "");
            // we always return the path in unix/url/java format
            String lUnixPath = FilenameUtils.separatorsToUnix(lFilename);
            int lSeparator = lUnixPath.lastIndexOf("/");
            if (lSeparator != -1) {
                lFilename = lUnixPath.substring(lSeparator + 1);
                lRelativePath = lUnixPath.substring(0, lSeparator + 1);
            } else {
                lRelativePath = "";
            }

            lFileData.put("relativePath", lRelativePath);
            lFileData.put("filename", lFilename);
            lFileData.put("size", lFile.length());
            lFileData.put("modified", Tools.DateToISO8601(new Date(lFile.lastModified())));
            lFileData.put("hidden", lFile.isHidden());
            lFileData.put("canRead", lFile.canRead());
            lFileData.put("canWrite", lFile.canWrite());
            lFileData.put("directory", lFile.isDirectory());
            lFileData.put("mime", lMimesMap.getContentType(lFile));
            if (lAlias.equals(PRIVATE_ALIAS_DIR_KEY)) {
                lFileData.put("url", getString(ALIAS_WEB_ROOT_KEY, ALIAS_WEB_ROOT_DEF)
                        // in URLs we only want forward slashes
                        + FilenameUtils.separatorsToUnix(lFilename));
            }
            lFileList.add(lFileData);
        }
        lToken.setList("files", lFileList);
        lToken.setInteger("code", 0);
        lToken.setString("msg", "ok");
    } else {
        lToken.setInteger("code", -1);
        lToken.setString("msg", "No alias '" + lAlias + "' defined for filesystem plug-in");
    }

    return lToken;
}

From source file:org.craftercms.studio.impl.v1.repository.alfresco.AlfrescoContentRepository.java

protected boolean writeContentCMIS(String fullPath, InputStream content) {
    long startTime = System.currentTimeMillis();
    Map<String, String> params = new HashMap<String, String>();
    String cleanPath = fullPath.replaceAll("//", "/"); // sometimes sent bad paths
    if (cleanPath.endsWith("/")) {
        cleanPath = cleanPath.substring(0, cleanPath.length() - 1);
    }//ww w . j  a v a 2  s . c o m
    int splitIndex = cleanPath.lastIndexOf("/");
    String filename = cleanPath.substring(splitIndex + 1);
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    String mimeType = mimeTypesMap.getContentType(filename);
    try {
        Session session = getCMISSession();
        ContentStream contentStream = session.getObjectFactory().createContentStream(filename, -1, mimeType,
                content);
        CmisObject cmisObject = null;
        if (contentExists(cleanPath)) {
            cmisObject = session.getObjectByPath(cleanPath);
        }
        if (cmisObject != null) {
            ObjectType type = cmisObject.getBaseType();
            if ("cmis:document".equals(type.getId())) {
                org.apache.chemistry.opencmis.client.api.Document document = (org.apache.chemistry.opencmis.client.api.Document) cmisObject;
                String pwcId = document.getVersionSeriesCheckedOutId();
                if (pwcId != null) {
                    org.apache.chemistry.opencmis.client.api.Document pwcDocument = (org.apache.chemistry.opencmis.client.api.Document) session
                            .getObject(pwcId);
                    pwcDocument.checkIn(false, null, contentStream, null);
                } else {
                    document.setContentStream(contentStream, true);
                }
                session.removeObjectFromCache(document.getId());
                session.clear();
            }
        } else {
            String folderPath = cleanPath.substring(0, splitIndex);
            if (StringUtils.isEmpty(folderPath)) {
                folderPath = "/";
            }
            CmisObject folderCmisObject = null;
            if (contentExists(folderPath)) {
                folderCmisObject = session.getObjectByPath(folderPath);
            }
            Folder folder = null;
            if (folderCmisObject == null) {
                // if not, create the folder first
                boolean created = createMissingFoldersCMIS(folderPath);
                if (created) {
                    session.clear();
                    folderCmisObject = session.getObjectByPath(folderPath);
                    folder = (Folder) folderCmisObject;
                } else {
                    return false;
                }
            } else {
                folder = (Folder) folderCmisObject;
            }
            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
            properties.put(PropertyIds.NAME, filename);
            org.apache.chemistry.opencmis.client.api.Document newDoc = folder.createDocument(properties,
                    contentStream, VersioningState.MINOR);
            session.removeObjectFromCache(newDoc.getId());
            session.clear();
        }
        long duration = System.currentTimeMillis() - startTime;
        logger.debug(
                "TRACE: writeContentCMIS(String fullPath, InputStream content); {0}, {1}\n\t\tDuration: {2}",
                fullPath, "content", duration);
        return true;
    } catch (CmisBaseException e) {
        logger.error("Error writing content to a path {0}", e, fullPath);
    } catch (NullPointerException e) {
        logger.error("Error writing content to a path {0}", e, fullPath);
    } catch (Throwable t) {
        logger.error("Error writing content to a path {0}", t, fullPath);
    }
    long duration = System.currentTimeMillis() - startTime;
    logger.debug("writeContentCMIS(String fullPath, InputStream content); {0}, {1}\n\t\tDuration: {2}",
            fullPath, "content", duration);
    return false;
}

From source file:org.craftercms.profile.services.impl.ProfileServiceImpl.java

private String getAttachmentContentType(final String attachmentName) throws ProfileException {
    String mimeType = new MimetypesFileTypeMap().getContentType(attachmentName);

    if (validAttachmentMimeTypes.contains(mimeType)) {
        return mimeType;
    }//ww  w.j a  va2 s. com

    throw new ProfileException(
            "File " + attachmentName + " if of content Type " + mimeType + " which is not allowed");
}

From source file:ome.services.blitz.repo.PublicRepositoryI.java

/**
 * Get the mimetype for a file./*from   w ww.  j  av a 2 s. com*/
 *
 * @param file
 *            A File in a repository.
 * @return A String representing the mimetype.
 *
 * TODO Return the correct Format object in place of a dummy one
 */
private String getMimetype(File file) {

    final String contentType = new MimetypesFileTypeMap().getContentType(file);
    return contentType;

}

From source file:com.salesmanager.central.catalog.EditProductAction.java

public String cropProductImage() {

    if (this.getProduct() == null || this.getProduct().getProductId() == 0) {
        return "productList";
    }/*from   w w  w  . j a  v  a  2 s  . c o  m*/

    try {

        Context ctx = (Context) super.getServletRequest().getSession().getAttribute(ProfileConstants.context);
        CatalogService catalogservice = (CatalogService) ServiceFactory
                .getService(ServiceFactory.CatalogService);
        ReferenceService rservice = (ReferenceService) ServiceFactory
                .getService(ServiceFactory.ReferenceService);
        MerchantService service = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
        MerchantStore mStore = service.getMerchantStore(ctx.getMerchantid());
        Map<String, String> moduleConfigMap = rservice
                .getModuleConfigurationsKeyValue(mStore.getTemplateModule(), mStore.getCountry());

        product = catalogservice.getProduct(this.getProduct().getProductId());
        //String folder = conf.getString("core.product.image.filefolder")
        String folder = FileUtil.getProductFilePath() + "/" + this.getProduct().getMerchantId() + "/";
        ProductImageUtil imutil = new ProductImageUtil();
        File croppedImg = imutil.getCroppedImage(new File(folder + this.getProduct().getProductImage()), x1, y1,
                productImageWidth, productImageHeight);
        imutil.uploadCropedProductImages(croppedImg, this.getProduct().getProductImageLarge(),
                new MimetypesFileTypeMap().getContentType(croppedImg), this.getProduct(), moduleConfigMap);

        super.setSuccessMessage();

    } catch (Exception e) {
        log.error(e);
        super.addActionError(getText("error.technical"));
        return SUCCESS;
    }

    return SUCCESS;

}