Java Code Examples for org.alfresco.service.cmr.repository.ContentData

The following are top voted examples for showing how to use org.alfresco.service.cmr.repository.ContentData. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: alfresco-repository   File: ZipDownloadExporter.java   View source code 6 votes vote down vote up
@Override
public void contentImpl(NodeRef nodeRef, QName property, InputStream content, ContentData contentData, int index)
{
    // if the content stream to output is empty, then just return content descriptor as is
    if (content == null)
    {
        return;
    }
    
    try
    {
        // ALF-2016
        ZipArchiveEntry zipEntry=new ZipArchiveEntry(getPath());
        zipStream.putArchiveEntry(zipEntry);
        
        // copy export stream to zip
        copyStream(zipStream, content);
        
        zipStream.closeArchiveEntry();
        filesAddedCount = filesAddedCount + 1;
    }
    catch (IOException e)
    {
        throw new ExporterException("Failed to zip export stream", e);
    }
}
 
Example 2
Project: alfresco-repository   File: ContentChunkerImpl.java   View source code 6 votes vote down vote up
/**
 * 
 */
public void addContent(ContentData data) throws TransferException
{
    logger.debug("add content size:" + data.getSize());
    buffer.add(data);
    
    /**
     * work out whether the buffer has filled up and needs to be flushed
     */
    Iterator<ContentData> iter = buffer.iterator();      
    long totalContentSize = 0;
    
    while (iter.hasNext())
    {
        ContentData x = (ContentData)iter.next();
        totalContentSize += x.getSize();
    }
    if(logger.isDebugEnabled())
    {
        logger.debug("elements " + buffer.size() + ", totalContentSize:" + totalContentSize);
    }
    if(totalContentSize >= chunkSize)
    {
        flush();
    }
}
 
Example 3
Project: alfresco-remote-api   File: Document.java   View source code 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 4
Project: alfresco-repository   File: ContentDataDAOTest.java   View source code 6 votes vote down vote up
/**
 * Ensure that upper and lowercase URLs don't clash
 * @throws Exception
 */
public void testEnsureCaseSensitiveStorage() throws Exception
{
    ContentData contentData = getContentData();
    String contentUrlUpper = contentData.getContentUrl().toUpperCase();
    ContentData contentDataUpper = new ContentData(
            contentUrlUpper, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, "UTF-8", new Locale("FR"));
    String contentUrlLower = contentData.getContentUrl().toLowerCase();
    ContentData contentDataLower = new ContentData(
            contentUrlLower, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, "utf-8", new Locale("fr"));
    
    Pair<Long, ContentData> resultPairUpper = create(contentDataUpper);
    getAndCheck(resultPairUpper.getFirst(), contentDataUpper);
    
    Pair<Long, ContentData> resultPairLower = create(contentDataLower);
    getAndCheck(resultPairLower.getFirst(), contentDataLower);
}
 
Example 5
Project: alfresco-repository   File: ActionServiceImplTest.java   View source code 6 votes vote down vote up
@Override
protected void onSetUpInTransaction() throws Exception
{
    super.onSetUpInTransaction();

    this.transactionHelper = (RetryingTransactionHelper)this.applicationContext.getBean("retryingTransactionHelper");

    // Create the node used for tests
    this.nodeRef = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}testnode"),
            ContentModel.TYPE_CONTENT).getChildRef();
    this.nodeService.setProperty(
            this.nodeRef,
            ContentModel.PROP_CONTENT,
            new ContentData(null, MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, null));
    this.folder = this.nodeService.createNode(
            this.rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName("{test}testFolder"),
            ContentModel.TYPE_FOLDER).getChildRef();
    
    // Register the test executor, if needed
    SleepActionExecuter.registerIfNeeded(applicationContext);
}
 
Example 6
Project: alfresco-repository   File: ContentStoreCleanerScalabilityRunner.java   View source code 6 votes vote down vote up
/**
 * Creates a node with two properties
 */
public void makeNode(ContentData contentData)
{
    StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, "SpacesStore");
    Long rootNodeId = nodeDAO.newStore(storeRef).getFirst();
    ChildAssocEntity assoc = nodeDAO.newNode(
            rootNodeId,
            ContentModel.ASSOC_CHILDREN,
            ContentModel.ASSOC_CHILDREN,
            storeRef,
            null,
            ContentModel.TYPE_CONTENT,
            I18NUtil.getLocale(),
            null,
            null);
    Long nodeId = assoc.getChildNode().getId();
    nodeDAO.addNodeProperty(nodeId, contentQName, contentData);
}
 
