NfsFile.java :  » Portal » Open-Portal » com » sun » portal » netfile » servlet » java1 » Java Open Source

Java Open Source » Portal » Open Portal 
Open Portal » com » sun » portal » netfile » servlet » java1 » NfsFile.java
/** 
 * $Id: NfsFile.java,v 1.39 2005/11/30 11:26:35 ss150821 Exp $ 
 * Copyright 2002 Sun Microsystems, Inc. All 
 * rights reserved. Use of this product is subject 
 * to license terms. Federal Acquisitions: 
 * Commercial Software -- Government Users 
 * Subject to Standard License Terms and 
 * Conditions. 
 * 
 * Sun, Sun Microsystems, the Sun logo, and Sun ONE 
 * are trademarks or registered trademarks of Sun Microsystems, 
 * Inc. in the United States and other countries. 
 */

package com.sun.portal.netfile.servlet.java1;

import com.sun.xfile.*;
import com.sun.portal.log.common.PortalLogger;
import java.io.*;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.logging.*;
import java.text.SimpleDateFormat;

class NfsFile {
    private static Logger logger=PortalLogger.getLogger (NfsFile.class);
    public static boolean SHOULD_HAVE_READ_PERMISSION = true;
    public static boolean SHOULD_NOT_HAVE_READ_PERMISSION = false;
    public static final String encoding = "UTF8";
    private static final int[] ia_unable_to_login = new int[] { -1, -1 };
    private String s_machine_encoding;

    private com.sun.xfile.XFileInputStream instream = null;
    private com.sun.xfile.XFileOutputStream outstream = null;
    protected int i_number_of_directories_traversed; //Keep track of number of directories scanned during single instance of a search

    private native boolean doNativeAuth(String username, String password)
        throws Exception;

    public native int[] getUserInfo(String user_name) throws Exception;
    static {
        if (System.getProperty("os.name").indexOf("indows") == -1) {
            System.loadLibrary("getpwnam");
        }
    }
    private NetFileLogManager logMgr;
    NfsFile(NetFileLogManager log_Mgr, String s_machine_encoding) {
        this.logMgr = log_Mgr;
        this.s_machine_encoding = s_machine_encoding;
        i_number_of_directories_traversed = 0;
    }

    NfsFile(NetFileLogManager log_Mgr, String s_machine_encoding, int authPort) {
        this(log_Mgr, s_machine_encoding);
    }

