Example usage for javax.activation MimetypesFileTypeMap getContentType

List of usage examples for javax.activation MimetypesFileTypeMap getContentType

Introduction

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

Prototype

public synchronized String getContentType(String filename) 

Source Link

Document

Return the MIME type based on the specified file name.

Usage

From source file:com.collabnet.ccf.pi.qc.v90.QCAttachmentHandler.java

/**
 * Constructs the GenericArtifact Java object for the attachment after
 * getting the schema from getSchemaAttachment method It also populates all
 * the values into the attachment artifact.
 * //  w ww  .j a v  a 2  s.  c  o  m
 * @param qcc
 * @param entityId
 * @param attachmentName
 * @param deletedAttachments
 * @param deleteTransactionId
 * @param shouldShipAttachmentsWithArtifact
 * @param isDefectRepository
 * @return GenericArtifact Containing all the field values.
 */
public GenericArtifact getGenericArtifactObjectOfAttachment(IConnection qcc, String entityId,
        String attachmentName, long maxAttachmentSizePerArtifact, boolean deletedAttachments,
        String deleteTransactionId, boolean shouldShipAttachmentsWithArtifact, boolean isDefectRepository) {
    long attachmentSize = 0;
    String thisMimeType = null;
    if (attachmentName != null) {
        genericArtifact = getSchemaAttachment(qcc, entityId, attachmentName, deletedAttachments,
                deleteTransactionId);
    }
    if (genericArtifact == null)
        return null;
    if (!deletedAttachments) {

        MimetypesFileTypeMap mimeType = new MimetypesFileTypeMap();
        if (attachmentName != null)
            thisMimeType = mimeType.getContentType(attachmentName);
        byte data[] = null;
        File qcAttachmentFile = null;
        String contentType = (String) genericArtifact
                .getAllGenericArtifactFieldsWithSameFieldName(AttachmentMetaData.ATTACHMENT_TYPE).get(0)
                .getFieldValue().toString();
        List<GenericArtifactField> allFields = genericArtifact.getAllGenericArtifactFields();
        int noOfFields = allFields.size();
        for (int cnt = 0; cnt < noOfFields; cnt++) {
            GenericArtifactField thisField = allFields.get(cnt);
            thisField.setFieldAction(GenericArtifactField.FieldActionValue.REPLACE);
            // thisField.setFieldDisplayName(thisField.getFieldName());
            thisField.setFieldValueHasChanged(true);
            if (thisField.getFieldName().equals(AttachmentMetaData.ATTACHMENT_TYPE)) {
                if (contentType.equals("DATA")) {
                    thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
                    if (!deletedAttachments) {
                        if (isDefectRepository) {
                            IBugFactory bugFactory = null;
                            IBug bug = null;
                            try {
                                bugFactory = qcc.getBugFactory();
                                bug = bugFactory.getItem(entityId);
                                qcAttachmentFile = bug.retrieveAttachmentData(attachmentName,
                                        delayBeforeAttachmentDownload, maximumAttachmentRetryCount);
                            } catch (AttachmentUploadStillInProgressException e) {
                                throw e;
                            } catch (Exception e) {
                                String message = "An Exception occured in QCAttachmentHandler.getGenericArtifactObjectOfAttachment"
                                        + " while trying to do retrieveAttachmentData on Filename "
                                        + attachmentName;
                                log.error(message, e);
                                throw new CCFRuntimeException(message, e);
                            } finally {
                                bugFactory = null;
                                if (bug != null) {
                                    bug.safeRelease();
                                }
                            }
                        } else {
                            IRequirementsFactory reqFactory = null;
                            IRequirement req = null;
                            try {
                                reqFactory = qcc.getRequirementsFactory();
                                req = reqFactory.getItem(entityId);
                                qcAttachmentFile = req.retrieveAttachmentData(attachmentName,
                                        delayBeforeAttachmentDownload, maximumAttachmentRetryCount);
                            } catch (AttachmentUploadStillInProgressException e) {
                                throw e;
                            } catch (Exception e) {
                                String message = "An Exception occured in QCAttachmentHandler.getGenericArtifactObjectOfAttachment"
                                        + " while trying to do retrieveAttachmentData on Filename "
                                        + attachmentName;
                                log.error(message, e);
                                throw new CCFRuntimeException(message, e);
                            } finally {
                                reqFactory = null;
                                if (req != null) {
                                    req.safeRelease();
                                }
                            }
                        }
                        if (qcAttachmentFile == null) {
                            return null;
                        }
                        attachmentSize = qcAttachmentFile.length();

                        if (attachmentSize > maxAttachmentSizePerArtifact) {
                            log.warn("The attachment " + attachmentName
                                    + " is bigger than our maxAttachmentSizePerArtifact, so cannot ship.");
                            return null;
                        } else {
                            if (!shouldShipAttachmentsWithArtifact) {
                                File tempFile = null;
                                try {
                                    if (!qcAttachmentFile.exists()) {
                                        log.warn("Downloaded attachment is not valid");
                                        return null;
                                    }
                                    tempFile = File.createTempFile("QC_Attachment", "file");
                                    boolean renamingSuccessful = qcAttachmentFile.renameTo(tempFile);
                                    if (!renamingSuccessful) {
                                        tempFile = qcAttachmentFile;
                                    }
                                    String attachmentDataFileName = tempFile.getAbsolutePath();
                                    GenericArtifactField attachmentDataFileField = genericArtifact.addNewField(
                                            AttachmentMetaData.ATTACHMENT_DATA_FILE,
                                            GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD);
                                    attachmentDataFileField
                                            .setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
                                    attachmentDataFileField.setFieldAction(FieldActionValue.REPLACE);
                                    attachmentDataFileField.setFieldValue(attachmentDataFileName);
                                    log.debug("Shipping the reference of the attachment "
                                            + attachmentDataFileName);
                                    if (tempFile.length() == 0) {
                                        log.warn("The file " + attachmentDataFileName
                                                + " does not contain any data.");
                                    }
                                    data = null;
                                } catch (IOException e) {
                                    String message = "Could not write attachment content to temp file."
                                            + " Shipping the attachment with the artifact.";
                                    log.error(message, e);
                                    throw new CCFRuntimeException(message, e);
                                }
                            } else {
                                if (!qcAttachmentFile.exists()) {
                                    log.warn("Downloaded attachment is not valid");
                                    return null;
                                }
                                ByteArrayOutputStream baOS = new ByteArrayOutputStream();
                                FileInputStream fis = null;
                                try {
                                    fis = new FileInputStream(qcAttachmentFile);
                                    int readCount = 0;
                                    byte[] tmpData = new byte[1024 * 3];
                                    if ((readCount = fis.read(tmpData)) != -1) {
                                        baOS.write(tmpData, 0, readCount);
                                    }
                                    data = baOS.toByteArray();
                                    fis.close();
                                    baOS.close();
                                } catch (FileNotFoundException e) {
                                    String message = "Could not read attachment content." + " File not found "
                                            + qcAttachmentFile.getAbsolutePath();
                                    log.error(message, e);
                                    throw new CCFRuntimeException(message, e);
                                } catch (IOException e) {
                                    String message = "Could not read attachment content."
                                            + " IOException while reading "
                                            + qcAttachmentFile.getAbsolutePath();
                                    log.error(message, e);
                                    throw new CCFRuntimeException(message, e);
                                }
                            }
                        }
                    }
                }
            }
            if (thisField.getFieldName().equals(AttachmentMetaData.getAttachmentName())) {
                if (contentType.equals("DATA")) {
                    // For defects and requirements, QC adds a prefix consisting of the
                    // artifact type and ID to the file name. Images inserted into
                    // requirement rich text fields do not have a prefix, but are named
                    // RichContentImage_<randomID>.<extension>
                    // We remove the prefix if it exists.
                    String prefix = (isDefectRepository ? "BUG_" : "REQ_") + entityId + "_";
                    String tmpAttachmentName = attachmentName.startsWith(prefix)
                            ? attachmentName.substring(prefix.length())
                            : attachmentName;
                    thisField.setFieldValue(tmpAttachmentName);
                } else
                    thisField.setFieldValue("Unknown");
                thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
            } else if (thisField.getFieldName().equals(AttachmentMetaData.getAttachmentSize())) {
                thisField.setFieldValue(attachmentSize);
                thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.INTEGER);
            } else if (thisField.getFieldName().equals(AttachmentMetaData.getAttachmentSourceUrl())) {
                if (contentType.equals("DATA"))
                    thisField.setFieldValue("Unknown");
                else
                    thisField.setFieldValue(attachmentName);
                thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
            } else if (thisField.getFieldName().equals(AttachmentMetaData.getAttachmentMimeType())) {
                thisField.setFieldValue(thisMimeType);
                thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
            } else if (thisField.getFieldName().equals(AttachmentMetaData.getAttachmentValueIsNull())) {
                if (data != null)
                    thisField.setFieldValue(AttachmentMetaData.AttachmentValueIsNull.FALSE);
                else
                    thisField.setFieldValue(AttachmentMetaData.AttachmentValueIsNull.TRUE);
                thisField.setFieldValueType(GenericArtifactField.FieldValueTypeValue.STRING);
            }
        }
        if (data != null) {
            genericArtifact.setRawAttachmentData(data);
        }
    }
    return genericArtifact;
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Get mime type of the given file// www  . ja  v  a  2 s  .  co  m
 *
 * @param file
 * @return mime type
 */