Example 7
Project: alfresco-repository   File: OnPropertyUpdateRuleTrigger.java   View source code 6 votes vote down vote up
/**
 * ALF-17483: It's possible that even for a single-valued contentdata property, its definition may have been changed
 * and the previous persisted value is multi-valued, so let's be careful about converting to ContentData.
 * 
 * @param object
 *            property value to convert
 * @return a ContentData if one can be extracted
 */
private static ContentData toContentData(Object object)
{
    if (object == null)
    {
        return null;
    }
    if (object instanceof ContentData)
    {
        return (ContentData) object;
    }
    if (object instanceof Collection<?> && !((Collection<?>) object).isEmpty())
    {
        return toContentData(((Collection<?>) object).iterator().next());
    }
    return null;
}
 
Example 8
Project: alfresco-repository   File: ScriptNode.java   View source code 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 9
Project: alfresco-remote-api   File: RenditionsImpl.java   View source code 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 10
Project: alfresco-repository   File: ContentDataDAOTest.java   View source code 6 votes vote down vote up
public void testDelete() throws Exception
{
    ContentData contentData = getContentData();
    
    Pair<Long, ContentData> resultPair = create(contentData);
    getAndCheck(resultPair.getFirst(), contentData);
    delete(resultPair.getFirst());
    try
    {
        getAndCheck(resultPair.getFirst(), contentData);
        fail("Entity still exists");
    }
    catch (Throwable e)
    {
        // Expected
    }
}
 
Example 11
Project: alfresco-repository   File: AbstractContentDataDAOImpl.java   View source code 6 votes vote down vote up
@Override
public void updateContentData(Long id, ContentData contentData)
{
    if (id == null)
    {
        throw new IllegalArgumentException("Cannot look up ContentData by null ID.");
    }
    if (contentData == null)
    {
        throw new IllegalArgumentException("Cannot update ContentData with a null.");
    }
    contentData = sanitizeMimetype(contentData);
    int updated = contentDataCache.updateValue(id, contentData);
    if (updated < 1)
    {
        throw new ConcurrencyFailureException("ContentData with ID " + id + " not updated");
    }
}
 
Example 12
Project: alfresco-repository   File: ContentDataDAOImpl.java   View source code 6 votes vote down vote up
@Override
protected int deleteContentDataEntity(Long id)
{
    // Get the content urls
    try
    {
        ContentData contentData = getContentData(id).getSecond();
        String contentUrl = contentData.getContentUrl();
        if (contentUrl != null)
        {
            // It has been dereferenced and may be orphaned - we'll check later
            registerDereferencedContentUrl(contentUrl);
        }
    }
    catch (DataIntegrityViolationException e)
    {
        // Doesn't exist.  The node doesn't enforce a FK constraint, so we protect against this.
    }
    // Issue the delete statement
    Map<String, Object> params = new HashMap<String, Object>(11);
    params.put("id", id);
    return template.delete(DELETE_CONTENT_DATA, params);
}
 
Example 13
Project: alfresco-repository   File: NodePropertyValue.java   View source code 6 votes vote down vote up
@Override
Serializable convert(Serializable value)
{
    if (value instanceof Long)
    {
        return value;
    }
    else if (value instanceof String)
    {
        logger.warn("Content URL converter has not run to completion: " + value);
        return DefaultTypeConverter.INSTANCE.convert(ContentData.class, value);
    }
    else
    {
        return DefaultTypeConverter.INSTANCE.convert(ContentData.class, value);
    }
}
 
Example 14
Project: alfresco-repository   File: NodePropertyValue.java   View source code 6 votes vote down vote up
@Override
Serializable convert(Serializable value)
{
    if (value == null)
    {
        return null;
    }
    else if (value instanceof Long)
    {
        return value;
    }
    else if (value instanceof ContentDataId)
    {
        return ((ContentDataId)value).getId();
    }
    else
    {
        return DefaultTypeConverter.INSTANCE.convert(ContentData.class, value);
    }
}
 
