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.scripting.ScriptingPlugIn.java

/**
 * Deploy an application//from w  ww.j a va  2 s .c  o m
 *
 * @param aConnector
 * @param aToken
 * @throws Exception
 */
public void deployAction(WebSocketConnector aConnector, Token aToken) throws Exception {
    // getting calling arguments
    String lAppFile = aToken.getString("appFile");
    boolean lDeleteAfterDeploy = aToken.getBoolean("deleteAfterDeploy", false);
    boolean lHotDeploy = aToken.getBoolean("hotDeploy", false);

    // getting the FSP instance
    TokenPlugIn lFSP = (TokenPlugIn) getPlugInChain().getPlugIn("jws.filesystem");
    Assert.notNull(lFSP, "FileSystem plug-in is not running!");

    // creating invoke request for FSP
    Token lCommand = TokenFactory.createToken(JWebSocketServerConstants.NS_BASE + ".plugins.filesystem",
            "getAliasPath");
    lCommand.setString("alias", "privateDir");
    Token lResult = lFSP.invoke(aConnector, lCommand);
    Assert.notNull(lResult,
            "Unable to communicate with the FileSystem plug-in " + "to retrieve the client private directory!");

    // locating the app zip file
    File lAppZipFile = new File(lResult.getString("aliasPath") + File.separator + lAppFile);
    Assert.isTrue(lAppZipFile.exists(), "The target application file '" + lAppFile + "' does not exists"
            + " on the user file-system scope!");

    // validating MIME type
    String lFileType = new MimetypesFileTypeMap().getContentType(lAppZipFile);
    Assert.isTrue("application/zip, application/octet-stream".contains(lFileType),
            "The file format is not valid! Expecting a ZIP compressed directory.");

    // umcompressing in TEMP unique folder
    File lTempDir = new File(FileUtils.getTempDirectory().getCanonicalPath() + File.separator
            + UUID.randomUUID().toString() + File.separator);

    try {
        Tools.unzip(lAppZipFile, lTempDir);
        if (lDeleteAfterDeploy) {
            lAppZipFile.delete();
        }
    } catch (IOException lEx) {
        throw new Exception("Unable to uncompress zip file: " + lEx.getMessage());
    }

    // validating structure
    File[] lTempAppDirContent = lTempDir.listFiles((FileFilter) FileFilterUtils.directoryFileFilter());
    Assert.isTrue(1 == lTempAppDirContent.length && lTempAppDirContent[0].isDirectory(),
            "Compressed application has invalid directory structure! " + "Expecting a single root folder.");

    // executing before-load checks
    execAppBeforeLoadChecks(lTempAppDirContent[0].getName(), lTempAppDirContent[0].getPath());

    // copying application content to apps directory
    File lAppDir = new File(mSettings.getAppsDirectory() + File.separator + lTempAppDirContent[0].getName());

    FileUtils.copyDirectory(lTempAppDirContent[0], lAppDir);
    FileUtils.deleteDirectory(lTempDir);

    // getting the application name
    String lAppName = lAppDir.getName();

    // checking security
    if (!hasAuthority(aConnector, NS + ".deploy.*") && !hasAuthority(aConnector, NS + ".deploy." + lAppName)) {
        sendToken(aConnector, createAccessDenied(aToken));
        return;
    }

    // loading the script app
    loadApp(lAppName, lAppDir.getAbsolutePath(), lHotDeploy);

    // broadcasting event to other ScriptingPlugIn nodes
    MapMessage lMessage = getServer().getJMSManager().buildMessage(NS, ClusterMessageTypes.LOAD_APP.name());
    lMessage.setStringProperty("appName", lAppName);
    lMessage.setBooleanProperty("hotLoad", lHotDeploy);
    lMessage.setStringProperty(Attributes.NODE_ID, JWebSocketConfig.getConfig().getNodeId());

    // sending the message
    getServer().getJMSManager().send(lMessage);

    // finally send acknowledge response
    sendToken(aConnector, createResponse(aToken));
}

From source file:org.betaconceptframework.astroboa.test.engine.service.ContentServiceTest.java

