Java Code Examples for org.alfresco.service.cmr.repository.ContentData#getMimetype()

The following examples show how to use org.alfresco.service.cmr.repository.ContentData#getMimetype() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Document.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
public Document(NodeRef nodeRef, NodeRef parentNodeRef, Map<QName, Serializable> nodeProps, Map<String, UserInfo> mapUserInfo, ServiceRegistry sr)
{
    super(nodeRef, parentNodeRef, nodeProps, mapUserInfo, sr);

    Serializable val = nodeProps.get(ContentModel.PROP_CONTENT);

    if ((val != null) && (val instanceof ContentData)) {
        ContentData cd = (ContentData)val;
        String mimeType = cd.getMimetype();
        String mimeTypeName = sr.getMimetypeService().getDisplaysByMimetype().get(mimeType);
        contentInfo = new ContentInfo(mimeType, mimeTypeName, cd.getSize(), cd.getEncoding());
    }

    setIsFolder(false);
    setIsFile(true);
}
 
Example 2
Source File: WebDAV.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Return the Alfresco property value for the specified WebDAV property
 * 
 * @param davPropName String
 * @return Object
 */
public static Object getDAVPropertyValue( Map<QName, Serializable> props, String davPropName)
{
    // Convert the WebDAV property name to the corresponding Alfresco property
    
    QName propName = _propertyNameMap.get( davPropName);
    if ( propName == null)
        throw new AlfrescoRuntimeException("No mapping for WebDAV property " + davPropName);
    
    //  Return the property value
    Object value = props.get(propName);
    if (value instanceof ContentData)
    {
        ContentData contentData = (ContentData) value;
        if (davPropName.equals(WebDAV.XML_GET_CONTENT_TYPE))
        {
            value = contentData.getMimetype();
        }
        else if (davPropName.equals(WebDAV.XML_GET_CONTENT_LENGTH))
        {
            value = new Long(contentData.getSize());
        }
    }
    return value;
}
 
Example 3
Source File: ScriptNode.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns the names of the thumbnail defintions that can be applied to the content property of
 * this node.
 * <p>
 * Thumbanil defintions only appear in this list if they can produce a thumbnail for the content
 * found in the content property.  This will be determined by looking at the mimetype of the content
 * and the destinatino mimetype of the thumbnail.
 * 
 * @return  String[]    array of thumbnail names that are valid for the current content type
 */
public String[] getThumbnailDefinitions()
{
    ThumbnailService thumbnailService = this.services.getThumbnailService();
    
    List<String> result = new ArrayList<String>(7);
    
    Serializable value = this.nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT);
    ContentData contentData = DefaultTypeConverter.INSTANCE.convert(ContentData.class, value);
    
    if (ContentData.hasContent(contentData))
    {
        String mimetype = contentData.getMimetype();
        List<ThumbnailDefinition> thumbnailDefinitions = thumbnailService.getThumbnailRegistry().getThumbnailDefinitions(mimetype, contentData.getSize());
        for (ThumbnailDefinition thumbnailDefinition : thumbnailDefinitions)
        {
            result.add(thumbnailDefinition.getName());
        }
    }
    
    return (String[])result.toArray(new String[result.size()]);
}
 
Example 4
Source File: FormServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void checkContentDetails(NodeRef node, String expectedName, String expectedTitle, 
            String expectedMimetype, String expectedContent)
{
    Map<QName, Serializable> props = this.nodeService.getProperties(node);
    String name = (String)props.get(ContentModel.PROP_NAME);
    String title = (String)props.get(ContentModel.PROP_TITLE);
    assertEquals(expectedName, name);
    assertEquals(expectedTitle, title);
    
    ContentData contentData = (ContentData) this.nodeService.getProperty(node, ContentModel.PROP_CONTENT);
    assertNotNull(contentData);
    String mimetype = contentData.getMimetype();
    assertEquals(expectedMimetype, mimetype);
    
    ContentReader reader = this.contentService.getReader(node, ContentModel.PROP_CONTENT);
    assertNotNull(reader);
    String content = reader.getContentString();
    assertEquals(expectedContent, content);
}
 