Example 15
Project: alfresco-repository   File: AbstractProperty.java   View source code 6 votes vote down vote up
protected ContentData getContentData(CMISNodeInfo nodeInfo)
{
    if (!nodeInfo.isDocument())
    {
        return null;
    }

    if (nodeInfo.containsPropertyValue(CONTENT_PROPERTY))
    {
        return (ContentData) nodeInfo.getPropertyValue(CONTENT_PROPERTY);
    } else
    {
        ContentData contentData = null;

        Serializable value = nodeInfo.getNodeProps().get(ContentModel.PROP_CONTENT);

        if (value != null)
        {
            contentData = DefaultTypeConverter.INSTANCE.convert(ContentData.class, value);
        }

        nodeInfo.putPropertyValue(CONTENT_PROPERTY, contentData);
        return contentData;
    }
}
 
Example 16
Project: alfresco-repository   File: ThumbnailServiceImplTest.java   View source code 6 votes vote down vote up
private NodeRef createCorruptedContent(NodeRef parentFolder) throws IOException
{
    // The below pdf file has been truncated such that it is identifiable as a PDF but otherwise corrupt.
    File corruptPdfFile = AbstractContentTransformerTest.loadNamedQuickTestFile("quickCorrupt.pdf");
    assertNotNull("Failed to load required test file.", corruptPdfFile);

    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_NAME, "corrupt.pdf");
    NodeRef node = this.secureNodeService.createNode(parentFolder, ContentModel.ASSOC_CONTAINS,
            QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "quickCorrupt.pdf"),
            ContentModel.TYPE_CONTENT, props).getChildRef();

    secureNodeService.setProperty(node, ContentModel.PROP_CONTENT, new ContentData(null,
                MimetypeMap.MIMETYPE_PDF, 0L, null));
    ContentWriter writer = contentService.getWriter(node, ContentModel.PROP_CONTENT, true);
    writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
    writer.setEncoding("UTF-8");
    writer.putContent(corruptPdfFile);
    
    return node;
}
 
Example 17
Project: alfresco-repository   File: BaseNodeServiceTest.java   View source code 6 votes vote down vote up
/**
 * Ensures that the type you get out of a <b>d:any</b> property is the type that you put in.
 */
public void testSerializableProperties() throws Exception
{
    ContentData contentData = new ContentData(null, null, 0L, null);
    QName qname = PROP_QNAME_CONTENT_VALUE;
    
    Map<QName, Serializable> properties = new HashMap<QName, Serializable>(17);
    properties.put(PROP_QNAME_CONTENT_VALUE, contentData);
    properties.put(PROP_QNAME_SERIALIZABLE_VALUE, qname);
    // create node
    NodeRef nodeRef = nodeService.createNode(
            rootNodeRef,
            ASSOC_TYPE_QNAME_TEST_CHILDREN,
            QName.createQName("pathA"),
            ContentModel.TYPE_CONTAINER,
            properties).getChildRef();
    // persist
    flushAndClear();
    
    // get the properties back
    Map<QName, Serializable> checkProperties = nodeService.getProperties(nodeRef);
    Serializable checkPropertyContentData = checkProperties.get(PROP_QNAME_CONTENT_VALUE);
    Serializable checkPropertyQname = checkProperties.get(PROP_QNAME_SERIALIZABLE_VALUE);
    assertTrue("Serialization/deserialization of ContentData failed", checkPropertyContentData instanceof ContentData);
    assertTrue("Serialization/deserialization failed", checkPropertyQname instanceof QName);
}
 
Example 18
Project: alfresco-repository   File: UnitTestInProcessTransmitterImpl.java   View source code 6 votes vote down vote up
public void sendContent(final Transfer transfer, final Set<ContentData> data)
{
    transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            String transferId = transfer.getTransferId();
    
            for(ContentData content : data)
            {
                String contentUrl = content.getContentUrl();
                String fileName = TransferCommons.URLToPartName(contentUrl);

                InputStream contentStream = getContentService().getRawReader(contentUrl).getContentInputStream();
                receiver.saveContent(transferId, fileName, contentStream);
            }
            return null;
        }
    }, false, true);
}
 