private ContentObject saveAndAssertBinaryContentIsSaved(ContentObject contentObject, String contentSource,
        File fileWhichContainsContent, String property, Map<String, byte[]> binaryContent) throws Exception {
    try {/*from w  ww. j av a2s.  c  o m*/

        ImportConfiguration configuration = ImportConfiguration.object()
                .persist(PersistMode.PERSIST_ENTITY_TREE).version(false).updateLastModificationTime(true)
                .addBinaryContent(binaryContent).build();

        contentObject = importService.importContentObject(contentSource, configuration);

        //reload object 
        ContentObject object = contentService.getContentObject(contentObject.getId(),
                ResourceRepresentationType.CONTENT_OBJECT_INSTANCE, FetchLevel.ENTITY, CacheRegion.NONE, null,
                false);

        BinaryProperty imageProperty = (BinaryProperty) object.getCmsProperty(property);

        Assert.assertTrue(imageProperty.hasValues(), "No binary channel saved for " + property + " property");

        for (BinaryChannel imageBinaryChannel : imageProperty.getSimpleTypeValues()) {

            String sourceFilename = imageBinaryChannel.getSourceFilename();

            Assert.assertTrue(StringUtils.isNotBlank(sourceFilename),
                    " BinaryChannel " + imageBinaryChannel.getName() + " does not have a source file name");

            File fileWhoseContentsAreSavedInBinaryChannel = null;

            if (sourceFilename.equals(fileWhichContainsContent.getName())) {
                fileWhoseContentsAreSavedInBinaryChannel = fileWhichContainsContent;
            } else {
                throw new Exception("BnaryChannel contains an invalid source file name " + sourceFilename);
            }

            String mimeType = new MimetypesFileTypeMap()
                    .getContentType(fileWhoseContentsAreSavedInBinaryChannel);

            if (property.contains(".")) {
                Assert.assertEquals(imageBinaryChannel.getName(),
                        StringUtils.substringAfterLast(property, "."));
            } else {
                Assert.assertEquals(imageBinaryChannel.getName(), property);
            }
            Assert.assertEquals(imageBinaryChannel.getMimeType(), mimeType);
            Assert.assertEquals(imageBinaryChannel.getSourceFilename(), sourceFilename);
            Assert.assertEquals(imageBinaryChannel.getSize(),
                    FileUtils.readFileToByteArray(fileWhoseContentsAreSavedInBinaryChannel).length);
            Assert.assertEquals(imageBinaryChannel.getModified().getTimeInMillis(),
                    fileWhoseContentsAreSavedInBinaryChannel.lastModified());

            //Now test in jcr to see if the proper node is created
            Node binaryChannelNode = getSession().getNodeByIdentifier(imageBinaryChannel.getId());

            //If node is not found then exception has already been thrown
            Assert.assertEquals(binaryChannelNode.getName(), imageBinaryChannel.getName(),
                    " Invalid name for binary data jcr node " + binaryChannelNode.getPath());

            if (property.contains(".")) {
                Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Name.getJcrName()).getString(),
                        StringUtils.substringAfterLast(property, "."));
            } else {
                Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Name.getJcrName()).getString(),
                        property);
            }

            Assert.assertEquals(
                    binaryChannelNode.getProperty(JcrBuiltInItem.JcrMimeType.getJcrName()).getString(),
                    mimeType);
            Assert.assertEquals(
                    binaryChannelNode.getProperty(CmsBuiltInItem.SourceFileName.getJcrName()).getString(),
                    sourceFilename);
            Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Size.getJcrName()).getLong(),
                    fileWhoseContentsAreSavedInBinaryChannel.length());
            Assert.assertEquals(binaryChannelNode.getProperty(JcrBuiltInItem.JcrLastModified.getJcrName())
                    .getDate().getTimeInMillis(), fileWhoseContentsAreSavedInBinaryChannel.lastModified());

        }

    } catch (Exception e) {
        logger.error("Initial \n{}", contentSource);
        throw e;
    }

    return contentObject;
}

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;
        }/*from  ww  w. j a va2  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:org.sakaiproject.tool.assessment.qti.helper.ExtractionHelper.java

/**
 * the ip address is in a newline delimited string
 * @param assessment/* ww w .  j  av a  2 s . c  o  m*/
 */
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:it.doqui.index.ecmengine.business.personalization.importer.ArchiveImporterJob.java