Example 5
Source File: RenditionsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected Rendition toApiRendition(NodeRef renditionNodeRef)
{
    Rendition apiRendition = new Rendition();

    String renditionName = (String) nodeService.getProperty(renditionNodeRef, ContentModel.PROP_NAME);
    apiRendition.setId(renditionName);

    ContentData contentData = getContentData(renditionNodeRef, false);
    ContentInfo contentInfo = null;
    if (contentData != null)
    {
        contentInfo = new ContentInfo(contentData.getMimetype(),
                getMimeTypeDisplayName(contentData.getMimetype()),
                contentData.getSize(),
                contentData.getEncoding());
    }
    apiRendition.setContent(contentInfo);
    apiRendition.setStatus(RenditionStatus.CREATED);

    return apiRendition;
}
 
Example 6
Source File: NodeResourceHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
public ContentInfo getContentInfo(Map<QName, Serializable> props)
{
    final Serializable content = props.get(ContentModel.PROP_CONTENT);
    ContentInfo contentInfo = null;
    if ((content instanceof ContentData))
    {
        ContentData cd = (ContentData) content;
        contentInfo = new ContentInfo(cd.getMimetype(), cd.getSize(), cd.getEncoding());
    }
    return contentInfo;
}
 
Example 7
Source File: CompressingContentStore.java    From alfresco-simple-content-stores with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ContentReader getReader(final String contentUrl)
{
    // need to use information from context (if call came via ContentService#getReader(NodeRef, QName)) to find the real size, as the
    // size reported by the reader from the delegate may differ due to compression
    // context also helps us optimise by avoiding decompressing facade if content data mimetype does not require compression at all
    long properSize = -1;
    String mimetype = null;

    final Object contentDataCandidate = ContentStoreContext.getContextAttribute(ContentStoreContext.DEFAULT_ATTRIBUTE_CONTENT_DATA);
    if (contentDataCandidate instanceof ContentData)
    {
        final ContentData contentData = (ContentData) contentDataCandidate;
        if (contentUrl.equals(contentData.getContentUrl()))
        {
            properSize = contentData.getSize();
            mimetype = contentData.getMimetype();
        }
    }

    // this differs from shouldCompress determination in compressing writer / decompressing reader
    // if we don't know the mimetype yet (e.g. due to missing context), we can't make the assumption that content may not need
    // decompression at this point - mimetype may still be set via setMimetype() on reader instance
    final boolean shouldCompress = this.mimetypesToCompress == null || this.mimetypesToCompress.isEmpty() || mimetype == null
            || this.mimetypesToCompress.contains(mimetype) || this.isMimetypeToCompressWildcardMatch(mimetype);

    ContentReader reader;
    final ContentReader backingReader = super.getReader(contentUrl);
    if (shouldCompress)
    {
        reader = new DecompressingContentReader(backingReader, this.compressionType, this.mimetypesToCompress, properSize);
    }
    else
    {
        reader = backingReader;
    }

    return reader;
}
 
Example 8
Source File: BulkMetadataGet.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String getMimeType(ContentData contentProperty)
{
    String mimetype = null;

    if(contentProperty != null)
    {
        mimetype = contentProperty.getMimetype();
    }

    return mimetype;
}
 
Example 9
Source File: DecryptingContentReaderFacade.java    From alfresco-simple-content-stores with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public ContentData getContentData()
{
    final ContentData contentData = super.getContentData();
    // correct size
    final ContentData updatedData = new ContentData(contentData.getContentUrl(), contentData.getMimetype(), this.unencryptedSize,
            contentData.getEncoding(), contentData.getLocale());
    return updatedData;
}
 
Example 10
Source File: AbstractContentDataDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private ContentData sanitizeMimetype(ContentData contentData)
{
    String mimetype = contentData.getMimetype();
    if (mimetype != null)
    {
        mimetype = mimetype.toLowerCase();
        contentData = ContentData.setMimetype(contentData, mimetype);
    }
    return contentData;
}
 
