Liferay 6.2 – Save FTP files into Media Library

Share

Hello. In this article I will show you how to connect to a FTP server, get the files found there and save them into the Media Library of a Liferay Portal.

Liferay doesn’t have any built-in support for FTP, therefore for this particular problem are necessary FTPClient and FTPFile. If you are using Maven to build your project, then you can simply copy-paste the following code into the pom.xml file of your Liferay Plugin and then update the project to get the jars.



	commons-lang
	commons-lang
	2.6


	commons-io
	commons-io
	2.1


	commons-net
	commons-net
	3.0.1

The implementation is straight forward, nothing fancy. For the actual save into the library, the following methods were used:

  • Folder creation – addFolder method (DLFolderLocalServiceUtil class)
  • File save – addFileEntry method (DLAppServiceUtil class)

There are other ways to save into the Media Library, such as the methods from the class DLFileEntryLocalServiceUtil. But the one used in this tutorial is much simpler and enough for the task at hand. Although you are welcome to try them all and research further.

The main method deals with the FTP connection and calls the folder method and the actual download method. There’s also a check in place that verifies if the connection exists. Only then the login on the FTP sever and the file download will be called. Also don’t forget to set the server, user and pass values you are going to use. Remember to change the class name for the Log object as well.

private static final Log LOGGER = LogFactoryUtil.getLog(WhateverClassYouUse.class);

public void connectToFtp(final ResourceRequest resourceRequest, final ResourceResponse resourceResponse) {

	int port = 21;
        String server = "host";
	String user = "username";
	String pass = "password";

	FTPClient ftpClient = new FTPClient();

	ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
	long repositoryId = themeDisplay.getScopeGroupId();
	long userId = themeDisplay.getUserId();

	DLFolder parentFolder = getParentFolder(resourceRequest, repositoryId, userId);
	long folderId = parentFolder.getFolderId();

	try {
    		ftpClient.connect(server, port);
		if(ftpClient.isConnected()) {
	      	ftpClient.login(user, pass);
	      	ftpClient.enterLocalPassiveMode();	 
	      	LOGGER.info("Connected");

	            downloadFiles(resourceRequest, ftpClient, folderId, repositoryId);

		      ftpClient.logout();
	            
	      } else {
	           	LOGGER.info("Failed to connect to FTP server");
	      }

	      ftpClient.disconnect();	
	      LOGGER.info("Disconnected");

	} catch (IOException e) {
        	LOGGER.debug("downloadFiles", e);
      } catch (PortalException e) {
        	LOGGER.debug("downloadFiles", e);
	} catch (SystemException e) {
        	LOGGER.debug("downloadFiles", e);
	}
}

The next 2 methods work together. One deals with the creation of the root folder (parentFolder) and the other checks if this folder exists already. If the folder doesn’t exist, then it will be added in the Portal’s media library. Also you will have to set the folder id, folder name and folder description as shown below.

private static String ROOT_FOLDER_NAME = "myFolder";
private static String ROOT_FOLDER_DESCRIPTION = "This is the root folder";
private static long PARENT_FOLDER_ID = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;

public DLFolder getParentFolder(ResourceRequest resourceRequest, long repositoryId, long userId) {

	boolean parentFolderExist = isFolderExist(repositoryId);
	DLFolder folder = null;
	boolean mountPoint = false;
	boolean hidden = false;

	try {
		if (parentFolderExist) {
			folder = DLFolderLocalServiceUtil.getFolder(repositoryId, 
                                     PARENT_FOLDER_ID, ROOT_FOLDER_NAME);
		} else {
			ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFolder.class.getName(), resourceRequest);
			
			folder = DLFolderLocalServiceUtil.addFolder(userId, 
                                     repositoryId, repositoryId, mountPoint,
			             PARENT_FOLDER_ID, ROOT_FOLDER_NAME, 
                                     ROOT_FOLDER_DESCRIPTION, hidden, 
                                     serviceContext);
		}

	} catch (PortalException e) {
		LOGGER.debug("getParentFolder", e);
	} catch (SystemException e) {
		LOGGER.debug("getParentFolder", e);
	}

	return folder;
}


private boolean isFolderExist(long repositoryId) {
	boolean folderExist = false;
	DLFolder folder = null;

	try {
		folder = DLFolderLocalServiceUtil.getFolder(repositoryId, 
                             PARENT_FOLDER_ID, ROOT_FOLDER_NAME);
		if(folder != null) {
			folderExist = true;
		}
	} catch (Exception e) {
		LOGGER.debug("Parent folder not exist");
	}

	return folderExist;
}

Using the downloadFiles method, the stream will be read and the files will be added one by one in the folder already created. If the file already exists in the Media Library, the appropriate message will be displayed in the console.

public void downloadFiles(ResourceRequest resourceRequest, FTPClient ftpClient, long folderId, long repositoryId) throws IOException, PortalException, SystemException {

	FTPFile[] subFiles = ftpClient.listFiles();

	if (subFiles != null && subFiles.length > 0) {

		ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(), resourceRequest);

		for (FTPFile aFile : subFiles) {
			InputStream is = ftpClient.retrieveFileStream(aFile.getName());
			byte[] bytes = IOUtils.toByteArray(is);
			String fileName = aFile.getName();
				
			FileNameMap fileNameMap = URLConnection.getFileNameMap();
			String mimeType = fileNameMap.getContentTypeFor(fileName);

			try {
				LOGGER.info("Save file: " + fileName);
				DLAppServiceUtil.addFileEntry(repositoryId, folderId, 
                                    fileName, mimeType, fileName, null, 
                                    null, bytes, serviceContext);

			} catch (DuplicateFileException e) {
				LOGGER.info("Duplicate file: " + fileName);
			}

			ftpClient.completePendingCommand();
		}
	}
}

By continuing to use the site, you agree to the use of cookies. More information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close