/**
 * Crea un contenuto sul repository a partire da un file su filesystem.
 *
 * @param content/*from w  w w  .  jav  a 2 s  .com*/
 *            Il file da creare sul repository.
 * @param parentNodeRef
 *            Il {@code NodeRef} del nodo sotto cui creare il contenuto.
 * @param contentTypeQName
 *            Il {@code QName} del tipo di contenuto da creare.
 * @param contentNamePropertyQName
 *            Il {@code QName} del nome del contenuto da creare.
 * @param containerAssocTypeQName
 *            Il {@code QName} dell'associazione che lega contenuto e nodo
 *            padre.
 *
 * @return Il {@code NodeRef} del contenuto creato.
 *
 * @throws Exception
 */
private boolean createContent(File content, NodeRef parentNodeRef, QName contentTypeQName,
        QName contentNamePropertyQName, QName containerAssocTypeQName) throws Exception {
    logger.debug("[ArchiveImporterJob::createContent] BEGIN");
    boolean bRet = false;
    try {
        // Verifico se il contenuto e' presente nel nodo padre
        NodeRef nr = nodeService.getChildByName(parentNodeRef, containerAssocTypeQName, content.getName());

        // Se non e' presente, provo a crearlo
        if (nr == null) {
            // Creazione nodo
            QName prefixedNameQName = resolvePrefixNameToQName("cm:" + content.getName());
            Map<QName, Serializable> props = new HashMap<QName, Serializable>();
            props.put(contentNamePropertyQName, content.getName());

            ChildAssociationRef contentChildRef = nodeService.createNode(parentNodeRef, containerAssocTypeQName,
                    prefixedNameQName, contentTypeQName, props);

            // Scrittura contenuto
            final ContentWriter writer = contentService.getWriter(contentChildRef.getChildRef(),
                    ContentModel.PROP_CONTENT, true);

            writer.setMimetype(new MimetypesFileTypeMap().getContentType(content));
            writer.setEncoding(getEncoding(content));
            writer.putContent(content);

            // Se riesco a scrivere
            bRet = true;
        }

    } catch (DuplicateChildNodeNameException dc) {
        // In caso di contenuto duplicato, viene usata una policy conservativa, e viene tenuto
        // Il valore presente in repository
        logger.debug("[ArchiveImporterJob::createContent] Contenuto presente (" + content.getName() + ")");
    } catch (Exception e) {
        throw e;
    } finally {
        logger.debug("[ArchiveImporterJob::createContent] END");
    }

    return bRet;
}

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);// w  w  w. j  av  a2  s .co  m
    MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
    String contentType = mimetypesFileTypeMap.getContentType(filename);
    ContentResource contentResource = attachmentHelper.createContentResource(fullFilePath.toString(), filename,
            contentType);

    return contentResource;
}

From source file:org.betaconceptframework.astroboa.test.engine.service.ContentServiceTest.java