    int[] getUserIDs(String user_name, String password) throws NetFileException {
        int[] i_ids = ia_unable_to_login;
        try {
            i_ids = getUserInfo(new String(user_name.getBytes(), "UTF8"));
        } catch (java.io.UnsupportedEncodingException e) {
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "unsupported_character_encoding");
        } catch (Exception e) {
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "unable_to_do_unix_login");
        }
        if (i_ids[0] == -1) {
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "error44");
        }
        return i_ids;
    }
    String mkdir(
        String machine,
        String share,
        String user_name,
        String password,
        String target_dir,
        String directory_to_create,
        NetFileResource nfr_user_locale_i18n_bucket) throws NetFileException {
        if (!doAuthenticate(user_name, password))
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "nf.2");

        try {
            int[] i_ids = getUserIDs(user_name, password);
            com.sun.xfile.XFile xf_parent_dir = getXFile(
                share,
                machine,
                target_dir,
                true,
                SHOULD_HAVE_READ_PERMISSION,
                i_ids);
            if (!(xf_parent_dir.canWrite())) {
                throw new NetFileException(new String[] {
                        NetFileException.KEY_IDENTIFIER_PREFIX
                            + "no_write_permission_to_parent",
                        NetFileException.KEY_IDENTIFIER_PREFIX
                            + "textseperator", xf_parent_dir.getPath() });
            }

            com.sun.xfile.XFile xfile = getXFile(
                share,
                machine,
                target_dir + "/" + directory_to_create,
                false,
                SHOULD_NOT_HAVE_READ_PERMISSION,
                i_ids);
            if (!xfile.mkdir()) {
                throw new NetFileException(
                    NetFileException.KEY_IDENTIFIER_PREFIX
                        + "could_not_create_directory");
            }
        } catch (Exception e) {
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "could_not_create_directory");
        }
        return nfr_user_locale_i18n_bucket.getString("warning52");
    }

    String[] getNFSDir(
        String username,
        String password,
        String VMSnam,
        String machname,
        String dir_nam,
        String tmpdir,
        NetFileResource nfr_user_locale_i18n_bucket) throws NetFileException {
        if (!doAuthenticate(username, password))
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "nf.2");

        int[] i_ids = getUserIDs(username, password);
        com.sun.xfile.XFile xfile = getXFile(
            VMSnam,
            machname,
            dir_nam,
            true,
            SHOULD_HAVE_READ_PERMISSION,
            i_ids);
        String[] sa_files_list = xfile.list();
        String[] sa_listing = null;

        if (sa_files_list == null) {
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "unable_to_get_listing_error");
        } else {
            sa_listing = new String[sa_files_list.length * 4];
            for (int i = 0, j = 0; i < sa_files_list.length; ++i) {
                com.sun.xfile.XFile xf_curr_file = new com.sun.xfile.XFile(
                    xfile,
                    sa_files_list[i]);
                if (xf_curr_file.isFile()) {
                    sa_listing[j] = "-";
                } else {
                    sa_listing[j] = "d";
                }
                ++j;
                sa_listing[j] = xf_curr_file.getName();
                ++j;
                sa_listing[j] = (new Long(xf_curr_file.length())).toString();
                ++j;
                Date d = new java.util.Date(xf_curr_file.lastModified());
                SimpleDateFormat sdf = new SimpleDateFormat(
                    "MMM dd yy, hh:mm a");
                sdf.setCalendar(new GregorianCalendar(TimeZone.getDefault()));
                sa_listing[j] = sdf.format(d);
                ++j;
            }
        }
        if (sa_listing == null) {
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "unable_to_get_listing_error");
        }
        return sa_listing;
    }

    String getNFSFile(
        String username,
        String password,
        String VMSname,
        String machname,
        String mainfilename,
        String dir_nam,
        String tmpdir,
        NetFileResource nfr_user_locale_i18n_bucket) throws NetFileException {
        File temp_file = null;
        byte[] buffer = new byte[8 * 1024];

        if (!doAuthenticate(username, password))
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "nf.2");

        try {
            int[] i_ids = getUserIDs(username, password);
            com.sun.xfile.XFile xfile = getXFile(VMSname, machname, dir_nam
                + "/"
                + mainfilename, true, SHOULD_HAVE_READ_PERMISSION, i_ids);
            com.sun.xfile.XFileInputStream xfis_file = new com.sun.xfile.XFileInputStream(
                xfile);
            Long time = new Long(System.currentTimeMillis());
            String s_temp_file = tmpdir
                + "/"
                + time.toString()
                + username.toUpperCase()
                + mainfilename;
            temp_file = new File(s_temp_file);
            temp_file.createNewFile();
            FileOutputStream fops_tmp = new FileOutputStream(temp_file);
            int c = 0;
            while ((c = xfis_file.read(buffer)) > -1) {
                fops_tmp.write(buffer, 0, c);
            }
            fops_tmp.close();
            xfis_file.close();
            fops_tmp = null;
            xfis_file = null;
            xfile = null;
            time = null;
            temp_file = null;
            return s_temp_file;
        } catch (Exception e) {
            //            logger.log(Level.SEVERE, "Error in putting NFS File",e);
            logger.log(Level.SEVERE, "PSSRNF_CSPNSJ1082");
            return "ERROR:" + e.getMessage();
        } finally {
            if (temp_file != null) {
                try {
                    temp_file.delete();
                } catch (Exception e) {
                }
                temp_file = null;
            }
        }
    }

    String[] search(
        String usernam,
        String passwrd,
        String machnam,
        String VMSnam,
        String pattern,
        String dir_nam,
        String domainname,
        int maxsrchdir,
        NetFileResource nfr_user_locale_i18n_bucket) throws NetFileException {
        return search(
            usernam,
            passwrd,
            machnam,
            VMSnam,
            pattern,
            dir_nam,
            maxsrchdir,
            nfr_user_locale_i18n_bucket);
    }

    String[] search(
        String usernam,
        String passwrd,
        String machnam,
        String VMSnam,
        String pattern,
        String dir_nam,
        int maxsrchdir,
        NetFileResource nfRes) throws NetFileException {

        if (!doAuthenticate(usernam, passwrd))
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "nf.2");

        int[] i_ids = getUserIDs(usernam, passwrd);
        com.sun.xfile.XFile xfile = getXFile(
            VMSnam,
            machnam,
            dir_nam,
            true,
            false,
            i_ids);
        String s_prefix = "nfs://" + machnam;
        int i_prefix_length = s_prefix.length();
        if (xfile.isFile()) {
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "cannot_search_a_file");
        }
        java.util.ArrayList v_search_results = new java.util.ArrayList();
        search(
            xfile,
            maxsrchdir,
            i_prefix_length,
            v_search_results,
            pattern,
            i_ids);
        if (i_number_of_directories_traversed > maxsrchdir) {
            String[] searchResults = new String[v_search_results.size() + 1];
            searchResults[0] = "EXCEED:" + nfRes.getString("maxSearch");
            for (int j = 1; j < searchResults.length; j++) {
                searchResults[j] = (String) v_search_results.get(j - 1);
            }
            return searchResults;
        }

        String[] sa_resulsts = new String[v_search_results.size()];
        for (int i = 0; i < v_search_results.size(); ++i) {
            sa_resulsts[i] = (String) (v_search_results.get(i));
        }
        return sa_resulsts;
    }

    void search(
        com.sun.xfile.XFile xfile,
        int maxsrchdir,
        int i_prefix_length,
        java.util.ArrayList v_search_results,
        String pattern,
        int[] i_ids) throws NetFileException {
        ++i_number_of_directories_traversed;
        //        logger.info(this+":Directory number being searched="+i_number_of_directories_traversed);
        Object[] params1 = { ":Directory number being searched=",
                new Integer(i_number_of_directories_traversed) };
        logger.log(Level.INFO, "PSSRNF_CSPNSJ1083", params1);
        if (i_number_of_directories_traversed > maxsrchdir) {
            return;
        }
        if (xfile.isFile()) {
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "cannot_search_a_file");
        }
        String[] sa_contents = xfile.list();
        String s_path = xfile.toString();
        if (sa_contents == null) {
            v_search_results.add("Permission denied :"
                + s_path.substring(i_prefix_length, s_path.length()));
        } else {
            for (int i = 0; ((i < sa_contents.length) && (!(i_number_of_directories_traversed > maxsrchdir))); ++i) {
                String s_current_path = s_path + "/" + sa_contents[i];
                com.sun.xfile.XFile x_file = null;
                try {
                    x_file = getXFile(s_current_path, true, false, i_ids);
                } catch (Exception e) {
                }
                if (sa_contents[i].indexOf(pattern) > -1) {
                    String path = x_file.toString().substring(
                        i_prefix_length,
                        x_file.toString().length());
                    if (x_file.isDirectory()) {
                        path += "/";
                    }
                    v_search_results.add(path);
                }
                if (x_file.isDirectory()) {
                    if (x_file.canRead()) {
                        search(
                            x_file,
                            maxsrchdir,
                            i_prefix_length,
                            v_search_results,
                            pattern,
                            i_ids);
                    } else {
                        v_search_results.add("Permission denied :"
                            + x_file.toString().substring(
                                i_prefix_length,
                                x_file.toString().length()));
                    }
                }
            }
        }
    }
    String delNFSFile(
        String username,
        String password,
        String VMSname,
        String machname,
        String mainfilename,
        String dir_nam,
        String tmpdir,
        NetFileResource nfr_user_locale_i18n_bucket) throws NetFileException {
        if (!doAuthenticate(username, password))
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "nf.2");

        try {
            int[] i_ids = getUserIDs(username, password);
            com.sun.xfile.XFile xf_parent_directory = getXFile(
                VMSname,
                machname,
                dir_nam,
                true,
                SHOULD_HAVE_READ_PERMISSION,
                i_ids);
            if (!xf_parent_directory.canWrite()) {
                throw new NetFileException(
                    new String[] { NetFileException.KEY_IDENTIFIER_PREFIX
                        + "no_write_permission_to_parent" });
            }
            com.sun.xfile.XFile xf_file = getXFile(VMSname, machname, dir_nam
                + "/"
                + mainfilename, true, SHOULD_HAVE_READ_PERMISSION, i_ids);
            if (!xf_file.canWrite()) {
                throw new NetFileException(
                    new String[] { NetFileException.KEY_IDENTIFIER_PREFIX
                        + "no_write_permission" });
            }
            xf_file.delete();
        } catch (Exception e) {
            //            logger.log(Level.SEVERE, "Error in putting NFS File",e);
            logger.log(Level.SEVERE, "PSSRNF_CSPNSJ1084");
            return "ERROR:" + e.getMessage();
        }
        return nfr_user_locale_i18n_bucket.getString("info5");
    }

    private String getFileURL(String VMSnam, String machname, String dir_nam) {
        StringBuffer sb_file_pointer = new StringBuffer("nfs://");
        sb_file_pointer.append(machname);
        sb_file_pointer.append(VMSnam);
        sb_file_pointer.append(dir_nam);
        return sb_file_pointer.toString();
    }

    public com.sun.xfile.XFileOutputStream getNFSOutputStream(
        String username,
        String password,
        String machname,
        String VMSname,
        String remotefil_arg,
        String dir_nam) throws NetFileException {

        return this.getNFSOutputStream(
            username,
            password,
            machname,
            VMSname,
            remotefil_arg,
            dir_nam,
            false);
    }

    public com.sun.xfile.XFileOutputStream getNFSOutputStream(
        String username,
        String password,
        String machname,
        String VMSname,
        String remotefil_arg,
        String dir_nam,
        boolean append) throws NetFileException {

        if (!doAuthenticate(username, password))
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "nf.2");

        try {
            int[] i_ids = getUserIDs(username, password);
            com.sun.xfile.XFile xf_parent_dir = getXFile(
                VMSname,
                machname,
                dir_nam,
                true,
                SHOULD_HAVE_READ_PERMISSION,
                i_ids);

            if (!(xf_parent_dir.canWrite())) {
                throw new NetFileException(new String[] {
                        NetFileException.KEY_IDENTIFIER_PREFIX
                            + "no_write_permission_to_parent",
                        NetFileException.KEY_IDENTIFIER_PREFIX
                            + " : "
                            + xf_parent_dir.getPath() });
            }

            com.sun.xfile.XFile xfile = getXFile(VMSname, machname, dir_nam
                + "/"
                + remotefil_arg, false, SHOULD_NOT_HAVE_READ_PERMISSION, i_ids);

            if (append)
                outstream = new XFileOutputStream(xfile, append);
            else
                outstream = new XFileOutputStream(xfile);

            return outstream;
        } catch (Exception e) {
            //            logger.log(Level.SEVERE, "Error in getting output stream for NFS File",e);
            logger.log(Level.SEVERE, "PSSRNF_CSPNSJ1085");

            if (e instanceof NetFileException)
                throw (NetFileException) e;
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + e.getMessage());
        }
    }

    public com.sun.xfile.XFileInputStream getNFSInputStream(
        String username,
        String password,
        String VMSname,
        String machname,
        String mainfilename,
        String dir_nam) throws Exception, NetFileException {
        if (!doAuthenticate(username, password))
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "nf.2");

        int[] i_ids = getUserIDs(username, password);
        com.sun.xfile.XFile xfile = getXFile(VMSname, machname, dir_nam
            + "/"
            + mainfilename, true, SHOULD_HAVE_READ_PERMISSION, i_ids);

        instream = new com.sun.xfile.XFileInputStream(xfile);
        return instream;
    }

    public void closeNfsFile() throws IOException {
        if (instream != null)
            instream.close();
        if (outstream != null)
            outstream.close();

        instream = null;
        outstream = null;
    }

    private com.sun.xfile.XFile getXFile(
        String s_nfs_url,
        boolean b_file_should_exist,
        boolean b_is_read_allowed,
        int[] i_ids) throws NetFileException {
        com.sun.xfile.XFile xfile = new com.sun.xfile.XFile(s_nfs_url);
        com.sun.nfs.XFileExtensionAccessor nfsx = new com.sun.nfs.XFileExtensionAccessor(
            xfile);
        int i_uid = i_ids[0];
        int i_gid = i_ids[1];
        int[] i_gids = new int[] { i_gid };
        nfsx.loginUGID(i_uid, i_gid, i_gids);
        if (b_file_should_exist) {
            if (!(xfile.exists())) {
                throw new NetFileException(new String[] { xfile.getPath(), " ",
                        NetFileException.KEY_IDENTIFIER_PREFIX + "not_found" });
            } else {
            }
        }

        if (b_is_read_allowed) {
            if (!xfile.canRead()) {
                throw new NetFileException(new String[] {
                        xfile.getPath(),
                        " ",
                        NetFileException.KEY_IDENTIFIER_PREFIX
                            + "no_read_permission" });
            }
        }
        return xfile;
    }

    private com.sun.xfile.XFile getXFile(
        String VMSName,
        String machname,
        String file,
        boolean b_file_should_exist,
        boolean b_is_read_allowed,
        int[] i_ids) throws NetFileException {
        if (!VMSName.startsWith("/")) {
            VMSName = ("/" + VMSName);
        }
        if (!file.startsWith("/")) {
            file = ("/" + file);
        }
        String s_nfs_url = getFileURL(VMSName, machname, file);
        return getXFile(
            s_nfs_url,
            b_file_should_exist,
            b_is_read_allowed,
            i_ids);
    }

    void rename(
        String username,
        String password,
        String machine,
        String share,
        String directory,
        String old_file_name,
        String new_file_name) throws NetFileException {
        if (!doAuthenticate(username, password))
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "nf.2");

        try {
            int[] i_ids = getUserIDs(username, password);
            com.sun.xfile.XFile xf_parent_directory = getXFile(
                share,
                machine,
                directory,
                true,
                SHOULD_HAVE_READ_PERMISSION,
                i_ids);
            if (!xf_parent_directory.canWrite()) {
                throw new NetFileException(new String[] {
                        NetFileException.KEY_IDENTIFIER_PREFIX
                            + "no_write_permission_to_parent",
                        NetFileException.KEY_IDENTIFIER_PREFIX
                            + "textseperator", " ",
                        xf_parent_directory.getPath() });
            }
            com.sun.xfile.XFile xf_file = getXFile(share, machine, directory
                + "/"
                + old_file_name, true, SHOULD_HAVE_READ_PERMISSION, i_ids);
            if (!xf_file.canWrite()) {
                throw new NetFileException(new String[] {
                        NetFileException.KEY_IDENTIFIER_PREFIX
                            + "no_write_permission",
                        NetFileException.KEY_IDENTIFIER_PREFIX
                            + "textseperator", " ", xf_file.getPath() });
            }
            XFile xf_renamed_file = new XFile(
                xf_parent_directory,
                new_file_name);
            if (xf_renamed_file.exists()) {
                if (!xf_renamed_file.canWrite()) {
                    throw new NetFileException(new String[] {
                            NetFileException.KEY_IDENTIFIER_PREFIX
                                + "no_write_permission",
                            NetFileException.KEY_IDENTIFIER_PREFIX
                                + "textseperator", " ",
                            xf_renamed_file.getPath() });
                }
            }
            xf_file.renameTo(xf_renamed_file);
        } catch (Exception e) {
            //            logger.log(Level.SEVERE, "Error in putting NFS File",e);
            logger.log(Level.SEVERE, "PSSRNF_CSPNSJ1086");
            throw new NetFileException(NetFileException.KEY_IDENTIFIER_PREFIX
                + "problem_rename_file");
        }
    }

    boolean doAuthenticate(String username, String passwd)
        throws NetFileException {
        try {
            String osname = System.getProperty("os.name");
            //            logger.info("OS detected is:" + osname);
            Object[] params5 = { osname };
            logger.log(Level.INFO, "PSSRNF_CSPNSJ1087", params5);
            if (osname.indexOf("Linux") != -1 || osname.indexOf("SunOS") != -1) {
                //                logger.info("Trying to do Native UNIX Auth");
                logger.info("PSSRNF_CSPNSJ1088");
                boolean ret = false;
                ret = doNativeAuth(username, passwd);

                //                logger.info("Native Auth code returned: " + ret);
                Object[] params7 = { new Boolean(ret) };
                logger.log(Level.INFO, "PSSRNF_CSPNSJ1089", params7);
                return ret;
            } else {
                //TODO: use pcnfs for authentication
                //                logger.info("Not UNIX OS, so not authenticating");
                logger.info("PSSRNF_CSPNSJ1090");
                return true;
            }
        } catch (Exception e) {
            //            logger.log(Level.SEVERE, "NfsFile, Exception while authenticating, ",e);
            logger.log(Level.SEVERE, "PSSRNF_CSPNSJ1091");
            return false;
        }
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.