Example 19
Project: alfresco-repository   File: ContentDataDAOTest.java   View source code 6 votes vote down vote up
@Category(PerformanceTests.class)
public void testCreateSpeedSingleTxn()
{
    RetryingTransactionCallback<List<Pair<Long, ContentData>>> writeCallback = new RetryingTransactionCallback<List<Pair<Long, ContentData>>>()
    {
        public List<Pair<Long, ContentData>> execute() throws Throwable
        {
            return speedTestWrite(getName(), 10000);
        }
    };
    final List<Pair<Long, ContentData>> pairs = txnHelper.doInTransaction(writeCallback, false, false);
    RetryingTransactionCallback<Void> readCallback = new RetryingTransactionCallback<Void>()
    {
        public Void execute() throws Throwable
        {
            speedTestRead(getName(), pairs);
            return null;
        }
    };
    txnHelper.doInTransaction(readCallback, false, false);
}
 
Example 20
Project: alfresco-repository   File: RenditionServiceIntegrationTest.java   View source code 6 votes vote down vote up
private NodeRef createFreeMarkerNode(NodeRef companyHome)
{
    NodeRef fmNode = createContentNode(companyHome, "testFreeMarkerNode");
    nodeService.setProperty(fmNode, ContentModel.PROP_CONTENT, new ContentData(null,
                MimetypeMap.MIMETYPE_TEXT_PLAIN, 0L, null));

    URL url = getClass().getResource(FM_TEMPLATE);
    assertNotNull("The url is null", url);
    File templateFile = new File(url.getFile());
    assertTrue("The template file does not exist", templateFile.exists());

    ContentWriter fmWriter = contentService.getWriter(fmNode, ContentModel.PROP_CONTENT, true);
    fmWriter.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    fmWriter.setEncoding("UTF-8");
    fmWriter.putContent(templateFile);
    return fmNode;
}
 
Example 21
Project: alfresco-repository   File: ContentDataTest.java   View source code 6 votes vote down vote up
public void testEquals()
{
    ContentData contentData1 = new ContentData("abc://xxx", MimetypeMap.MIMETYPE_BINARY, 600L, "UTF-8", Locale.ENGLISH);
    ContentData contentData2 = new ContentData("abc://xxx", MimetypeMap.MIMETYPE_BINARY, 600L, "UTF-8", Locale.ENGLISH);
    ContentData contentData3 = new ContentData("abc://XXX", MimetypeMap.MIMETYPE_BINARY, 600L, "UTF-8", Locale.ENGLISH);
    ContentData contentData4 = new ContentData("abc://xxx", MimetypeMap.MIMETYPE_TEXT_PLAIN, 600L, "UTF-8", Locale.ENGLISH);
    ContentData contentData5 = new ContentData("abc://xxx", MimetypeMap.MIMETYPE_BINARY, 500L, "UTF-8", Locale.ENGLISH);
    ContentData contentData6 = new ContentData("abc://xxx", MimetypeMap.MIMETYPE_BINARY, 600L, "UTF-16", Locale.ENGLISH);
    ContentData contentData7 = new ContentData("abc://xxx", MimetypeMap.MIMETYPE_BINARY, 600L, "UTF-8", Locale.CHINESE);
    assertEquals(contentData1, contentData2);
    assertNotSame(contentData1, contentData3);
    assertNotSame(contentData1, contentData4);
    assertNotSame(contentData1, contentData5);
    assertNotSame(contentData1, contentData6);
    assertNotSame(contentData1, contentData7);
}
 
Example 22
Project: alfresco-repository   File: RoutingContentServiceTest.java   View source code 5 votes vote down vote up
@Override
public void setUp() throws Exception
{
    ctx = ApplicationContextHelper.getApplicationContext();
    transactionService = (TransactionService) ctx.getBean("TransactionService");
    nodeService = (NodeService) ctx.getBean("NodeService");
    contentService = (ContentService) ctx.getBean(ServiceRegistry.CONTENT_SERVICE.getLocalName());
    this.policyComponent = (PolicyComponent) ctx.getBean("policyComponent");
    this.authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    
    // authenticate
    this.authenticationComponent.setSystemUserAsCurrentUser();
    
    // start the transaction
    txn = getUserTransaction();
    txn.begin();
    
    // create a store and get the root node
    StoreRef storeRef = new StoreRef(StoreRef.PROTOCOL_WORKSPACE, getName());
    if (!nodeService.exists(storeRef))
    {
        storeRef = nodeService.createStore(storeRef.getProtocol(), storeRef.getIdentifier());
    }
    rootNodeRef = nodeService.getRootNode(storeRef);
    // create a content node
    ContentData contentData = new ContentData(null, "text/plain", 0L, "UTF-16", Locale.CHINESE);
    
    PropertyMap properties = new PropertyMap();
    properties.put(ContentModel.PROP_CONTENT, contentData);
    
    ChildAssociationRef assocRef = nodeService.createNode(
            rootNodeRef,
            ContentModel.ASSOC_CHILDREN,
            QName.createQName(TEST_NAMESPACE, GUID.generate()),
            ContentModel.TYPE_CONTENT,
            properties);
    contentNodeRef = assocRef.getChildRef();
}
 