Example 11
Source File: ContentDataPart.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * ContentDataPart 
 * @param contentService content service
 * @param partName String
 * @param data data
 */
public ContentDataPart(ContentService contentService, String partName, ContentData data) {
    super(partName, data.getMimetype(), data.getEncoding(), null);
    this.contentService = contentService;
    this.data = data;
    this.filename = partName;
}
 
Example 12
Source File: NodeContentData.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Construct
 */
public NodeContentData(NodeRef nodeRef, ContentData contentData)
{
    super(contentData.getContentUrl(), contentData.getMimetype(), contentData.getSize(),
            contentData.getEncoding(), contentData.getLocale());
    this.nodeRef = nodeRef;
}
 
Example 13
Source File: AbstractContentDataDAOImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Translates the {@link ContentData} into persistable values using the helper DAOs
 */
protected ContentDataEntity createContentDataEntity(ContentData contentData)
{
    // Resolve the content URL
    Long contentUrlId = null;
    String contentUrl = contentData.getContentUrl();
    long size = contentData.getSize();
    if (contentUrl != null)
    {
        ContentUrlEntity contentUrlEntity = new ContentUrlEntity();
        contentUrlEntity.setContentUrl(contentUrl);
        contentUrlEntity.setSize(size);
        Pair<Long, ContentUrlEntity> pair = contentUrlCache.createOrGetByValue(contentUrlEntity, controlDAO);
        contentUrlId = pair.getFirst();
    }

    // Resolve the mimetype
    Long mimetypeId = null;
    String mimetype = contentData.getMimetype();
    if (mimetype != null)
    {
        mimetypeId = mimetypeDAO.getOrCreateMimetype(mimetype).getFirst();
    }
    // Resolve the encoding
    Long encodingId = null;
    String encoding = contentData.getEncoding();
    if (encoding != null)
    {
        encodingId = encodingDAO.getOrCreateEncoding(encoding).getFirst();
    }
    // Resolve the locale
    Long localeId = null;
    Locale locale = contentData.getLocale();
    if (locale != null)
    {
        localeId = localeDAO.getOrCreateLocalePair(locale).getFirst();
    }
    
    // Create ContentDataEntity
    ContentDataEntity contentDataEntity = createContentDataEntity(contentUrlId, mimetypeId, encodingId, localeId);
    // Done
    return contentDataEntity;
}
 
Example 14
Source File: RenditionsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
private String getMimeType(NodeRef nodeRef)
{
    ContentData contentData = getContentData(nodeRef, true);
    return contentData.getMimetype();
}
 
