com.liferay.portal.test.TestUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.liferay.portal.test.TestUtil.java

Source

/**
 * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */
package com.liferay.portal.test;

import com.liferay.portal.bean.BeanLocatorImpl;
import com.liferay.portal.kernel.bean.PortalBeanLocatorUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.messaging.MessageBus;
import com.liferay.portal.kernel.messaging.MessageBusUtil;
import com.liferay.portal.kernel.messaging.sender.MessageSender;
import com.liferay.portal.kernel.messaging.sender.SynchronousMessageSender;
import com.liferay.portal.kernel.portlet.PortletClassLoaderUtil;
import com.liferay.portal.kernel.search.Indexer;
import com.liferay.portal.kernel.search.IndexerRegistryUtil;
import com.liferay.portal.kernel.search.SearchEngineUtil;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
import com.liferay.portal.service.CompanyLocalServiceUtil;
import com.liferay.portal.service.GroupLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.spring.transaction.TransactionCommitCallbackUtil;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.workflow.DLFileEntryWorkflowHandler;
import jodd.util.StringUtil;
import org.junit.Assert;
import org.mockito.Mockito;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class TestUtil {

    public static long getCompanyId() throws Exception {
        long companyId = CompanyLocalServiceUtil.getCompanyByWebId("liferay.com").getCompanyId();
        Assert.assertTrue(companyId > 0);
        return companyId;
    }

    public static long getGroupId() throws Exception {
        long companyId = getCompanyId();
        long groupId = GroupLocalServiceUtil.getGroup(companyId, "Guest").getGroupId();
        Assert.assertTrue(groupId > 0);
        return groupId;
    }

    public static long getUserId() throws Exception {
        long userId = UserLocalServiceUtil.getDefaultUserId(getCompanyId());
        Assert.assertTrue(userId > 0);
        return userId;
    }

    private static void setPortletClassLoader() {
        //Had to add this for GA2
        Thread currentThread = Thread.currentThread();
        ClassLoader contextClassLoader = currentThread.getContextClassLoader();
        PortletClassLoaderUtil.setClassLoader(contextClassLoader);
    }

    public static ApplicationContext initSpringForPortlet(String portletName) throws Exception {
        setPortletClassLoader();
        List<String> configLocations = getPortletConfigLocations(portletName);

        BeanLocatorImpl impl = (BeanLocatorImpl) PortalBeanLocatorUtil.getBeanLocator();
        ApplicationContext parent = impl.getApplicationContext();

        String[] locations = configLocations.toArray(new String[0]);
        ApplicationContext context = new FileSystemXmlApplicationContext(locations, parent);

        return context;
    }

    public static List<String> getPortletConfigLocations(String portletName) throws Exception {
        String basePath = getFullBasePath();

        String docrootPath = "/portlets/" + portletName + "/docroot/";

        String path = basePath + docrootPath + "WEB-INF/src/service.properties";
        Properties props = new Properties();
        FileInputStream fis = new FileInputStream(path);
        props.load(fis);
        String springConfigs = props.getProperty("spring.configs");
        String[] configs = com.liferay.portal.kernel.util.StringUtil.split(springConfigs, ",");
        List<String> configLocations = new ArrayList<String>();

        for (int i = 0; i < configs.length; i++) {
            String config = configs[i];
            String fullPath = docrootPath + config;
            //Only include files which are actually present, e.g. ext-spring.xml
            // isn't required to be there but is automatically included in the spring.configs
            if (FileUtil.exists(basePath + fullPath)) {
                _log.info("Including config file: " + fullPath);
                configLocations.add(fullPath);
            }
        }

        //Also add in the test xml if present
        String testPath = docrootPath + "WEB-INF/classes/META-INF/ext-spring-test.xml";
        if (FileUtil.exists(basePath + testPath)) {
            configLocations.add(testPath);
        }

        return configLocations;
    }

    public static void initDLAppDependencies() throws Exception {
        // Needed by the DLAApp
        WorkflowHandlerRegistryUtil.register(new DLFileEntryWorkflowHandler());
        TestUtil.initMessageBus();
        SearchEngineUtil.setIndexReadOnly(true);
        IndexerRegistryUtil.register(DLFileEntry.class.getName(), Mockito.mock(Indexer.class));

        // Have to initialize the transaction callback list, should be an easier way to do this
        Method m = TransactionCommitCallbackUtil.class.getDeclaredMethod("pushCallbackList", null);
        m.setAccessible(true);
        m.invoke(null, null);
    }

    public static void initMessageBus() {
        //Lifted from the events.StartupAction
        if (_log.isDebugEnabled()) {
            _log.debug("Initialize message bus");
        }

        MessageBus messageBus = (MessageBus) PortalBeanLocatorUtil.locate(MessageBus.class.getName());
        MessageSender messageSender = (MessageSender) PortalBeanLocatorUtil.locate(MessageSender.class.getName());
        SynchronousMessageSender synchronousMessageSender = (SynchronousMessageSender) PortalBeanLocatorUtil
                .locate(SynchronousMessageSender.class.getName());

        MessageBusUtil.init(messageBus, messageSender, synchronousMessageSender);
    }

    /**
     * Get a resource File where the path is relative to liferay-plugin
     *
     * @param path path to resource relative to liferay-plugin
     * @return
     */
    public static File getResourceFile(String path) {
        String basePath = getFullBasePath();
        String name = basePath + path;

        File result = new File(name);
        Assert.assertTrue("the resource file should exist at" + name, result.exists());
        return result;
    }

    private static String getFullBasePath() {
        //Note; assume the running directory is the liferay-plugin directory
        //Should be able to use current classLoader.getResource but had issues
        // getting that to work within IntelliJ as well as Ant.
        File file = new File("test");
        String basePath = file.getAbsolutePath();
        basePath = basePath.substring(0, StringUtil.lastIndexOfIgnoreCase(basePath, "/"));
        return basePath;
    }

    private static Log _log = LogFactoryUtil.getLog(TestUtil.class);

}