Example 23
Project: alfresco-repository   File: ThumbnailServiceImpl.java   View source code 5 votes vote down vote up
/**
 * Determine whether the thumbnail meta-data matches the given mimetype and options
 * 
 * If mimetype and transformation options are null then match is guarenteed
 * 
 * @param  thumbnail     thumbnail node reference
 * @param  mimetype      mimetype
 * @param  options       transformation options
 * @return boolean       true if the mimetype and options match the thumbnail metadata, false otherwise
 */
private boolean matchMimetypeOptions(NodeRef thumbnail, String mimetype, TransformationOptions options)
{
    boolean result = true;
    
    if (mimetype != null)
    {
        // Check the mimetype
        String thumbnailMimetype = ((ContentData) this.nodeService.getProperty(thumbnail, ContentModel.PROP_CONTENT)).getMimetype();

        if (mimetype.endsWith(SUBTYPES_POSTFIX))
        {
            String baseMimetype = mimetype.substring(0, mimetype.length() - SUBTYPES_POSTFIX.length());
            if (thumbnailMimetype == null || thumbnailMimetype.startsWith(baseMimetype) == false)
            {
                result = false;
            }
        }
        else
        {
            if (mimetype.equals(thumbnailMimetype) == false)
            {
                result = false;
            }
        }
    }
    
    if (result != false && options != null)
    {
        // TODO .. check for matching options here ...
    }
    
    return result;
}
 
Example 24
Project: alfresco-file-transfer-receiver   File: FileTransferReceiverTest.java   View source code 5 votes vote down vote up
/**
 * @return TransferManifestNormalNode
 */
private TransferManifestNormalNode createContentNode(NodeRef parentFolder, String nodeName) throws Exception
{
    TransferManifestNormalNode node = new TransferManifestNormalNode();
    String uuid = GUID.generate();
    NodeRef nodeRef = new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, uuid);
    node.setNodeRef(nodeRef);
    node.setUuid(uuid);
    byte[] dummyContent = "This is some dummy content.".getBytes("UTF-8");

    node.setType(ContentModel.TYPE_CONTENT);
    node.setAncestorType(ContentModel.TYPE_CONTENT);

    /**
     * Get guest home
     */

    List<ChildAssociationRef> parents = new ArrayList<ChildAssociationRef>();
    ChildAssociationRef primaryAssoc = new ChildAssociationRef(ContentModel.ASSOC_CONTAINS, parentFolder, QName
            .createQName(NamespaceService.CONTENT_MODEL_1_0_URI, nodeName), node.getNodeRef(), true, -1);
    parents.add(primaryAssoc);
    node.setParentAssocs(parents);
    node.setParentPath(null);
    node.setPrimaryParentAssoc(primaryAssoc);

    Map<QName, Serializable> props = new HashMap<QName, Serializable>();
    props.put(ContentModel.PROP_NODE_UUID, uuid);
    props.put(ContentModel.PROP_NAME, nodeName);
    ContentData contentData = new ContentData("/" + uuid, "text/plain", dummyContent.length, "UTF-8");
    props.put(ContentModel.PROP_CONTENT, contentData);
    node.setProperties(props);

    return node;
}
 
Example 25
Project: alfresco-repository   File: NodeFormProcessor.java   View source code 5 votes vote down vote up
@Override
protected Map<String, Object> getTransientValues(NodeRef item)
{
    Map<String, Object> values = new HashMap<String, Object>(3);
    ContentData contentData = getContentData(item);
    if (contentData != null)
    {
        values.put(EncodingFieldProcessor.KEY, contentData.getEncoding());
        values.put(MimetypeFieldProcessor.KEY, contentData.getMimetype());
        values.put(SizeFieldProcessor.KEY, contentData.getSize());
    }
    return values;
}
 