Example 15
Source File: FormServiceImplTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSaveNodeForm() throws Exception
{
    // create FormData object containing the values to update
    FormData data = new FormData();
    
    // update the name
    String newName = "new-" + this.documentName;
    data.addFieldData("prop_cm_name", newName);
    
    // update the title property
    String newTitle = "This is the new title property";
    data.addFieldData("prop_cm_title", newTitle);
    
    // update the mimetype
    String newMimetype = MimetypeMap.MIMETYPE_HTML;
    data.addFieldData("prop_mimetype", newMimetype);
    
    // update the author property (this is on an aspect not applied)
    String newAuthor = "Gavin Cornwell";
    data.addFieldData("prop_cm_author", newAuthor);
    
    // update the originator
    String newOriginator = "[email protected]";
    data.addFieldData("prop_cm_originator", newOriginator);
    
    // update the adressees, add another
    String newAddressees = VALUE_ADDRESSEES1 + "," + VALUE_ADDRESSEES2 + "," + VALUE_ADDRESSEES3;
    data.addFieldData("prop_cm_addressees", newAddressees);
    
    // set the date to null (using an empty string)
    data.addFieldData("prop_cm_sentdate", "");
    
    // add an association to the child doc (as an attachment which is defined on an aspect not applied)
    //data.addField("assoc_cm_attachments_added", this.childDoc.toString());
    
    // try and update non-existent properties and assocs (make sure there are no exceptions)
    data.addFieldData("prop_cm_wrong", "This should not be persisted");
    data.addFieldData("cm_wrong", "This should not be persisted");
    data.addFieldData("prop_cm_wrong_property", "This should not be persisted");
    data.addFieldData("prop_cm_wrong_property_name", "This should not be persisted");
    data.addFieldData("assoc_cm_wrong_association", "This should be ignored");
    data.addFieldData("assoc_cm_wrong_association_added", "This should be ignored");
    data.addFieldData("assoc_cm_wrong_association_removed", "This should be ignored");
    data.addFieldData("assoc_cm_added", "This should be ignored");
    
    // persist the data
    this.formService.saveForm(new Item(NODE_FORM_ITEM_KIND, this.document.toString()), data);
    
    // retrieve the data directly from the node service to ensure its been changed
    Map<QName, Serializable> updatedProps = this.nodeService.getProperties(this.document);
    String updatedName = (String)updatedProps.get(ContentModel.PROP_NAME);
    String updatedTitle = (String)updatedProps.get(ContentModel.PROP_TITLE);
    String updatedAuthor = (String)updatedProps.get(ContentModel.PROP_AUTHOR);
    String updatedOriginator = (String)updatedProps.get(ContentModel.PROP_ORIGINATOR);
    List<String> updatedAddressees = (List<String>)updatedProps.get(ContentModel.PROP_ADDRESSEES);
    String wrong = (String)updatedProps.get(QName.createQName("cm", "wrong", this.namespaceService));
    Date sentDate = (Date)updatedProps.get(ContentModel.PROP_SENTDATE);
    
    assertEquals(newName, updatedName);
    assertEquals(newTitle, updatedTitle);
    assertEquals(newAuthor, updatedAuthor);
    assertEquals(newOriginator, updatedOriginator);
    assertNull("Expecting sentdate to be null", sentDate);
    assertNull("Expecting my:wrong to be null", wrong);
    assertNotNull("Expected there to be addressees", updatedAddressees);
    assertTrue("Expected there to be 3 addressees", updatedAddressees.size() == 3);
    assertEquals(VALUE_ADDRESSEES1, updatedAddressees.get(0));
    assertEquals(VALUE_ADDRESSEES2, updatedAddressees.get(1));
    assertEquals(VALUE_ADDRESSEES3, updatedAddressees.get(2));
    
    // check the titled aspect was automatically applied
    assertTrue("Expecting the cm:titled to have been applied", 
                this.nodeService.hasAspect(this.document, ContentModel.ASPECT_TITLED));
    
    // check the author aspect was automatically applied
    assertTrue("Expecting the cm:author to have been applied", 
                this.nodeService.hasAspect(this.document, ContentModel.ASPECT_AUTHOR));
    
    // check mimetype was updated
    ContentData contentData = (ContentData)updatedProps.get(ContentModel.PROP_CONTENT);
    if (contentData != null)
    {
        String updatedMimetype = contentData.getMimetype();
        assertEquals(MimetypeMap.MIMETYPE_HTML, updatedMimetype);
    }
    
    // check the association was added and the aspect it belongs to applied
    /*
    List<AssociationRef> assocs = this.nodeService.getTargetAssocs(this.document, 
                ContentModel.ASSOC_ATTACHMENTS);
    assertEquals("Expecting 1 attachment association", 1, assocs.size());
    assertEquals(assocs.get(0).getTargetRef().toString(), this.childDoc.toString());
    assertTrue("Expecting the cm:attachable to have been applied", 
                this.nodeService.hasAspect(this.document, ContentModel.ASPECT_ATTACHABLE));
    */
}
 
