Recipes by Category

App Distribution (2) Bundle logic, interface and services for distribution. App Logic (37) The Apex programming language, workflow and formulas for logic. Collaboration (6) The Salesforce Chatter collaboration platform. Database (29) Data persistence, reporting and analytics. Integration (33) Web Service APIs and toolkits for integration. Security (9) Platform, application and data security. Tools (4) Force.com tooling User Interface (36) Visualforce MVC and metadata-drive user interfaces. Web Sites (12) Public web sites and apps with optional user registration and login.
Beta Feedback
Cookbook Home » Publishing Documents Into a Salesforce CRM Content Personal Library

Publishing Documents Into a Salesforce CRM Content Personal Library

Post by Developer Force  (2010-07-16)

Status: Certified
Level: novice

Problem

You have a binary file on your computer that you want to store in Salesforce CRM Content so you can access it from anywhere you have an Internet connection. By storing it in Salesforce CRM Content, you can set a title and description, and view a preview of the file without having to download it.

Solution

Upload the file and publish it into a Salesforce CRM Content personal library. Though you can do this using the Salesforce.com user interface, this recipe steps through the same process using the Web services API.

Connect to Salesforce.com using the standard Web services API login code. The file you want to publish must be read into memory.

Create a ContentVersion record and set these fields. All of these fields are required:
  • Complete path of the document—PathOnClient
  • Binary file data—VersionData
  • Current user's ID (this indicates it's a personal library)—FirstPublishLocationId
package com.sforce;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;

import org.apache.axis.client.Stub;

import com.sforce.soap.enterprise.*;
import com.sforce.soap.enterprisedoc.Error;
import com.sforce.soap.enterprise.sobject.ContentVersion;
import com.sforce.soap.enterprise.sobject.SObject;

public class PublishIntoPersonalWorkspace {

    private static final int BYTES_16K = 1024 * 16;

    private static final int BYTES_4M = 4 * 1024 * 1024;

    private static final String TEST_FILE_PATH =
        "/home/jsmith/workspace/API Scratch/src/com/scratch/";

    /**
     * @param args
     */  
    
    public static void main(String[] args) {
        PublishIntoPersonalWorkspace publisher
            = new PublishIntoPersonalWorkspace();
        try {
            publisher.doIt();
        } catch (Exception ex) {
            ex.printStackTrace(System.err);
        }
    }

    private void doIt() throws Exception {

        SforceServiceLocator sforceServiceLocator
            = new SforceServiceLocator();

        SoapBindingStub binding
            = (SoapBindingStub) sforceServiceLocator
                .getSoap();

        // Login  
    
        LoginResult lr = binding.login("user@jstest.org",
                "password");

        binding._setProperty(Stub.ENDPOINT_ADDRESS_PROPERTY, lr
                .getServerUrl());

        // Create a session header for subsequent calls  
    
        _SessionHeader sessionHeader = new _SessionHeader();
        sessionHeader.setSessionId(lr.getSessionId());
        binding.setHeader(sforceServiceLocator.getServiceName()
                .getNamespaceURI(), "SessionHeader",
                sessionHeader);

        File testUploadFile = new File(TEST_FILE_PATH
                + "TestUpload.ppt");

        // Make sure we have enough space to upload the file,  
    
        // this can be increased to 25MB if necessary  
    
        if (testUploadFile.length() > BYTES_4M) {
            System.err.println("File exceeds 4MB!");
            return;
        }

        BufferedInputStream bins = new BufferedInputStream(
                new FileInputStream(testUploadFile));

        ByteBuffer readBuffer = ByteBuffer.allocate(BYTES_4M);
        byte[] readData = new byte[BYTES_16K];

        boolean done = false;
        int totalRead = 0;
        while (!done) {
            int bytesRead = bins.read(readData, 0,
                    readData.length);

            if (bytesRead == -1) {
                done = true;
            } else {
                readBuffer.put(readData, 0, bytesRead);
                totalRead += bytesRead;
            }
        }

        bins.close();

        // Create a content version object  
    
        ContentVersion contentVersion = new ContentVersion();

        // Set the mandatory field pathOnClient  
    
        contentVersion.setPathOnClient(testUploadFile
                .getAbsolutePath());

        // Set the binary file data  
    
        contentVersion.setVersionData(readData);

        // When publishing into a personal workspace set the  
    
        // user id  
    
        // Note: The userid must match the user that was used to  
    
        // log in  
    
        contentVersion.setFirstPublishLocationId(lr.getUserId());

        // You can add multiple versions if required by adding  
    
        // them to the array  
    
        SObject[] array = new SObject[] { contentVersion };
        SaveResult[] saveResultArray = binding.create(array);
        for (SaveResult sr : saveResultArray) {
            if (sr.isSuccess()) {
                System.out.println("created version with id:"
                    +  sr.getId());
            } else {
                System.out.println("Failed to create entity");
                for (Error error : sr.getErrors()) {
                    System.out.println(error.getMessage());
                }
            }
        }
    }

}

Share

Recipe Activity - Please Log in to write a comment

Is it possible to verify that the current user/session can create a ContentVersion before attempting the binding.create()?

Determine if the current user has access to the Salesforce CRM Content features via the Partner API

by daniel.ballinger10162007  (2011-03-28)

X

Vote to Verify a Recipe

Verifying a recipe is a way to give feedback to others and broaden your own understanding of the capabilities on Force.com. When you verify a recipe, please make sure the code runs, and the functionality solves the articulated problem as expected.

Please make sure:
  • All the necessary pieces are mentioned
  • You have tested the recipe in practice
  • Have sent any suggestions for improvements to the author

Please Log in to verify a recipe

You have voted to verify this recipe.