Example 26
Project: alfresco-repository   File: NodeContentData.java   View source code 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 27
Project: alfresco-repository   File: TransferEventProcessor.java   View source code 5 votes vote down vote up
/**
 * 
 * @param data ContentData
 * @param range long
 * @param position long
 */
public void sendContent(ContentData data, long range, long position)
{
    setState(TransferEvent.TransferState.SENDING_CONTENT);
    
    TransferEventSendingContent event = new TransferEventSendingContent();
    event.setTransferState(TransferEvent.TransferState.SENDING_CONTENT);
    event.setRange(range);
    event.setPosition(position);
    event.setSize(data.getSize());
    event.setMessage("sending content " + position + " of " + range + ", size: " + event.getSize());
    queue.add(event);
    notifyObservers();
}
 
Example 28
Project: alfresco-repository   File: TransferManifestNodeHelper.java   View source code 5 votes vote down vote up
/**
 * Gets the content properties for a node
 * @param node the node to process
 */
public static Set<ContentData> getContentData(TransferManifestNormalNode node)
{
    Set<ContentData> content = new HashSet<ContentData>();
    
    for(Serializable value : node.getProperties().values())
    {
        if(value instanceof ContentData)
        {
            content.add((ContentData)value);
        }
    }
    
    return content;
}
 
Example 29
Project: alfresco-repository   File: ContentDataDAOTest.java   View source code 5 votes vote down vote up
public void testContentUrl_FetchingOrphansWithLimit() throws Exception
{
    // Orphan some content
    for (int i = 0; i < 5; i++)
    {
        ContentData contentData = getContentData();
        Pair<Long, ContentData> resultPair = create(contentData);
        getAndCheck(resultPair.getFirst(), contentData);
        delete(resultPair.getFirst());
    }
    final int[] count = new int[] {0}; 
    
    // Iterate over all orphaned content URLs and ensure that we hit the one we just orphaned
    ContentUrlHandler handler = new ContentUrlHandler()
    {
        public void handle(Long id, String contentUrl, Long orphanTime)
        {
            // Check
            if (id == null || contentUrl == null || orphanTime == null)
            {
                fail("Invalid orphan data returned to handler: " + id + "-" + contentUrl + "-" + orphanTime);
            }
            count[0]++;
        }
    };
    contentDataDAO.getContentUrlsOrphaned(handler, Long.MAX_VALUE, 5);
    assertEquals("Expected exactly 5 results callbacks", 5, count[0]);
}
 
Example 30
Project: alfresco-repository   File: ContentDataPart.java   View source code 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 31
Project: alfresco-repository   File: RepoPrimaryManifestProcessorImpl.java   View source code 5 votes vote down vote up
/**
 * @param nodeToUpdate NodeRef
 * @param contentProps Map<QName, Serializable>
 * @return true if any content property has been updated for the needToUpdate node
 */
private boolean writeContent(NodeRef nodeToUpdate, Map<QName, Serializable> contentProps)
{
    boolean contentUpdated = false;
    File stagingDir = getStagingFolder();
    for (Map.Entry<QName, Serializable> contentEntry : contentProps.entrySet())
    {
        ContentData contentData = (ContentData) contentEntry.getValue();
        String contentUrl = contentData.getContentUrl();
        if(contentUrl == null || contentUrl.isEmpty())
        {
            log.debug("content data is null or empty:" + nodeToUpdate);
            ContentData cd = new ContentData(null, null, 0, null);
            nodeService.setProperty(nodeToUpdate, contentEntry.getKey(), cd);
            contentUpdated = true;
        }
        else
        {
            String fileName = TransferCommons.URLToPartName(contentUrl);
            File stagedFile = new File(stagingDir, fileName);
            if (!stagedFile.exists())
            {
                error(MSG_REFERENCED_CONTENT_FILE_MISSING);
            }
            ContentWriter writer = contentService.getWriter(nodeToUpdate, contentEntry.getKey(), true);
            writer.setEncoding(contentData.getEncoding());
            writer.setMimetype(contentData.getMimetype());
            writer.setLocale(contentData.getLocale());
            writer.putContent(stagedFile);
            contentUpdated = true;
        }
    }
    return contentUpdated;
}
 
Example 32
Project: alfresco-repository   File: RepoPrimaryManifestProcessorImpl.java   View source code 5 votes vote down vote up
/**
 * inject transferred
 */