Example 16
Source File: EventsServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void contentWrite(NodeRef nodeRef, QName propertyQName, ContentData value)
{
    NodeInfo nodeInfo = getNodeInfo(nodeRef, NodeContentPutEvent.EVENT_TYPE);
    if(nodeInfo.checkNodeInfo())
    {
        String username = AuthenticationUtil.getFullyAuthenticatedUser();
        String networkId = TenantUtil.getCurrentDomain();

        String name = nodeInfo.getName();
        String objectId = nodeInfo.getNodeId();
        String siteId = nodeInfo.getSiteId();
        String txnId = AlfrescoTransactionSupport.getTransactionId();
        List<String> nodePaths = nodeInfo.getPaths();
        List<List<String>> pathNodeIds = nodeInfo.getParentNodeIds();
        long timestamp = System.currentTimeMillis();
        Long modificationTime = nodeInfo.getModificationTimestamp();
        long size;
        String mimeType;
        String encoding;
        if (value != null)
        {
            size = value.getSize();
            mimeType = value.getMimetype();
            encoding = value.getEncoding();
        }
        else
        {
            size = 0;
            mimeType = "";
            encoding = "";
        }

        String nodeType = nodeInfo.getType().toPrefixString(namespaceService);
        Client alfrescoClient = getAlfrescoClient(nodeInfo.getClient());

        Set<String> aspects = nodeInfo.getAspectsAsStrings();
        Map<String, Serializable> properties = nodeInfo.getProperties();

        Event event = new NodeContentPutEvent(nextSequenceNumber(), name, txnId, timestamp, networkId, siteId, objectId,
                nodeType, nodePaths, pathNodeIds, username, modificationTime, size, mimeType, encoding, alfrescoClient, aspects, properties);
        sendEvent(event);
    }
}
 
Example 17
Source File: UpdateThumbnailActionExecuter.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.action.Action, org.alfresco.service.cmr.repository.NodeRef)
 */
@Override
protected void executeImpl(Action action, NodeRef actionedUponNodeRef)
{
    // Check if thumbnailing is generally disabled
    if (!thumbnailService.getThumbnailsEnabled())
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Thumbnail transformations are not enabled");
        }
        return;
    }
    
    // Get the thumbnail
    NodeRef thumbnailNodeRef = (NodeRef)action.getParameterValue(PARAM_THUMBNAIL_NODE);
    if (thumbnailNodeRef == null)
    {
        thumbnailNodeRef = actionedUponNodeRef;
    }
    
    if (this.nodeService.exists(thumbnailNodeRef) == true &&
            renditionService.isRendition(thumbnailNodeRef))
    {            
        // Get the thumbnail Name
        ChildAssociationRef parent = renditionService.getSourceNode(thumbnailNodeRef);
        String thumbnailName = parent.getQName().getLocalName();
        
        // Get the details of the thumbnail
        ThumbnailRegistry registry = this.thumbnailService.getThumbnailRegistry();
        ThumbnailDefinition details = registry.getThumbnailDefinition(thumbnailName);
        if (details == null)
        {
            throw new AlfrescoRuntimeException("The thumbnail name '" + thumbnailName + "' is not registered");
        }
        
        // Get the content property
        QName contentProperty = (QName)action.getParameterValue(PARAM_CONTENT_PROPERTY);
        if (contentProperty == null)
        {
            contentProperty = ContentModel.PROP_CONTENT;
        }
        
        Serializable contentProp = nodeService.getProperty(actionedUponNodeRef, contentProperty);
        if (contentProp == null)
        {
            logger.info("Creation of thumbnail, null content for " + details.getName());
            return;
        }

        if(contentProp instanceof ContentData)
        {
            ContentData content = (ContentData)contentProp;
            String mimetype = content.getMimetype();
            if (mimetypeMaxSourceSizeKBytes != null)
            {
                Long maxSourceSizeKBytes = mimetypeMaxSourceSizeKBytes.get(mimetype);
                if (maxSourceSizeKBytes != null && maxSourceSizeKBytes >= 0 && maxSourceSizeKBytes < (content.getSize()/1024L))
                {
                    logger.debug("Unable to create thumbnail '" + details.getName() + "' for " +
                            mimetype + " as content is too large ("+(content.getSize()/1024L)+"K > "+maxSourceSizeKBytes+"K)");
                    return; //avoid transform
                }
            }
        }
        // Create the thumbnail
        this.thumbnailService.updateThumbnail(thumbnailNodeRef, details.getTransformationOptions());
    }
}
 
