Subversion Repositories bacoAlunos

Rev

Rev 1782 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package pt.estgp.estgweb.services.ftpservices;

import jomm.utils.DesUtils;
import jomm.utils.DiacriticFilter;
import jomm.utils.FilesUtils;
import jomm.utils.MimeTypeGuesser;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import pt.estgp.estgweb.domain.CourseUnitImpl;
import pt.estgp.estgweb.domain.UserSession;
import pt.estgp.estgweb.domain.UserSessionImpl;
import pt.estgp.estgweb.domain.dao.DaoFactory;
import pt.estgp.estgweb.utils.ConfigProperties;
import pt.estgp.estgweb.web.FtpServer;
import pt.estgp.estgweb.utils.DatesWebUtils;
import pt.utl.ist.berserk.logic.serviceManager.IService;

import java.io.File;
import java.io.IOException;

/**
 * @author Jorge Machado
 * @date 20/Mar/2008
 * @time 18:31:00
 * @see pt.estgp.estgweb.services.email
 */

public class FtpService implements IService
{

    private static final 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(FtpService.class);

    public static final 1.5.0/docs/api/java/lang/String.html">String FTP_PASSWORD = "pt.estgp.estgweb.services.ftpservices.FtpService.FTP_PASSWORD";


    public 1.5.0/docs/api/java/lang/String.html">String run(FtpRequestForm ftpRequestForm, UserSession userSession) throws 1.5.0/docs/api/java/io/IOException.html">IOException
    {
        //userSession.getUser().get
        boolean isStaticAccess = ConfigProperties.getBooleanProperty(ftpRequestForm.getServerConfName()+".use.default.credentials.to.updates.and.deletes");
        1.5.0/docs/api/java/lang/String.html">String password = ftpRequestForm.getPassword();
        1.5.0/docs/api/java/lang/String.html">String username = ftpRequestForm.getUsername();
        //This only works for Contents of CourseUnits, if user uses SavePassword than the password saved will be used
        if(!ftpRequestForm.isSavePassword() && isStaticAccess)
        {
            if(ftpRequestForm.getCourseUnitView() != null)
            {
                CourseUnitImpl courseUnit = (CourseUnitImpl) DaoFactory.getCourseUnitDaoImpl().load(ftpRequestForm.getCourseUnitView().getId());
                if(!courseUnit.checkIsOwnedBy(userSession.getUser(), true))
                {
                    logger.warn("Trying to admin FTP Folder, no permission for username:" + userSession.getUsername());
                    return "errors.ftp.no.permission";
                }
                username = ConfigProperties.getProperty(ftpRequestForm.getServerConfName() + ".user");
                password = ConfigProperties.getProperty(ftpRequestForm.getServerConfName() + ".pass");
            }
            else
               return "errors.ftp.no.permission";
        }
        else
        {
            if(ftpRequestForm.isSavePassword() && ftpRequestForm.getPassword() != null && ftpRequestForm.getPassword().trim().length() > 0)
            {
                ((UserSessionImpl)userSession).put(FTP_PASSWORD,DesUtils.getInstance().encrypt(ftpRequestForm.getPassword()));
            }
            //ESTE CAMPO É COLOCADO EM MEMORIA LOGO NA AUTENTICACAO POR ISSO A POP3 PASS NAO CHEGA A SER USADA
            //E A POP3PASS DAVA PROBLEMAS SE O USER ALGUMA VEZ A TINHA INICIADO
            1.5.0/docs/api/java/lang/String.html">String passwordCode = (1.5.0/docs/api/java/lang/String.html">String) ((UserSessionImpl)userSession).get(FTP_PASSWORD);

            //System.out.println("SAVEDCODE"+passwordCode);

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

            }
            else
            {
                logger.info("using saved password");
                password = DesUtils.getInstance().decrypt(passwordCode);
                //System.out.println("SAVEDPASS:" + password);
            }
            /*else if(userSession.getUser().getPop3password() != null && userSession.getUser().getPop3password().length() > 0)
            {
                logger.info("trying pop 3 password");
                password = DesUtils.getInstance().decrypt(userSession.getUser().getPop3password());
            }
            else
            {
                logger.info("trying last used login password");
                password = DesUtils.getInstance().decrypt(userSession.getUser().getPassword());
            }*/