private void injectTransferred(Map<QName, Serializable> props)
{       
    if(!props.containsKey(TransferModel.PROP_REPOSITORY_ID))
    {
        log.debug("injecting repositoryId property");
        props.put(TransferModel.PROP_REPOSITORY_ID, header.getRepositoryId());
    }
    props.put(TransferModel.PROP_FROM_REPOSITORY_ID, header.getRepositoryId());
    
    /**
     * For each property
     */
    List<String> contentProps = new ArrayList<String>();
    for (Serializable value : props.values())
    {
        if ((value != null) && ContentData.class.isAssignableFrom(value.getClass()))
        {
            ContentData srcContent = (ContentData)value;

            if(srcContent.getContentUrl() != null && !srcContent.getContentUrl().isEmpty())
            {
                log.debug("adding part name to from content field");
                contentProps.add(TransferCommons.URLToPartName(srcContent.getContentUrl()));
            }  
        }
    }
    
    props.put(TransferModel.PROP_FROM_CONTENT, (Serializable)contentProps);
}
 
Example 33
Project: alfresco-repository   File: ImporterActionExecuterTest.java   View source code 5 votes vote down vote up
private void putContent(NodeRef zipFileNodeRef, String resource)
{
    URL url = AbstractContentTransformerTest.class.getClassLoader().getResource(resource);
    final File file = new File(url.getFile());
    
    contentService.getWriter(zipFileNodeRef, ContentModel.PROP_CONTENT, true).putContent(file);

    ContentData contentData = (ContentData) nodeService.getProperty(zipFileNodeRef, ContentModel.PROP_CONTENT);
    ContentData newContentData = ContentData.setMimetype(contentData, MimetypeMap.MIMETYPE_ZIP);

    nodeService.setProperty(zipFileNodeRef, ContentModel.PROP_CONTENT, newContentData);
}
 
Example 34
Project: alfresco-repository   File: ContentUsageImpl.java   View source code 5 votes vote down vote up
/**
 * Called before a node is deleted.
 * 
 * @param nodeRef   the node reference
 */
public void beforeDeleteNode(NodeRef nodeRef)
{
    if (stores.contains(tenantService.getBaseName(nodeRef.getStoreRef()).toString()) && (! alreadyDeleted(nodeRef)))
    {
        // TODO use data dictionary to get content property
        ContentData contentData = (ContentData) nodeService.getProperty(nodeRef, ContentModel.PROP_CONTENT);
        
        if (contentData != null)
        {
            long contentSize = contentData.getSize();
            
            // Get owner/creator
            String owner = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_ARCHIVED_ORIGINAL_OWNER); // allow for case where someone else is deleting the node
            if (owner == null || owner.equals(OwnableService.NO_OWNER))
            {
                owner = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_OWNER);
                if ((owner == null) || (owner.equals(OwnableService.NO_OWNER)))
                {
                    owner = (String) nodeService.getProperty(nodeRef, ContentModel.PROP_CREATOR);
                }
            }
            
            if (contentSize != 0 && owner != null)
            {
               // decrement usage if node is being deleted
               if (logger.isDebugEnabled()) logger.debug("beforeDeleteNode: nodeRef="+nodeRef+", owner="+owner+", contentSize="+contentSize);
               decrementUserUsage(owner, contentSize, nodeRef);
               recordDelete(nodeRef);
            }
        }
    }
}
 
Example 35
Project: alfresco-repository   File: BackingStoreAwareCacheWriter.java   View source code 5 votes vote down vote up
@Override
public ContentData getContentData()
{
    if (!this.cacheWriter.getReader().exists())
    {
        return this.bsWriter.getContentData();
    }
    return this.cacheWriter.getContentData();
}
 
Example 36
Project: alfresco-repository   File: ContentDataDAOTest.java   View source code 5 votes vote down vote up
private Pair<Long, ContentData> update(final Long id, final ContentData contentData)
{
    RetryingTransactionCallback<Pair<Long, ContentData>> callback = new RetryingTransactionCallback<Pair<Long, ContentData>>()
    {
        public Pair<Long, ContentData> execute() throws Throwable
        {
            contentDataDAO.updateContentData(id, contentData);
            return new Pair<Long, ContentData>(id, contentData);
        }
    };
    return txnHelper.doInTransaction(callback, false, false);
}
 
