Saturday, July 25, 2009

How to use the WCM API to retrieve content element information such as image component file size

Question
You would like to use the IBM® Web Content Management (WCM) API to access a content item's element and retrieve information. How can you retrieve the size of an image file stored in an image component?

Answer
The WCM API provides methods which allow access to a content item's elements, such as an image component.
Summary: How to access a content's element.

In this example, we retrieve the Image Component for a piece of WCM content:

1. Acquire the user workspace.
2. Set the current document library.
3. Build the document iterator (find your content)
4. Acquire the content's document id.
5. Use the ContentComponent getComponent(java.lang.String name) method to acquire the content element.
6. Use the ImageComponent getImageFileName() method to retrieve the image file name.
7. Use the ImageComponent getImage() method to retrieve the image file and set the image file as a Java byte array.
8. Use the Java byte array length value to determine the image file size in bytes.


**Note:** This example retrieves the image file size in bytes.

Example code retrieves a content's image component's image file size in bytes.

//finds the document id of the content items that match by name
DocumentIdIterator docIdIterator = ws.findByName(DocumentTypes.Content, "testcontent");
DocumentId docId;
Content currentContent;

//loops through the document id's found in the iterator
while(docIdIterator.hasNext())
{
docId = (DocumentId)docIdIterator.next();

//get the current content item
currentContent = (Content)ws.getById(docId);

//standard out log message
System.out.println("Log: Testing WCM API: Retrieved content name = "
+ (String)currentContent.getName());

//get the content's image component element by name
ContentComponent myCmpnt = (ContentComponent) currentContent.getComponent("MyImage");

//standard out log message
System.out.println("Log: Testing WCM API: My image component name = "
+ (String)myCmpnt.getName());

//Use the instanceof method to confirm the component type.
if (myCmpnt instanceof ImageComponent)
{
//Cast the ContentComponent to an ImageComponent
ImageComponent imageCmpnt;
imageCmpnt = (ImageComponent)myCmpnt;

//standard out log message
System.out.println("Log: Testing WCM API: My image component: File name = "
+ imageCmpnt.getImageFileName() );

//Get the image file stored in the current content's image component.
byte[] imageFileSize = imageCmpnt.getImage();

//Get the image file size and print it to the System out.
System.out.println("Log: Testing WCM API: My image component size in bytes: "
+ imageFileSize.length );
}// end if statement

}//end while