public void testUnmanagedBinaryChannel() throws Exception {
    //Create content objects for test
    RepositoryUser systemUser = getSystemUser();

    ContentObject contentObject = createContentObject(systemUser, "unmanagedImage");

    BinaryChannel logoBinaryChannel = loadUnManagedBinaryChannel(logo.getName(), "unmanagedImage");
    BinaryChannel logo2BinaryChannel = loadUnManagedBinaryChannel(logo2.getName(), "unmanagedImage");

    //Add two binary channels in property image
    ((BinaryProperty) contentObject.getCmsProperty("unmanagedImage")).addSimpleTypeValue(logoBinaryChannel);
    ((BinaryProperty) contentObject.getCmsProperty("unmanagedImage")).addSimpleTypeValue(logo2BinaryChannel);

    contentObject = contentService.save(contentObject, false, true, null);

    markObjectForRemoval(contentObject);

    ContentObject contentObjectReloaded = contentService.getContentObject(contentObject.getId(),
            ResourceRepresentationType.CONTENT_OBJECT_INSTANCE, FetchLevel.ENTITY, CacheRegion.NONE, null,
            false);/* www .j  a va2 s  .c o  m*/

    BinaryProperty unmanagedImageProperty = (BinaryProperty) contentObjectReloaded
            .getCmsProperty("unmanagedImage");

    Assert.assertTrue(unmanagedImageProperty.hasValues(),
            "No binary channel saved for unmanagedImage property");
    Assert.assertTrue(unmanagedImageProperty.getSimpleTypeValues().size() == 2,
            "Should have saved 2 binary channels for unmanagedImage property");

    for (BinaryChannel unmanagedImageBinaryChannel : unmanagedImageProperty.getSimpleTypeValues()) {

        String sourceFilename = unmanagedImageBinaryChannel.getSourceFilename();

        Assert.assertTrue(StringUtils.isNotBlank(sourceFilename), " BinaryChannel "
                + unmanagedImageBinaryChannel.getName() + " does not have a source file name");

        File fileWhoseContentsAreSavedInBinaryChannel = null;

        if (sourceFilename.equals(logo.getName())) {
            fileWhoseContentsAreSavedInBinaryChannel = logo;
        } else if (sourceFilename.equals(logo2.getName())) {
            fileWhoseContentsAreSavedInBinaryChannel = logo2;
        } else {
            throw new Exception("BnaryChannel contains an invalid source file name " + sourceFilename);
        }

        String mimeType = new MimetypesFileTypeMap().getContentType(fileWhoseContentsAreSavedInBinaryChannel);

        Assert.assertEquals(unmanagedImageBinaryChannel.getName(), "unmanagedImage");
        Assert.assertEquals(unmanagedImageBinaryChannel.getMimeType(), mimeType);
        Assert.assertEquals(unmanagedImageBinaryChannel.getSourceFilename(), sourceFilename);
        Assert.assertEquals(unmanagedImageBinaryChannel.getSize(),
                fileWhoseContentsAreSavedInBinaryChannel.length());
        Assert.assertEquals(unmanagedImageBinaryChannel.getModified().getTimeInMillis(),
                fileWhoseContentsAreSavedInBinaryChannel.lastModified());

        //Now test in jcr to see if the proper node is created
        //Unmanaged Binary property do not have an ID as they represent a jcr property
        Node contentObjectNode = getSession().getNodeByIdentifier(contentObjectReloaded.getId());

        Property unmanagedImageJcrProperty = contentObjectNode.getProperty("unmanagedImage");

        //This property is multivalue and should contain
        Value[] relativePaths = unmanagedImageJcrProperty.getValues();

        Assert.assertEquals(relativePaths.length, 2,
                " Jcr property " + unmanagedImageJcrProperty.getPath() + " does not contain 2 values");

        boolean foundPath = true;
        for (Value relativePath : relativePaths) {
            if (relativePath.getString().equals(fileWhoseContentsAreSavedInBinaryChannel.getName())) {
                foundPath = true;
                break;
            }
        }

        Assert.assertTrue(foundPath, "Relative Path for unmanaged image "
                + fileWhoseContentsAreSavedInBinaryChannel.getName() + " was not saved");

    }

}

From source file:org.betaconceptframework.astroboa.test.engine.service.ContentServiceTest.java