Example 18
Source File: NodesImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public BinaryResource getContent(NodeRef nodeRef, Parameters parameters, boolean recordActivity)
{
    if (!nodeMatches(nodeRef, Collections.singleton(ContentModel.TYPE_CONTENT), null, false))
    {
        throw new InvalidArgumentException("NodeId of content is expected: " + nodeRef.getId());
    }

    Map<QName, Serializable> nodeProps = nodeService.getProperties(nodeRef);
    ContentData cd = (ContentData) nodeProps.get(ContentModel.PROP_CONTENT);
    String name = (String) nodeProps.get(ContentModel.PROP_NAME);

    org.alfresco.rest.framework.resource.content.ContentInfo ci = null;
    String mimeType = null;
    if (cd != null)
    {
        mimeType = cd.getMimetype();
        ci = new org.alfresco.rest.framework.resource.content.ContentInfoImpl(mimeType, cd.getEncoding(), cd.getSize(), cd.getLocale());
    }

    // By default set attachment header (with filename) unless attachment=false *and* content type is pre-configured as non-attach
    boolean attach = true;
    String attachment = parameters.getParameter("attachment");
    if (attachment != null)
    {
        Boolean a = Boolean.valueOf(attachment);
        if (!a)
        {
            if (nonAttachContentTypes.contains(mimeType))
            {
                attach = false;
            }
            else
            {
                logger.warn("Ignored attachment=false for "+nodeRef.getId()+" since "+mimeType+" is not in the whitelist for non-attach content types");
            }
        }
    }
    String attachFileName = (attach ? name : null);

    if (recordActivity)
    {
        final ActivityInfo activityInfo = getActivityInfo(getParentNodeRef(nodeRef), nodeRef);
        postActivity(Activity_Type.DOWNLOADED, activityInfo, true);
    }

    return new NodeBinaryResource(nodeRef, ContentModel.PROP_CONTENT, ci, attachFileName);
}
 
Example 19
Source File: ContentDiskDriver.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Clone node
 * 
 * @param newName the new name of the node
 * @param fromNode the node to copy from
 * @param toNode the node to copy to
 * @param ctx
 */
private void cloneNode(String newName, NodeRef fromNode, NodeRef toNode, ContentContext ctx) 
{
    if(logger.isDebugEnabled())
    {
        logger.debug("clone node from fromNode:" + fromNode + "toNode:" + toNode);
    }
    cloneNodeAspects(newName, fromNode, toNode, ctx);

    // copy over the node creator and owner properties
    // need to disable the auditable aspect first to prevent default audit behaviour
    policyBehaviourFilter.disableBehaviour(ContentModel.ASPECT_AUDITABLE);
    try
    {
    	nodeService.setProperty(toNode, ContentModel.PROP_CREATOR, nodeService.getProperty(fromNode, ContentModel.PROP_CREATOR));
    	ownableService.setOwner(toNode, ownableService.getOwner(fromNode));
    }
    finally
    {
        policyBehaviourFilter.enableBehaviour(ContentModel.ASPECT_AUDITABLE);
    }
    
    Set<AccessPermission> permissions = permissionService.getAllSetPermissions(fromNode);
    boolean inheritParentPermissions = permissionService.getInheritParentPermissions(fromNode);
    permissionService.deletePermissions(fromNode);
    
    permissionService.setInheritParentPermissions(toNode, inheritParentPermissions);        
    for(AccessPermission permission : permissions)
    {
        permissionService.setPermission(toNode, permission.getAuthority(), permission.getPermission(), (permission.getAccessStatus() == AccessStatus.ALLOWED));
    }
    
    // Need to take a new guess at the mimetype based upon the new file name.
    ContentData content = (ContentData)nodeService.getProperty(toNode, ContentModel.PROP_CONTENT);
        
    // Take a guess at the mimetype (if it has not been set by something already)
    if (content != null && (content.getMimetype() == null || content.getMimetype().equals(MimetypeMap.MIMETYPE_BINARY)))
    {
        String mimetype = mimetypeService.guessMimetype(newName);
        if(logger.isDebugEnabled())
        {
            logger.debug("set new mimetype to:" + mimetype);
        }
        ContentData replacement = ContentData.setMimetype(content, mimetype);
        nodeService.setProperty(toNode, ContentModel.PROP_CONTENT, replacement);
    }

    // Extract metadata pending change for ALF-5082
    Action action = getActionService().createAction(ContentMetadataExtracter.EXECUTOR_NAME);
    if(action != null)
    {
        getActionService().executeAction(action, toNode);
    }
}
 
