org.kmworks.liferay.rpc.client.RPCExtensionsHttp.java Source code

Java tutorial

Introduction

Here is the source code for org.kmworks.liferay.rpc.client.RPCExtensionsHttp.java

Source

/*
 * Copyright (C) 2005-2014 Christian P. Lerch <christian.p.lerch [at] gmail [dot] com>
 *
 * 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 3 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.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution. If not, see <http://www.gnu.org/licenses/>.
 */
package org.kmworks.liferay.rpc.client;

import com.google.common.io.ByteStreams;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.util.MethodHandler;
import com.liferay.portal.kernel.util.MethodKey;
import com.liferay.portal.model.CompanyConstants;
import com.liferay.portal.model.Group;
import com.liferay.portal.security.auth.HttpPrincipal;
import com.liferay.portal.service.ServiceContext;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.kmworks.liferay.rpc.service.RPCExtensionsLocalServiceUtil;
import org.kmworks.liferay.rpc.utils.AuthToken;
import org.kmworks.liferay.rpc.utils.RPCTunneling;
import org.kmworks.utils.MimeType;

/**
 *
 * @author Christian P. Lerch
 */
public class RPCExtensionsHttp {

    /** Authenticate a HttpPrincipal against the Liferay user database.
     * The login string passed in via principal must match the basic authentication method configured in the portal 
     * (e-mail address, screen name or user id).
     * @param principal
     * @return The userId on successful authentication, Authenticator.FAILURE otherwise
     * @throws PortalException
     * @throws SystemException 
     */
    public static long authenticateUser(HttpPrincipal principal) throws PortalException, SystemException {

        final String login = principal.getLogin();
        final String authType = login.contains("@") ? CompanyConstants.AUTH_TYPE_EA
                : isNumber(login) ? CompanyConstants.AUTH_TYPE_ID : CompanyConstants.AUTH_TYPE_SN;
        try {
            MethodKey methodKey = new MethodKey(RPCExtensionsLocalServiceUtil.class, "authenticateUser",
                    _parameterTypes3);

            MethodHandler methodHandler = new MethodHandler(methodKey, principal.getCompanyId(), authType, login,
                    principal.getPassword());

            return (long) RPCTunneling.invoke(principal, methodHandler);
        } catch (SystemException se) {
            _log.error(se, se);
            throw se;
        }
    }

    /** Return the user's repositoryId (sometimes also called groupId).
     * 
     * @param token The authenticated user token
     * @return The user's repository id
     * @throws PortalException
     * @throws SystemException 
     */
    public static long getRepositoryId(AuthToken token) throws PortalException, SystemException {

        final long userId = token.getUserId();
        final HttpPrincipal principal = token.getPrincipal();

        try {
            MethodKey methodKey = new MethodKey(com.liferay.portal.service.GroupLocalServiceUtil.class, "getGroup",
                    _parameterTypes4);

            MethodHandler methodHandler = new MethodHandler(methodKey, principal.getCompanyId(),
                    String.valueOf(userId));

            Group group = (Group) RPCTunneling.invoke(principal, methodHandler);
            if (group == null)
                throw new SystemException("GroupLocalServiceUtil.getGroup returned null for userId: " + userId);
            return group.getGroupId();
        } catch (SystemException se) {
            _log.error(se, se);
            throw se;
        }
    }

    /** Download a FileEntry's file content to a file on the local file system.
     * 
     * @param token The authenticated user token
     * @param fileEntryId
     * @param version
     * @param localFile
     * @return
     * @throws PortalException
     * @throws SystemException 
     */
    public static long downloadFile(AuthToken token, long fileEntryId, String version, File localFile)
            throws PortalException, SystemException {

        long byteCount;
        try {
            try (InputStream from = new ByteArrayInputStream(getFileAsBytes(token, fileEntryId, version));
                    OutputStream to = new FileOutputStream(localFile)) {
                byteCount = ByteStreams.copy(from, to);
            }
        } catch (IOException ioe) {
            _log.error(ioe, ioe);
            throw new SystemException(ioe);
        }
        return byteCount;
    }

    /** Download a FileEntry's file content to a file on the server file system.
     * Be careful with relative file specs: they are resolved relative to the application server home directory.
     * This is the only file retrieval method, that doesn't serialize the file content through the
     * underlying HTTP stream.
     * 
     * @param token The authenticated user token
     * @param fileEntryId
     * @param version
     * @param serverFile
     * @return
     * @throws PortalException
     * @throws SystemException 
     */
    public static long downloadFileToServer(AuthToken token, long fileEntryId, String version, File serverFile)
            throws PortalException, SystemException {

        try {
            MethodKey methodKey = new MethodKey(RPCExtensionsLocalServiceUtil.class, "downloadFileToServer",
                    _parameterTypes2);

            MethodHandler methodHandler = new MethodHandler(methodKey, token.getUserId(), fileEntryId, version,
                    serverFile);

            return (long) RPCTunneling.invoke(token.getPrincipal(), methodHandler);
        } catch (SystemException se) {
            _log.error(se, se);
            throw se;
        }
    }