            username = ftpRequestForm.getUsername();
            if(username == null || username.trim().length() == 0)
                username = userSession.getUsername();
        }
        FtpServer server = FtpServer.getNewServer(ftpRequestForm.getServerUrl(),username,password);
        FTPClient client = server.getClient();
        if(client == null)
        {
            logger.warn("###################");
            logger.warn("################### > CANT CONNECT FTP");
            return server.getErrorMsg();
        }

        1.5.0/docs/api/java/lang/String.html">String result = "ftp.operation.success";
        client.setFileType(FTP.BINARY_FILE_TYPE);
        logger.info("changing working path to " + ftpRequestForm.getStartPath());
        client.changeWorkingDirectory(ftpRequestForm.getStartPath());
        if(ftpRequestForm.getFilesToImport() != null)
        {
            for(FileItem item: ftpRequestForm.getFilesToImport())
            {

                1.5.0/docs/api/java/lang/String.html">String name = item.getName();

                if(name != null)
                {

                    if(name.length() > 2 && name.charAt(1)==':')
                    {

                        1.5.0/docs/api/java/lang/String.html">String[] names = name.split("\\\\");

                        name = names[names.length - 1];
                    }
                    else
                    {
                        name = new 1.5.0/docs/api/java/io/File.html">File(item.getName()).getName();
                    }
                }

                logger.info("trying to import file: " + name);
                //client.setControlEncoding("ISO-8859-1");
                if(!client.storeFile(DiacriticFilter.stripAccents(name),item.getInputStream()))
                    result = "errors.ftp.no.permission";
            }
        }
        if(ftpRequestForm.getNewFolderName() != null && ftpRequestForm.getNewFolderName().trim().length() > 0)
        {
            if(!client.makeDirectory(ftpRequestForm.getNewFolderName()))
                result = "errors.ftp.no.permission";
        }
        if(ftpRequestForm.getFileToDelete() != null && ftpRequestForm.getFileToDelete().trim().length() > 0)
        {
            if(!client.deleteFile(ftpRequestForm.getFileToDelete()))
                result = "errors.ftp.no.permission";
        }
        if(ftpRequestForm.getFolderToDelete() != null && ftpRequestForm.getFolderToDelete().trim().length() > 0)
        {
            int code = client.rmd(ftpRequestForm.getFolderToDelete());
            if(code != 250)
            {
                if(code == 550)
                    return "error.ftp.dir.not.empty";
                else if(code == 530)
                    return "errors.ftp.no.permission";
            }

        }
        client.quit();
        client.disconnect();
        return result;
    }

    private static void printMem()
    {
        int mb = 1024*1024;

        //Getting the runtime reference from system
        1.5.0/docs/api/java/lang/Runtime.html">Runtime runtime = 1.5.0/docs/api/java/lang/Runtime.html">Runtime.getRuntime();


        //Print used memory
        logger.debug("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);

    }
    public static long[] calculateDirectoryInfo(FtpServer.FtpClientWrapper ftpClient,
                                                1.5.0/docs/api/java/lang/String.html">String parentDir, 1.5.0/docs/api/java/lang/String.html">String currentDir) throws 1.5.0/docs/api/java/io/IOException.html">IOException {
        long[] info = new long[4];
        //System.gc();
        printMem();
        int totalDirs = 0;
        int totalFiles = 0;
        long totalSize = 0;
        long lastUpdate = 0;

        1.5.0/docs/api/java/lang/String.html">String dirToList = parentDir;
        if (!currentDir.equals("")) {
            dirToList += "/" + currentDir;
        }

        try {

            FTPFile[] subFiles = ftpClient.listFiles(dirToList);

            if (subFiles != null && subFiles.length > 0) {
                for (FTPFile aFile : subFiles) {
                    1.5.0/docs/api/java/lang/String.html">String currentFileName = aFile.getName();
                    if (currentFileName.equals(".")
                            || currentFileName.equals("..")) {
                        // skip parent directory and the directory itself
                        continue;
                    }

                    //System.out.println("dir:" +currentDir+ aFile.getName());
                    if (aFile.isDirectory()) {
                        //System.out.println("dir:" +currentDir+ aFile.getName());
                        totalDirs++;
                        long[] subDirInfo =
                                calculateDirectoryInfo(ftpClient, dirToList, currentFileName);
                        totalDirs += subDirInfo[0];
                        totalFiles += subDirInfo[1];
                        totalSize += subDirInfo[2];
                        if(subDirInfo[3] > lastUpdate)
                            lastUpdate = subDirInfo[3];
                    } else {
                        totalSize += aFile.getSize();
                        totalFiles++;
                        if(aFile.getTimestamp().getTime().getTime() > lastUpdate)
                            lastUpdate = aFile.getTimestamp().getTime().getTime();

                    }
                }
            }

            info[0] = totalDirs;
            info[1] = totalFiles;
            info[2] = totalSize;
            info[3] = lastUpdate;

            return info;
        } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable ex) {
            logger.error(ex,ex);
            return info;
        }
    }


    public static JSONArray getDirectoryFilesFields(FtpServer.FtpClientWrapper ftpClient,
                                                    1.5.0/docs/api/java/lang/String.html">String parentDir, 1.5.0/docs/api/java/lang/String.html">String currentDir) throws 1.5.0/docs/api/java/io/IOException.html">IOException {
        return getDirectoryFilesFields(ftpClient, parentDir, currentDir,parentDir);
    }

    private static JSONArray getDirectoryFilesFields(FtpServer.FtpClientWrapper ftpClient,
                                                1.5.0/docs/api/java/lang/String.html">String parentDir, 1.5.0/docs/api/java/lang/String.html">String currentDir, 1.5.0/docs/api/java/lang/String.html">String startDir) throws 1.5.0/docs/api/java/io/IOException.html">IOException {

        JSONArray subArray = new JSONArray();

        printMem();

        1.5.0/docs/api/java/lang/String.html">String dirToList = parentDir;
        if (!currentDir.equals("")) {
            dirToList += "/" + currentDir;
        }

        try {

            FTPFile[] subFiles = ftpClient.listFiles(dirToList);

            if (subFiles != null && subFiles.length > 0) {
                for (FTPFile aFile : subFiles) {
                    1.5.0/docs/api/java/lang/String.html">String currentFileName = aFile.getName();
                    if (currentFileName.equals(".")
                            || currentFileName.equals("..")) {
                        // skip parent directory and the directory itself
                        continue;
                    }

                    //System.out.println("dir:" +currentDir+ aFile.getName());
                    if (aFile.isDirectory()) {
                        //System.out.println("dir:" +currentDir+ aFile.getName());
                        JSONArray subDirInfo =
                                getDirectoryFilesFields(ftpClient, dirToList, currentFileName,startDir);
                        for(int i = 0; i < subDirInfo.length();i++)
                            subArray.put(subDirInfo.getJSONObject(i));

                    } else {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("fileCompletePath",parentDir + "/" + currentDir + "/" + aFile.getName());
                        jsonObject.put("fileCompletePathEncoded",URIUtil.encodePath(parentDir + "/" + currentDir + "/" + aFile.getName(), "ISO-8859-1"));

                        jsonObject.put("file",parentDir.substring(startDir.length()) + "/" + currentDir + "/" + aFile.getName());
                        jsonObject.put("filename",aFile.getName());
                        jsonObject.put("contenttype", MimeTypeGuesser.getInstance().guessMimeType(aFile.getName()));
                        jsonObject.put("size",aFile.getSize());
                        jsonObject.put("lastmodified",aFile.getTimestamp().getTime().getTime());
                        jsonObject.put("lastmodifieddate", DatesWebUtils.getStringFromDate(aFile.getTimestamp().getTime()));
                        jsonObject.put("extension", FilesUtils.getExtension(aFile.getName()));


                        subArray.put(jsonObject);
                    }
                }
            }


            return subArray;
        } catch (1.5.0/docs/api/java/lang/Throwable.html">Throwable ex) {
            logger.error(ex,ex);
            return subArray;
        }
    }
}