Example 20
Source File: RenditionsImpl.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
private BinaryResource getContentImpl(NodeRef nodeRef, String renditionId, Parameters parameters)
{
    NodeRef renditionNodeRef = getRenditionByName(nodeRef, renditionId, parameters);

    // By default set attachment header (with rendition Id) unless attachment=false
    boolean attach = true;
    String attachment = parameters.getParameter(PARAM_ATTACHMENT);
    if (attachment != null)
    {
        attach = Boolean.valueOf(attachment);
    }
    final String attachFileName = (attach ? renditionId : null);

    if (renditionNodeRef == null)
    {
        boolean isPlaceholder = Boolean.valueOf(parameters.getParameter(PARAM_PLACEHOLDER));
        if (!isPlaceholder)
        {
            throw new NotFoundException("Thumbnail was not found for [" + renditionId + ']');
        }
        String sourceNodeMimeType = null;
        try
        {
            sourceNodeMimeType = (nodeRef != null ? getMimeType(nodeRef) : null);
        }
        catch (InvalidArgumentException e)
        {
            // No content for node, e.g. ASSOC_AVATAR rather than ASSOC_PREFERENCE_IMAGE
        }
        // resource based on the content's mimeType and rendition id
        String phPath = scriptThumbnailService.getMimeAwarePlaceHolderResourcePath(renditionId, sourceNodeMimeType);
        if (phPath == null)
        {
            // 404 since no thumbnail was found
            throw new NotFoundException("Thumbnail was not found and no placeholder resource available for [" + renditionId + ']');
        }
        else
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("Retrieving content from resource path [" + phPath + ']');
            }
            // get extension of resource
            String ext = "";
            int extIndex = phPath.lastIndexOf('.');
            if (extIndex != -1)
            {
                ext = phPath.substring(extIndex);
            }

            try
            {
                final String resourcePath = "classpath:" + phPath;
                InputStream inputStream = resourceLoader.getResource(resourcePath).getInputStream();
                // create temporary file
                File file = TempFileProvider.createTempFile(inputStream, "RenditionsApi-", ext);
                return new FileBinaryResource(file, attachFileName);
            }
            catch (Exception ex)
            {
                if (logger.isErrorEnabled())
                {
                    logger.error("Couldn't load the placeholder." + ex.getMessage());
                }
                throw new ApiException("Couldn't load the placeholder.");
            }
        }
    }

    Map<QName, Serializable> nodeProps = nodeService.getProperties(renditionNodeRef);
    ContentData contentData = (ContentData) nodeProps.get(ContentModel.PROP_CONTENT);
    Date modified = (Date) nodeProps.get(ContentModel.PROP_MODIFIED);

    org.alfresco.rest.framework.resource.content.ContentInfo contentInfo = null;
    if (contentData != null)
    {
        contentInfo = new ContentInfoImpl(contentData.getMimetype(), contentData.getEncoding(), contentData.getSize(), contentData.getLocale());
    }
    // add cache settings
    CacheDirective cacheDirective = new CacheDirective.Builder()
            .setNeverCache(false)
            .setMustRevalidate(false)
            .setLastModified(modified)
            .setETag(modified != null ? Long.toString(modified.getTime()) : null)
            .setMaxAge(Long.valueOf(31536000))// one year (in seconds)
            .build();

    return new NodeBinaryResource(renditionNodeRef, ContentModel.PROP_CONTENT, contentInfo, attachFileName, cacheDirective);
}