Не удалось загрузить файл записи библиотеки документов в Liferay DXP 7.4

В настоящее время я разрабатываю портлет Liferay, который может загружать некоторые файлы pdf и png в репозиторий документов и мультимедиа в Liferay DXP 7.4.13 u33. Я пытаюсь использовать статический метод addFileEntry из класса DLFileEntryLocalServiceUtil. Либо в обычном, либо в устаревшем режиме он не работает.

Я также пробовал сDLAppLocalServiceUtil.addFileEntry(externalReferenceCode, userId, repositoryId, folderId, sourceFileName,mimeType, urlTitle, description, changeLog, file, expirationDate, reviewDate, serviceContext) but I got the same result.

Я получаю следующие ошибки из этого запроса, когда я вызываю этот метод через MVCActionCommand в своем портлете:

          ERROR [liferay/monitoring-4][ParallelDestination:59] Unable to process message {destinationName=liferay/monitoring, response=null, responseDestinationName=null, 
responseId=null, payload=[{displayName=ConceptUploadUrls, portletId=com_liferay_concept_upload_urls_ConceptUploadUrlsPortlet_INSTANCE_KNuJiTyuo6gx, 
requestType=ACTION, {attributes=null, companyId=20097, groupId=20121, description=null, duration=0, name=com_liferay_concept_upload_urls_ConceptUploadUrlsPortlet, 
namespace=com.liferay.monitoring.Portlet, requestStatus=null, stopWatch=0:00:10.151, timeout=0, user=20125}}, {referer=http://localhost:8080/client, remoteAddr=127.0.0.1, 
requestURL=, statusCode=0, userAgent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36, {attributes=null, 
companyId=20097, groupId=20121, description=null, duration=10155, name=/c/portal/layout, namespace=com.liferay.monitoring.Portal, requestStatus=ERROR, stopWatch=0:00:10.155, 
timeout=-1, user=20125}}, {referer=http://localhost:8080/client, remoteAddr=127.0.0.1, requestURL=, statusCode=0, userAgent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36, {attributes=null, companyId=20097, groupId=0, description=null, duration=10157, name=/web/guest/carga-por-url, 
namespace=com.liferay.monitoring.Portal, requestStatus=ERROR, stopWatch=0:00:10.157, timeout=-1, user=null}}], values={defaultLocale=en_US, companyId=20097, groupId=0, principalName=20125, 
permissionChecker=com.liferay.portal.kernel.util.TransientValue@4ff66308, siteDefaultLocale=en_US, themeDisplayLocale=en_US}}
    com.liferay.portal.kernel.messaging.MessageListenerException: java.lang.NullPointerException
    
    Caused by: java.lang.NullPointerException at com.liferay.portal.monitoring.internal.statistics.portlet.PortletStatistics.processDataSample(PortletStatistics.java:112) ~[?:?]
    ...

    ERROR [http-nio-8080-exec-3][VirtualHostFilter:381] null
    javax.servlet.ServletException: Servlet execution threw an exception
    
    Caused by: java.lang.NoSuchMethodError: com.liferay.document.library.kernel.service.DLAppService.addFileEntry(Ljava/lang/String;
    JJLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/io/File;Ljava/util/Date;Ljava/util/Date;Lcom/liferay/portal/kernel/service/ServiceContext;)Lcom/liferay/portal/kernel/repository/model/FileEntry;
            at com.liferay.concept.upload.urls.portlet.action.UploadFile.uploadFile(UploadFile.java:193) ~[?:?]
    ...

Полная программа следующая:

      package com.liferay.concept.upload.urls.portlet.action;

import com.liferay.concept.upload.urls.constants.ConceptUploadUrlsPortletKeys;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.portlet.bridges.mvc.BaseMVCActionCommand;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCActionCommand;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.ServiceContextFactory;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.MimeTypesUtil;
import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.kernel.util.WebKeys;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import com.liferay.concept.upload.urls.constants.MVCCommandNames;
import com.liferay.document.library.kernel.model.DLFileEntry;
import com.liferay.document.library.kernel.model.DLFolderConstants;
import com.liferay.document.library.kernel.service.DLFileEntryLocalServiceUtil;
import com.liferay.dynamic.data.mapping.kernel.DDMFormValues;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;

import org.osgi.service.component.annotations.Component;

@Component(immediate = true, property = { "javax.portlet.name=" + ConceptUploadUrlsPortletKeys.CONCEPTUPLOADURLS,
        "mvc.command.name=" + MVCCommandNames.UPLOAD_FILE }, service = MVCActionCommand.class)

public class UploadFile extends BaseMVCActionCommand {