public static String getFileMimeType(File file) {
    MimetypesFileTypeMap mimeMap = new MimetypesFileTypeMap();
    return mimeMap.getContentType(file);
}

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);
    }/*  www .  j  a v a  2  s .  c om*/
    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.studio.impl.v1.service.content.ContentServiceImpl.java

protected void loadContentTypeProperties(String site, ContentItemTO item, String contentType) {
    if (contentType != null && !contentType.equals("folder") && !contentType.equals("asset")) {
        ContentTypeConfigTO config = servicesConfig.getContentTypeConfig(site, contentType);
        if (config != null) {
            item.setForm(config.getForm());
            item.setFormPagePath(config.getFormPath());
            item.setPreviewable(config.isPreviewable());
            item.isPreviewable = item.previewable;
        }/*w  w w.  ja  v a 2 s . c om*/
    } else {
        MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        String mimeType = mimeTypesMap.getContentType(item.getName());
        if (mimeType != null && !StringUtils.isEmpty(mimeType)) {
            item.setPreviewable(ContentUtils.matchesPatterns(mimeType,
                    servicesConfig.getPreviewableMimetypesPaterns(site)));
            item.isPreviewable = item.previewable;
        }
    }
    // TODO CodeRev:but what if the config is null?
}

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);// w  w w. j  a  v a2  s.  c  o  m
    } 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.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/*www .j  a  v a 2  s .  c o  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.sakaiproject.tool.assessment.qti.helper.ExtractionHelper.java

private ContentResource makeContentResource(String filename) {
    AttachmentHelper attachmentHelper = new AttachmentHelper();
    StringBuffer fullFilePath = new StringBuffer(unzipLocation);
    fullFilePath.append("/");
    fullFilePath.append(filename);/*from   w  w w .ja  v a 2s  .  c om*/
    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
    String contentType = mimetypesFileTypeMap.getContentType(filename);
    ContentResource contentResource = attachmentHelper.createContentResource(fullFilePath.toString(), filename,
            contentType);

    return contentResource;
}