@Test
public void testManagedBinaryChannel() throws Exception {
    //Create content objects for test
    RepositoryUser systemUser = getSystemUser();

    ContentObject contentObject = createContentObject(systemUser, "image");

    BinaryChannel logoBinaryChannel = loadManagedBinaryChannel(logo, "image");
    BinaryChannel logo2BinaryChannel = loadManagedBinaryChannel(logo2, "image");

    //Add two binary channels in property image
    ((BinaryProperty) contentObject.getCmsProperty("image")).addSimpleTypeValue(logoBinaryChannel);
    ((BinaryProperty) contentObject.getCmsProperty("image")).addSimpleTypeValue(logo2BinaryChannel);

    contentObject = contentService.save(contentObject, false, true, null);

    markObjectForRemoval(contentObject);

    ContentObject contentObjectReloaded = contentService.getContentObject(contentObject.getId(),
            ResourceRepresentationType.CONTENT_OBJECT_INSTANCE, FetchLevel.ENTITY, CacheRegion.NONE, null,
            false);/*from w w w .  java  2 s.  com*/

    BinaryProperty imageProperty = (BinaryProperty) contentObjectReloaded.getCmsProperty("image");

    Assert.assertTrue(imageProperty.hasValues(), "No binary channel saved for image property");
    Assert.assertTrue(imageProperty.getSimpleTypeValues().size() == 2,
            "Should have saved 2 binary channels for image property");

    for (BinaryChannel imageBinaryChannel : imageProperty.getSimpleTypeValues()) {

        String sourceFilename = imageBinaryChannel.getSourceFilename();

        Assert.assertTrue(StringUtils.isNotBlank(sourceFilename),
                " BinaryChannel " + imageBinaryChannel.getName() + " does not have a source file name");

        File fileWhoseContentsAreSavedInBinaryChannel = null;

        if (sourceFilename.equals(logo.getName())) {
            fileWhoseContentsAreSavedInBinaryChannel = logo;
        } else if (sourceFilename.equals(logo2.getName())) {
            fileWhoseContentsAreSavedInBinaryChannel = logo2;
        } else {
            throw new Exception("BnaryChannel contains an invalid source file name " + sourceFilename);
        }

        String mimeType = new MimetypesFileTypeMap().getContentType(fileWhoseContentsAreSavedInBinaryChannel);

        Assert.assertEquals(imageBinaryChannel.getName(), "image");
        Assert.assertEquals(imageBinaryChannel.getMimeType(), mimeType);
        Assert.assertEquals(imageBinaryChannel.getSourceFilename(), sourceFilename);
        Assert.assertEquals(imageBinaryChannel.getSize(), fileWhoseContentsAreSavedInBinaryChannel.length());
        Assert.assertEquals(imageBinaryChannel.getModified().getTimeInMillis(),
                fileWhoseContentsAreSavedInBinaryChannel.lastModified());

        //Now test in jcr to see if the proper node is created
        Node binaryChannelNode = getSession().getNodeByIdentifier(imageBinaryChannel.getId());

        //If node is not found then exception has already been thrown
        Assert.assertEquals(binaryChannelNode.getName(), imageBinaryChannel.getName(),
                " Invalid name for binary data jcr node " + binaryChannelNode.getPath());

        Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Name.getJcrName()).getString(),
                "image");
        Assert.assertEquals(binaryChannelNode.getProperty(JcrBuiltInItem.JcrMimeType.getJcrName()).getString(),
                mimeType);
        Assert.assertEquals(
                binaryChannelNode.getProperty(CmsBuiltInItem.SourceFileName.getJcrName()).getString(),
                sourceFilename);
        Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Size.getJcrName()).getLong(),
                fileWhoseContentsAreSavedInBinaryChannel.length());
        Assert.assertEquals(binaryChannelNode.getProperty(JcrBuiltInItem.JcrLastModified.getJcrName()).getDate()
                .getTimeInMillis(), fileWhoseContentsAreSavedInBinaryChannel.lastModified());

    }

}

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

/**
 * Default file use//  w w  w .j av a2  s  . c  o m
 * @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;
}

From source file:org.etudes.jforum.view.admin.ImportExportAction.java

/**
 * check and save the resource is not existing
 * /*from w w  w .jav a  2 s .  c  o  m*/
 * @param refId
 *          - reference id
 * @param unZippedDirPath
 *          - unzipped directory path
 */