    /** Return a FileEntry's file content as a stream.
     * This is just a convenience wrapper for getFileAsBytes, which is doing the job.
     * @param token The authenticated user token
     * @param fileEntryId
     * @param version
     * @return
     * @throws PortalException
     * @throws SystemException 
     */
    public static InputStream getFileAsStream(AuthToken token, long fileEntryId, String version)
            throws PortalException, SystemException {

        return new ByteArrayInputStream(getFileAsBytes(token, fileEntryId, version));
    }

    /** Return a FileEntry's file content as a (serializable) byte array.
     * 
     * All other methods for retrieving a FileEntry's file content are based on this one,
     * because byte arrays are the only containers that can be serialized.
     * Note however, that for very lerge files calling this mehtod may not be reasonable
     * due to excessive memory consumption. In such a case downloading the file to the 
     * server's filesystem with method downloadFileToServer() may be a viable solution.
     * 
     * @param token The authenticated user token
     * @param fileEntryId
     * @param version
     * @return
     * @throws PortalException
     * @throws SystemException 
     */
    public static byte[] getFileAsBytes(AuthToken token, long fileEntryId, String version)
            throws PortalException, SystemException {

        try {
            MethodKey methodKey = new MethodKey(RPCExtensionsLocalServiceUtil.class, "getFileAsBytes",
                    _parameterTypes1);

            MethodHandler methodHandler = new MethodHandler(methodKey, token.getUserId(), fileEntryId, version);

            return (byte[]) RPCTunneling.invoke(token.getPrincipal(), methodHandler);
        } catch (SystemException se) {
            _log.error(se, se);
            throw se;
        }
    }

    /** Upload a local file to the portal, thereby creating a new FileEntry.
     * This is just a convenience wrapper around DLAppServiceHttp.addFileEntry(...) which is doing all the work.
     * @param token  The authenticated user token holding the user that will be the owner of the new FileEntry
     * @param folderId  The id of target folder; must be in repository of the user defined in AccessToken
     * @param title The title of new FileEntry (i.e. document title)
     * @param sourceFileName The upload file's name
     * @param in The upload file's content as an open input stream
     * @return Newly created FileEntry
     * @throws PortalException
     * @throws SystemException 
     */
    public static FileEntry uploadFile(AuthToken token, long folderId, String title, String sourceFileName,
            InputStream in) throws PortalException, SystemException {

        final long userId = token.getUserId();
        final long repositoryId = token.getRepositoryId();
        final String mimeType = MimeType.fromFileName(sourceFileName);

        final ServiceContext svcCtx = new ServiceContext();
        svcCtx.setCompanyId(token.getPrincipal().getCompanyId());
        svcCtx.setScopeGroupId(repositoryId);
        svcCtx.setUserId(userId);
        svcCtx.setAddGroupPermissions(true);
        svcCtx.setIndexingEnabled(true);

        FileEntry fileEntry = null;
        try {
            fileEntry = com.liferay.portlet.documentlibrary.service.http.DLAppServiceHttp.addFileEntry(
                    token.getPrincipal(), // owner
                    repositoryId, // = repositoryId
                    folderId, // parent folder
                    sourceFileName, // 
                    mimeType, // 
                    title, // document title
                    "", // description
                    "", // changeLog entry
                    ByteStreams.toByteArray(in), // file's byte content
                    svcCtx);
            if (fileEntry == null)
                throw new NullPointerException();
        } catch (NullPointerException | IOException ex) {
            _log.error(ex, ex);
            throw new SystemException(ex);
        } catch (SystemException se) {
            _log.error(se, se);
            throw se;
        }
        return fileEntry;
    }

    /**
     * 
     * @param token The authenticated user token
     * @return
     * @throws PortalException
     * @throws SystemException 
     */
    public static int getOrganizationsCount(AuthToken token) throws PortalException, SystemException {

        try {
            MethodKey methodKey = new MethodKey(com.liferay.portal.service.OrganizationLocalServiceUtil.class,
                    "getOrganizationsCount", _parameterTypes0);

            MethodHandler methodHandler = new MethodHandler(methodKey);

            return (int) RPCTunneling.invoke(token.getPrincipal(), methodHandler);
        } catch (SystemException se) {
            _log.error(se, se);
            throw se;
        }
    }

    /**
     * 
     * @param token The authenticated user token
     * @return
     * @throws PortalException
     * @throws SystemException 
     */
    public static int getUsersCount(AuthToken token) throws PortalException, SystemException {

        try {
            MethodKey methodKey = new MethodKey(com.liferay.portal.service.UserLocalServiceUtil.class,
                    "getUsersCount", _parameterTypes0);

            MethodHandler methodHandler = new MethodHandler(methodKey);

            return (int) RPCTunneling.invoke(token.getPrincipal(), methodHandler);
        } catch (SystemException se) {
            _log.error(se, se);
            throw se;
        }
    }

    private static boolean isNumber(String s) {
        Long number = null;
        try {
            number = Long.parseLong(s);
        } catch (NumberFormatException e) {
        }
        return number != null;
    }

    private static final Class<?>[] _parameterTypes0 = new Class[] {};
    private static final Class<?>[] _parameterTypes1 = new Class[] { long.class, long.class, String.class };
    private static final Class<?>[] _parameterTypes2 = new Class[] { long.class, long.class, String.class,
            File.class };
    private static final Class<?>[] _parameterTypes3 = new Class[] { long.class, String.class, String.class,
            String.class };
    private static final Class<?>[] _parameterTypes4 = new Class[] { long.class, String.class };

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

}