Nicolas Raoul
Nicolas Raoul

Reputation: 60203

How to create Liferay web content in Java?

Creating a Web Content is easy via the UI.

But how to do add a new Web Content programmatically, in Java?

enter image description here

I must migrate data from a legacy system to Liferay 7, so I am writing a Java OSGI bundle to do so. No user interface.

Upvotes: 0

Views: 2695

Answers (2)

Milen Dyankov
Milen Dyankov

Reputation: 3052

In such cases it helps to look at the source code.

Also consider using an Upgrade Process. While your case is not really an update it sounds like a one time operation which you would ideally perform on startup.

Upvotes: 0

myakiju
myakiju

Reputation: 46

Nicolas.

I had a similar problem to solve in Liferay 6.2, but I believe you can solve yours using the same approach.

We built a "integration interface" (a simple Java Batch project to trigger the whole thing) that comunicates with the legacy system and with a Liferay REST Service (created using Liferay Service Builder).

Liferay provides you a Service API where you can handle some of its resources. To create a Journal Article (Web Content) you must invoke the Class JournalArticleLocalServiceUtil

Here is a sample code to create a Journal Article:

public static JournalArticle addJournalArticle(
        long userId, long groupId, String title, String contentEn)
        throws Exception {

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setScopeGroupId(groupId);
    serviceContext.setWorkflowAction(WorkflowConstants.ACTION_PUBLISH);
    Map<Locale, String> titleMap = new HashMap<Locale, String>();
    Map<Locale, String> descriptionMap = new HashMap<Locale, String>();

    titleMap.put(Locale.US, title);
    descriptionMap.put(Locale.US, title);


    try {
        JournalArticleLocalServiceUtil.deleteArticle(groupId, title, serviceContext);
    } catch (Exception ex) {
        System.out.println("Ignoring " + ex.getMessage());
    }

    String xmlContent = "<?xml version='1.0' encoding='UTF-8'?>" +
            "<root default-locale=\"en_US\" available-locales=\"en_US\">" +
                "<static-content language-id=\"en_US\">" +
                    "<![CDATA[" + contentEn + "]]>" +
                "</static-content>" +
            "</root>";

    JournalArticle article = JournalArticleLocalServiceUtil.addArticle(
            userId, groupId, 0, 
            0, 0, title, true, 
            JournalArticleConstants.VERSION_DEFAULT, titleMap, 
            descriptionMap, xmlContent, 
            "general", null, null, null, 
            1, 1, 2014, 0, 0,
            0, 0, 0, 0, 0, true, 
            0, 0, 0, 0, 0, true, 
            true, false, null, null, 
            null, null, serviceContext);

    return article;
}

But you must to improve it to put the correct user permissions, categories, tags and etc.

Upvotes: 3

Related Questions