private void checkAndSaveResource(String refId, String unZippedDirPath) {
    if (refId == null || refId.trim().length() == 0)
        return;

    /*try
    {
       refId = URLDecoder.decode(refId, "UTF-8");
    }
    catch (UnsupportedEncodingException e)
    {
       if (logger.isWarnEnabled()) logger.warn("checkAndSaveResource: " + e);
    }*/

    if (!refId.startsWith("/"))
        refId = "/" + refId;

    String siteId = ToolManager.getCurrentPlacement().getContext();

    boolean exisResource = false;

    // get the resource
    try {
        // bypass security when reading the resource to copy
        SecurityService.pushAdvisor(new SecurityAdvisor() {
            public SecurityAdvice isAllowed(String userId, String function, String reference) {
                return SecurityAdvice.ALLOWED;
            }
        });

        //ContentResource resource = ContentHostingService.getResource("/group/" + siteId + refId);
        ContentHostingService.checkResource("/group/" + siteId + refId);

        exisResource = true;

    } catch (PermissionException e) {
        if (logger.isWarnEnabled())
            logger.warn("checkAndSaveResource: " + e.toString());

        return;
    } catch (IdUnusedException e) {
        /*if (logger.isWarnEnabled())
           logger.warn("checkAndSaveResource: " + e.toString());*/
    } catch (TypeException e) {
        if (logger.isWarnEnabled())
            logger.warn("checkAndSaveResource(String , String): " + e.toString());

        return;
    } finally {
        SecurityService.popAdvisor();
    }

    if (logger.isDebugEnabled())
        logger.debug("Resource is " + exisResource);

    if (!exisResource) {
        // bypass security when reading the resource to copy
        SecurityService.pushAdvisor(new SecurityAdvisor() {
            public SecurityAdvice isAllowed(String userId, String function, String reference) {
                return SecurityAdvice.ALLOWED;
            }
        });

        // the new resource collection and name
        String destinationCollection = "/group/" + siteId + refId;
        String displayName = refId.substring(refId.lastIndexOf("/") + 1);

        // make sure to remove the reference root sakai:reference-root
        ResourcePropertiesEdit props = ContentHostingService.newResourceProperties();
        props.removeProperty("sakai:reference-root");
        props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);

        File file = new File(unZippedDirPath + File.separator + "resources" + File.separator
                + "embeded_jf_content/content/group/" + refId);
        byte[] body;
        try {
            body = readFile(file);
        } catch (IOException e) {
            if (logger.isWarnEnabled())
                logger.warn("checkAndSaveResource(String , String): " + e.toString());

            return;
        }
        String type = new MimetypesFileTypeMap().getContentType(file);

        if (logger.isDebugEnabled())
            logger.debug("checkAndSaveResource: type : " + type);

        // create url/link resource if the file has no extentions and has valid url in the file
        if (displayName.indexOf(".") == -1) {
            // this is a link if the file has one line and valid url
            type = "text/url";
        }

        ContentResource importedResource = null;
        try {
            //String destinationPath = destinationCollection + destinationName;
            String destinationPath = destinationCollection;
            //importedResource = ContentHostingService.addResource(destinationName, destinationCollection, 255, type, body, props, 0);
            importedResource = ContentHostingService.addResource(destinationPath, type, body, props, 0);
        } catch (IdInvalidException e) {
            if (logger.isWarnEnabled())
                logger.warn("checkAndSaveResource(String , String): " + e.toString());
        } catch (InconsistentException e) {
            if (logger.isWarnEnabled())
                logger.warn("checkAndSaveResource(String , String): " + e.toString());
        } catch (OverQuotaException e) {
            if (logger.isWarnEnabled())
                logger.warn("checkAndSaveResource(String , String): " + e.toString());
        } catch (ServerOverloadException e) {
            if (logger.isWarnEnabled())
                logger.warn("checkAndSaveResource(String , String): " + e.toString());
        } catch (PermissionException e) {
            if (logger.isWarnEnabled())
                logger.warn("checkAndSaveResource(String , String): " + e.toString());
        } catch (IdUsedException e) {
            if (logger.isWarnEnabled())
                logger.warn("checkAndSaveResource(String , String): " + e.toString());
        } finally {
            SecurityService.popAdvisor();
        }

    }
}