    @Override
    protected void doProcessAction(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
        try {
            UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);

            if (uploadRequest.getSize("myFile") == 0) {
                SessionErrors.add(actionRequest, "error");
            }

            // saving the document in local
            String fileName = uploadRequest.getFileName("myFile");
            File file = uploadRequest.getFile("myFile");
            saveDocument(file, fileName);

            // readandDownload
            List<String> urls = UploadUrlsFromFile(actionRequest, file);

            System.out.println("urls Read: " + urls);
            SessionMessages.add(actionRequest, "success");
        } catch (FileNotFoundException e) {
            System.out.println("EXCEPTION! Input File Not Found.");
            e.printStackTrace();
            SessionMessages.add(actionRequest, "error");
        } catch (NullPointerException e) {
            System.out.println("EXCEPTION! An Object is null");
            e.printStackTrace();
            SessionMessages.add(actionRequest, "error");
        } catch (IOException e) {
            System.out.println("EXCEPTION! Error Reading The Input File.");
            SessionMessages.add(actionRequest, "error");
            e.printStackTrace();
        } catch (PortalException p) {
            System.out.println("EXCEPTION! Portal Exception");
            p.printStackTrace();
            SessionMessages.add(actionRequest, "error");
        }
    }

    private void saveDocument(File file, String fileName) throws IOException {
        File newFile = new File(folder + "_" + fileName);

        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(newFile);
        System.out.println("File: " + file);
        System.out.println("SavedFile: " + newFile);

        byte[] bytes_ = FileUtil.getBytes(file);
        int i = fis.read(bytes_);

        while (i != -1) {
            fos.write(bytes_, 0, i);
            i = fis.read(bytes_);
        }
        fis.close();
        fos.close();
        long size = newFile.length();
        System.out.println("File size kb:" + (float) size / 1024);
        System.out.println("File created: " + newFile.getName());
    }

    private List<String> UploadUrlsFromFile(ActionRequest actionRequest, File inputFile)
            throws IOException, PortalException {
        BufferedReader br = new BufferedReader(new FileReader(inputFile));
        String line;
        List<String> urls = new ArrayList<String>();
        while ((line = br.readLine()) != null) {
            urls.add(line);
        }
        br.close();
        for (String url : urls) {
            String fileName = getNameForFileFromUrl(url);
            // download file from the web
            try {
                File file = downloadFile(url, fileName); 
                DLFileEntry dlFileEntry = uploadFile(actionRequest, file);
                
            } catch (NoSuchMethodError e) {
                System.out.println("EXCEPTION! Error with the class method.");
                SessionMessages.add(actionRequest, "error");
            } catch (PortalException e) {
                SessionMessages.add(actionRequest, "error");
                throw (new PortalException());
            } catch (FileNotFoundException e) {
                System.out.println("EXCEPTION! File Not Found.");
                SessionMessages.add(actionRequest, "error");
            } catch (MalformedURLException e) {
                System.out.println("EXCEPTION! Malformed URL.");
                SessionMessages.add(actionRequest, "error");
            } catch (IOException e) {
                System.out.println("EXCEPTION! Error reading the File.");
                SessionMessages.add(actionRequest, "error");
            }
        }
        return urls;
    }

    private String getNameForFileFromUrl(String url) {
        String fileName = String.valueOf(url);
        int index = fileName.lastIndexOf("/");
        if (index != -1) {
            fileName = fileName.substring(index + 1);
        }
        return fileName;
    }

    private File downloadFile(String url, String fileName) throws MalformedURLException, IOException, FileNotFoundException {
        String completePath = folder + fileName;
        BufferedInputStream in = new BufferedInputStream(new URL(url).openStream());

        System.out.println("URL: " + url);
        FileOutputStream fileOutputStream = new FileOutputStream(completePath);
        byte dataBuffer[] = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
            fileOutputStream.write(dataBuffer, 0, bytesRead);
        }
        fileOutputStream.close();
        File file = new File(completePath);
        System.out.println("New File Downloaded: " + completePath);
        return file;
    }

    @SuppressWarnings("deprecation")
    private DLFileEntry uploadFile(ActionRequest actionRequest, File file) throws PortalException {
        ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
        String fileName = file.getName();

        String externalReferenceCode = "";
        long userId = themeDisplay.getUserId();
        long groupId = themeDisplay.getScopeGroupId();
        long repositoryId = groupId;
        long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
        String sourceFileName = fileName;
        String mimeType = MimeTypesUtil.getContentType(file);
        String title = FileUtil.stripExtension(fileName);
        String urlTitle = FileUtil.stripExtension(fileName).substring(0, 10);
        String description = fileName;
        String changeLog = "initialization, web source";
        long fileEntryType = 0;
        Map<String, DDMFormValues> ddmFormValuesMap = null;
        InputStream inputStream = null;
        long size = file.length();

//      Calendar.set
        Calendar myCal = Calendar.getInstance();
        myCal.set(Calendar.YEAR, 2023);
        myCal.set(Calendar.MONTH, 3);
        myCal.set(Calendar.DAY_OF_MONTH, 2);
//      Date expirationDate = myCal.getTime(); // never expire
        myCal.set(Calendar.DAY_OF_MONTH, 1);
//      Date reviewDate = myCal.getTime(); // never review

        ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); // permissions and assets
        System.out.println("size: " + size);
        System.out.println("folderId: " + folderId);
        System.out.println("Creating file in DL....");

        DLFileEntry fileEntry = null;
        try {
            fileEntry = DLFileEntryLocalServiceUtil.addFileEntry(userId, groupId, repositoryId, folderId, fileName,
                    mimeType, fileName, "", "", 0, null, file, null, size, serviceContext);
            System.out.println("file entry added");

        } catch (Exception e) {
            System.out.println("Exception File Entry");
            e.printStackTrace();
            throw (new PortalException());
        }
        return fileEntry;

    }

    private String folder = "D:\\LIFERAY-gradebook\\gradebook-workspace\\modules\\concept-upload-urls\\files\\";
}

0 ответов

Другие вопросы по тегам