Example 37
Project: alfresco-repository   File: RoutingContentServiceTest.java   View source code 5 votes vote down vote up
/**
 * Checks what happens when the physical content disappears
 */
public void testMissingContent() throws Exception
{
    File tempFile = TempFileProvider.createTempFile(getName(), ".txt");
    
    ContentWriter writer = new FileContentWriter(tempFile);
    writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
    writer.setEncoding("UTF-8");
    writer.putContent("What about the others?  Buckwheats!");
    // check
    assertTrue("File does not exist", tempFile.exists());
    assertTrue("File not written to", tempFile.length() > 0);
    
    // update the node with this new info 
    ContentData contentData = writer.getContentData();
    nodeService.setProperty(contentNodeRef, ContentModel.PROP_CONTENT, contentData);
    
    // delete the content
    tempFile.delete();
    assertFalse("File not deleted", tempFile.exists());
    
    // now attempt to get the reader for the node
    ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertFalse("Reader should indicate that content is missing", reader.exists());
    
    // check the indexing doesn't spank everthing
    txn.commit();
    txn = null;

    // cleanup
    txn = getUserTransaction();
    txn.begin();
    nodeService.deleteNode(contentNodeRef);
    txn.commit();
    txn = null;
}
 
Example 38
Project: alfresco-repository   File: RoutingContentServiceTest.java   View source code 5 votes vote down vote up
public void testWriteToNodeWithoutAnyContentProperties() throws Exception
{
    // previously, the node was populated with the mimetype, etc
    // check that the write has these
    ContentWriter writer = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    assertEquals(MimetypeMap.MIMETYPE_TEXT_PLAIN, writer.getMimetype());
    assertEquals("UTF-16", writer.getEncoding());
    assertEquals(Locale.CHINESE, writer.getLocale());

    // now remove the content property from the node
    nodeService.setProperty(contentNodeRef, ContentModel.PROP_CONTENT, null);
    
    writer = contentService.getWriter(contentNodeRef, ContentModel.PROP_CONTENT, true);
    assertNull(writer.getMimetype());
    assertEquals("UTF-8", writer.getEncoding());
    assertEquals(Locale.getDefault(), writer.getLocale());
    
    // now set it on the writer
    writer.setMimetype("text/plain");
    writer.setEncoding("UTF-16");
    writer.setLocale(Locale.FRENCH);
    
    String content = "The quick brown fox ...";
    writer.putContent(content);
    
    // the properties should have found their way onto the node
    ContentData contentData = (ContentData) nodeService.getProperty(contentNodeRef, ContentModel.PROP_CONTENT);
    assertEquals("metadata didn't get onto node", writer.getContentData(), contentData);
    
    // check that the reader's metadata is set
    ContentReader reader = contentService.getReader(contentNodeRef, ContentModel.PROP_CONTENT);
    assertEquals("Metadata didn't get set on reader", writer.getContentData(), reader.getContentData());
}
 
Example 39
Project: alfresco-repository   File: ContentDataDAOTest.java   View source code 5 votes vote down vote up
/**
 * the caveat to {@link #testEnsureCaseSensitiveStorage()} is that mimetypes
 * must be normalized to lowercase.
 *
 * @throws Exception
 */
public void testEnsureCaseInsensitiveMimetypeStorage() throws Exception
{
    ContentData contentData = getContentData();
    ContentData cdWithUpperMimetype = ContentData.setMimetype(contentData, "TEXT/MYFORMAT");
    ContentData cdWithLowerMimetype = ContentData.setMimetype(contentData, "text/myformat");

    // In both instances, the created entry should have a lowercase mimetype
    Pair<Long, ContentData> result = create(cdWithUpperMimetype);
    // Ensure the ContentData's mimetype was stored in lowercase
    assertEquals("text/myformat", result.getSecond().getMimetype());

    result = create(cdWithLowerMimetype);
    assertEquals("text/myformat", result.getSecond().getMimetype());
}
 
Example 40
Project: alfresco-repository   File: ScriptNode.java   View source code 5 votes vote down vote up
/**
 * Constructor
 * 
 * @param contentData      The ContentData object this object wraps
 * @param property         The property the ContentData is attached too
 */
public ScriptContentData(ContentData contentData, QName property)
{
    this.contentData = contentData;
    this.property = property;
    this.isDirty = ContentData.hasContent(contentData);
}