From source file:org.sakaiproject.tool.assessment.qti.helper.ExtractionHelper.java

/**
 * the ip address is in a newline delimited string
 * @param assessment/*from w w w.  j  a v a  2  s . c  om*/
 */
public String makeFCKAttachment(String text) {
    if (text == null) {
        return text;
    }
    String processedText = XmlUtil.processFormattedText(log, text);
    // if unzipLocation is null, there is no assessment attachment - no action is needed
    if (unzipLocation == null || processedText.equals("")) {
        return processedText;
    }

    String accessURL = ServerConfigurationService.getAccessUrl();
    String referenceRoot = AssessmentService.getContentHostingService().REFERENCE_ROOT;
    String prependString = accessURL + referenceRoot;
    StringBuffer updatedText = null;
    ContentResource contentResource = null;
    AttachmentHelper attachmentHelper = new AttachmentHelper();
    String resourceId = null;
    String importedPrependString = getImportedPrependString(processedText);
    if (importedPrependString == null) {
        return processedText;
    }
    String[] splittedString = processedText.split("src=\"" + importedPrependString);
    List<String> splittedList = new ArrayList<String>();
    String src = "";
    for (int i = 0; i < splittedString.length; i++) {
        splittedString[i] = src + splittedString[i];
        String[] splittedRefString = splittedString[i].split("href=\"" + importedPrependString);
        String href = "";
        for (int j = 0; j < splittedRefString.length; j++) {
            splittedRefString[j] = href + splittedRefString[j];
            splittedList.add(splittedRefString[j]);
            href = "href=\"";
        }
        src = "src=\"";
    }
    splittedString = splittedList.toArray(splittedString);
    int endIndex = 0;
    String filename = null;
    String contentType = null;
    String fullFilePath = null;
    String oldResourceId = null;

    updatedText = new StringBuffer(splittedString[0]);
    for (int i = 1; i < splittedString.length; i++) {
        log.debug("splittedString[" + i + "] = " + splittedString[i]);
        // Here is an example, splittedString will be something like:
        // /group/b917f0b9-e21d-4819-80ee-35feac91c9eb/Blue Hill.jpg" alt="...  or
        // /user/ktsao/Blue Hill.jpg" alt="...
        // oldResourceId = /group/b917f0b9-e21d-4819-80ee-35feac91c9eb/Blue Hill.jpg or /user/ktsao/Blue Hill.jpg
        // oldSplittedResourceId[0] = ""
        // oldSplittedResourceId[1] = group or user
        // oldSplittedResourceId[2] = b917f0b9-e21d-4819-80ee-35feac91c9eb or ktsao
        // oldSplittedResourceId[3] = Blue Hill.jpg
        endIndex = splittedString[i].indexOf("\"", splittedString[i].indexOf("\"") + 1);
        oldResourceId = splittedString[i].substring(splittedString[i].indexOf("\"") + 1, endIndex);
        String[] oldSplittedResourceId = oldResourceId.split("/");
        fullFilePath = unzipLocation + "/" + oldResourceId.replace(" ", "");
        filename = oldSplittedResourceId[oldSplittedResourceId.length - 1];
        MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
        contentType = mimetypesFileTypeMap.getContentType(filename);
        contentResource = attachmentHelper.createContentResource(fullFilePath, filename, contentType);

        if (contentResource != null) {
            resourceId = contentResource.getId();
            updatedText.append(splittedString[i].substring(0, splittedString[i].indexOf("\"") + 1));
            updatedText.append(prependString);
            updatedText.append(resourceId);
            updatedText.append(splittedString[i].substring(endIndex));
        } else {
            throw new RuntimeException("resourceId is null");
        }

    }
    return updatedText.toString();
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

/**
 * Default file use/*from ww w . j  a  va 2  s . c  om*/
 * @param filename
 */
public String getFileUse(String filename) {
    String use = null;

    // check for generated derivatives
    if (filename.endsWith(derivativesExt)) {
        String fid = filename.substring(0, filename.indexOf(derivativesExt));
        use = props.getProperty("derivatives." + fid + ".use");
    }

    if (use == null) {
        // check in fsUseMap
        String ext = filename.substring(filename.lastIndexOf(".") + 1);
        use = fsUseMap.get(ext);
    }

    if (use == null) {
        // fallback on mime type
        MimetypesFileTypeMap mimeTypes = new MimetypesFileTypeMap();
        String mimeType = mimeTypes.getContentType(filename);
        String format = mimeType.substring(0, mimeType.indexOf('/'));
        if (format.equals("application")) {
            format = "data";
        }
        if (!filename.startsWith("1.") && filename.endsWith(derivativesExt)) {
            // Derivative type
            use = format + "-thumbnail";
        } else {
            use = format + "-service";
        }
    }
    return use;
}