tabooxchanz 0 Newbie Poster

Fellow Java Coders,
I recently got a project to do for my coursework in university which requires that me and my group members simulate a file manager similar to windows explorer but I guess not as complex. Here is a synopsis of what is required:

The members of this group were required to develop a Windows Program task manager written with a Java Graphical user Interface to view all system resources on our local machine. The user interface is expected to be event driven. It was outlined that simple Java iconic object type to create or import images as a part of the simulated interface. It is also expected to feature a creatively designed user interface following good Human Computer Interface guidelines.
Relevant permissions are to be assigned to users of the OS resources by way of an access control list. The permissions are expected to be such that you can grant r-w-x, r-w and r access to users.

A resource can become sharable from a multithreaded pool based on the access provided, that is, system resources could reside on a server and a java Web Client is utilised to communicate with the thread pool of objects from that Web server.

The program is also expected to dump all web client-server connectivity sessions, file reads and updates to a log table which the option to write the same data to an index file is also available. Users should be able to read from the log tables when called within the Java Application, either from the database or from the file. Permission to add or remove a log file is based on permission granted from within the access control list.
Any user with r-w-x privilege has mutual exclusive rights to the resource. Other users will be assigned access based on priority.

Here is what we have done so far but we have run into a number of problems (we created it in a project called Feather with 3 files; a table in access is also needed and a database connection called FeatherSource needs to be setup; to see the theme you also have to setup quaqua in project settings which is a .jar file...I will attach these files):

//Feather.java
package Feather;

//importing predifined methods/packages
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.Graphics;
import java.sql.*;


//Feather class 
public class Feather extends JFrame
{
		//label for username text field
		private JLabel lblUName = new JLabel("Username");
		//text field for username
    	private JTextField txtUName = new JTextField(20);
    	//label for password text field
    	private JLabel lblPWord = new JLabel ("Password");
    	//password field for password
    	private JPasswordField pwfPWord = new JPasswordField(20);
    	//button for logging in
    	private JButton btnLogin = new JButton ("Login");
    	//button for cancelling log in
    	private JButton btnCancel = new JButton ("Cancel");
    	private Image image;
    	//variables to store username and password
    	private String UserName, Password;
    	
    	
		private Connection featherConnect;
		private Statement featherStatement;
		
		//no-argument constructor to setup GUI
    	public Feather()
    	{
    	
    		super("Feather");
    		
    		Container container = getContentPane();
    		container.setLayout(new FlowLayout());
    		//adds label for username field to container
    		container.add(lblUName);
    		//adds text box for username field to container
    		container.add(txtUName);
    		//adds label for password field to container
    		container.add(lblPWord);
    		//adds text box for password field to container
    		container.add(pwfPWord);
    		
    		//Login Button
			btnLogin = new JButton("Login");
			//adds Login Button to container
			container.add(btnLogin);
			
			//Cancel Button
			btnCancel = new JButton("Cancel");
			//adds Cancel Button to container
			container.add(btnCancel);
    		
    		ActionHandler handler = new ActionHandler();
    		btnLogin.addActionListener(handler);
    		pwfPWord.addActionListener(handler);
    		
    		btnCancel.addActionListener(
    			new ActionListener()
    			{
    				public void actionPerformed(ActionEvent event)
    				{
    					System.exit(0);
    				}
    			}
    		);
    			
    		setSize(300, 300);
    		setVisible(true);
    		con();
    	
    			
    	}
    
    	
    	private class ActionHandler implements ActionListener
    	{
    		public void actionPerformed(ActionEvent buttonEvent)
    		{
    			if(buttonEvent.getSource() == btnLogin)
    			{
    				try
					{
						featherStatement = featherConnect.createStatement();
						String query = "SELECT User, Pword,Permissions FROM MyTable";
						ResultSet result = featherStatement.executeQuery(query);
			
						while (result.next())
						{
							//print the columns of the row that was retrieved
							UserName = result.getString(1);
							Password = result.getString(2);
							String perm = result.getString(3);
							if ((txtUName.getText().equals(UserName))&&(pwfPWord.getText().equals(Password)))
							{
    							setVisible(false);
    							FeatherFileManager ffm = new FeatherFileManager(UserName, perm);
								ffm.setSize(500,200);
								ffm.setVisible(true);
								ffm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    						}
    					}
    				}
    				catch (SQLException sqle)
					{
						sqle.printStackTrace();
					}	
    			}	
    		}
    	}
    	public void con()
		{
			/*the url specifiying the database to which this program connects using the JBDC to 
		 	connect to a Microsoft ODBC database */
		 	String url = "jdbc:odbc:FeatherSource";
		 	String userName = "";
		 	String password = "";
		 
		 	//Load the driver to allow connection to the database
			 try
		 	{
		 		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		 		featherConnect = DriverManager.getConnection(url, userName, password);
		 	}
		 	catch(ClassNotFoundException buttonEvent)
		 	{
		 		System.out.println("Failed to load JDBC/ODBC Driver");
		 		buttonEvent.printStackTrace();
		 		System.exit(1);
		 	}
		 	catch(SQLException sqle)
		 	{
		 		System.err.println("Unable to connect");
		 		sqle.printStackTrace();
		 	}
		}

    	
    	public static void main(String[] args) 
    	{
             System.setProperty("Quaqua.tabLayoutPolicy","wrap");
         
    		try 
    		{
      			UIManager.setLookAndFeel("ch.randelshofer.quaqua.QuaquaLookAndFeel");
    		}
    		catch (Exception e) 
    		{
          
    		}
    
    		Feather ft = new Feather();
    	}
    	

	
    	
}
//FeatherFileManager.java
package Feather;

//importing predifined methods/packages
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.tree.*;
import java.io.*;
import javax.swing.JComponent.*;
import java.awt.Container.*;
import java.awt.Component.*;
import java.sql.*;
import java.io.File;
import java.net.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.filechooser.*;
import java.net.URI;
import java.net.URISyntaxException;



//FeatherFileManager class
public class FeatherFileManager extends JFrame
{
	private TableColumn column;
	private JTable featherTable;
	private DefaultTableModel ftmodel;
	String permission;
	Connection featherConnect;
	Statement featherStatement;	
	String UN;
	private String filePath;
	Socket socket = null;
//	private ToolPanel toolPanel;
	
	//constructor to set-up GUI
	public FeatherFileManager(String UserName,String permtype)
	{
		super("Feather File Manager : " + UserName + " ("+permtype+")");
		
		UN = UserName;
		//File Menu
		JMenu fileMenu = new JMenu("File");
		fileMenu.setMnemonic('F');
		
		//Exit Menu Item on File Menu
		JMenuItem exitItem = new JMenuItem("Exit");
		exitItem.setMnemonic('x');
		
		//ActionListener for Exit Menu Item
		exitItem.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					System.exit(0);
				}
			}
		);
		
		//Menu Bar
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		menuBar.add(fileMenu);
		
		//Connect Menu
		JMenu connectMenu = new JMenu("Connect");
		connectMenu.setMnemonic('N');
		menuBar.add(connectMenu);
		
		//Edit Menu
		JMenu editMenu = new JMenu("Edit");
		editMenu.setMnemonic('E');
		menuBar.add(editMenu);
		
		//View Menu
		JMenu viewMenu = new JMenu("View");
		viewMenu.setMnemonic('W');
		menuBar.add(viewMenu);
		
		//Help Menu
		JMenu helpMenu = new JMenu("Help");
		helpMenu.setMnemonic('H');
		menuBar.add(helpMenu);
		
		//Logout Menu Item on File Menu
		JMenuItem logoutItem = new JMenuItem ("Log Out");
		logoutItem.setMnemonic('L');
		//Action Listener for Logout Menu Item
		logoutItem.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					setVisible(false);
					Feather ft = new Feather();
					ft.setSize(300,300);
					ft.setVisible(true);
				}
			}
		);
	
		JMenuItem openItem = new JMenuItem ("Open");
		openItem.setMnemonic('O');
	
		fileMenu.add(openItem);
		fileMenu.add(logoutItem);
		fileMenu.add(exitItem);
		
		//Add server menu item
		JMenuItem serverItem = new JMenuItem ("Connect as Server");
		serverItem.setMnemonic('S');
		
		
		//Adds client menu item
		JMenuItem clientItem = new JMenuItem ("Connect as Client");
		serverItem.setMnemonic('C');
			
		connectMenu.add(serverItem);
		connectMenu.add(clientItem);
		
		//Creates Scroll Pane for tree and table
		JScrollPane viewPermissions,viewTree;
		
		//Declares featherTree as type Tree
		JTree featherTree;
		
		DefaultTreeModel featherTreeModel;
		DefaultMutableTreeNode featherFolder = new DefaultMutableTreeNode("Feather");
		
		// Creates tree with root featherFolder
		featherTree=new JTree(featherFolder);
		
		featherTree.addMouseListener(
		new MouseAdapter()
		{
			
			public void mouseClicked(MouseEvent g)
			{
				setDirectory("e:\\Feather\\Feather\\Root\\");
			}
		}
		);
		
		// Maps root to root folder of the file system
		listAllFiles("e:\\Feather\\Feather\\Root\\", featherFolder,true);
		
		viewTree= new JScrollPane(featherTree);
		
		ftmodel= new DefaultTableModel();
		
		//Declares feather table as type JTable
		featherTable= new JTable(ftmodel)
		{
			public Class getColumnClass(int column)
			{
				return getValueAt(0, column).getClass();
			}
			public boolean isCellEditable(int rowIndex, int colIndex)
			{
				return false;
			}
			public Class getRowClass(int row)
			{
				return getValueAt(0, row).getClass();
			}
		};
		
		ftmodel.addColumn("");
		ftmodel.addColumn("Name");
		ftmodel.addColumn("Type");
		
		column = featherTable.getColumnModel().getColumn(0);
		column.setMaxWidth(30);
		column = featherTable.getColumnModel().getColumn(2);
		column.setPreferredWidth(10);
		column.setWidth(10);
		
		setDirectory("e:\\Feather\\Feather\\Root\\");
		
		featherTable.addMouseListener(
		new MouseAdapter()
		{
			int row_int;
			public void mouseClicked(MouseEvent e)
			{
				int r=featherTable.rowAtPoint(e.getPoint());
				String ffolder = (String) (ftmodel.getValueAt(r, 2));
				if (ffolder == "Folder")
				{
					filePath +=(String)  (ftmodel.getValueAt(r, 1)) + '\\';
					setDirectory(filePath);
					
				}
				else
				{
					String fileName = (String)(ftmodel.getValueAt(r,1));
					fileName = fileName + "." +(String) (ftmodel.getValueAt(r,2));
					String ffp = filePath + fileName;
					File file = new File(ffp);
					
					if(true)
					{
						fileName = (String) (ftmodel.getValueAt(r,1));
						fileName = '"'+fileName + '"'+(String) (ftmodel.getValueAt(r,2));
						ffp=filePath +fileName;
						file= new File(ffp);
						
						try
						{
							Runtime frun = Runtime.getRuntime();
							frun.exec("cmd /c start " + file);
						}
						catch(Throwable f)
						{
							
						}
					}
				}
				//JOptionPane.showMessageDialog(null,"Table in: ");
			}	
		
		}
		);
		
		viewPermissions=new JScrollPane(featherTable);
		getContentPane().add(viewPermissions, BorderLayout.CENTER);
		
		//Sets the size of scroll panes viewTree and view Permissions		
		viewTree.setMinimumSize(new Dimension(250, 500));
		viewPermissions.setMinimumSize(new Dimension(200, 500));
		viewTree.setPreferredSize(new Dimension(250, 500));
		viewPermissions.setPreferredSize(new Dimension(200, 500));
		
		//Adds scroll panes viewTree and view Permissions to Split pane
		JSplitPane featherPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, viewTree, viewPermissions);
		getContentPane().add(featherPane, BorderLayout.CENTER);
		
		//Connects to the database and allows the User to open a file based on the permissions they have
		con();
		openItem.addActionListener(
			new ActionListener()
			{
				public void actionPerformed(ActionEvent event)
				{
					try
					{
						featherStatement = featherConnect.createStatement();
						String query = "SELECT User,Pword, Permissions FROM MyTable";
						ResultSet result = featherStatement.executeQuery(query);
						
						while (result.next())
						{
							String Username = result.getString(1);
							String pw= result.getString(2);
							permission = result.getString(3);
							
							if ((UN).equals(Username)&&permission.equals("admin")||permission.equals("admim"))
							{
								featherfilelock();
							}
							else
							{
								featherfileunlock();
							}
							
						}
					}
					catch (SQLException sqle)
					{
						sqle.printStackTrace();
					}	
				}
			}
				
			
		);
	}
	
	//recursive function to create nodes for the tree
	public static void listAllFiles(String directory, DefaultMutableTreeNode parent, Boolean recursive)
	{
		
		File [] children = new File(directory).listFiles();
		for (int i = 0; i < children.length; i++)
		{
			DefaultMutableTreeNode node = new DefaultMutableTreeNode(children[i].getName());
			if (children[i].isDirectory()&& recursive)
			{
				parent.add(node);
				listAllFiles(children[i].getPath(),node,recursive);
			}
			else if (!children[i].isDirectory())
			{
				parent.add(node);
			}
		}
		
		
		
	}
	
	public void con()
	{
			/*the url specifiying the database to which this program connects using the JBDC to 
		 	connect to a Microsoft ODBC database */
		 	String url = "jdbc:odbc:FeatherSource";
		 	String userName = "";
		 	String password = "";
		 
		 	//Load the driver to allow connection to the database
			 try
		 	{
		 		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		 		featherConnect = DriverManager.getConnection(url, userName, password);
		 	}
		 	catch(ClassNotFoundException buttonEvent)
		 	{
		 		System.out.println("Failed to load JDBC/ODBC Driver");
		 		buttonEvent.printStackTrace();
		 		System.exit(1);
		 	}
		 	catch(SQLException sqle)
		 	{
		 		System.err.println("Unable to connect");
		 		sqle.printStackTrace();
		 	}	
	}	
	
	
	public void featherfilelock()
	{
		JOptionPane.showMessageDialog(null,"Please select a file");
		fileopen();
	}
	public static void featherfileunlock()
	{
		//JOptionPane.showMessageDialog(null,"You are not athorized for veiwing");
	}
	
	//Method to Open a file
	private void fileopen()
	{
		
		JFileChooser filechoose = new JFileChooser("C:\\users\\kimani\\desktop\\feather\\feather\\Root\\");
		filechoose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
		int result = filechoose.showOpenDialog( this );
		
		if ( result == JFileChooser.CANCEL_OPTION)
			{
		
			JOptionPane.showMessageDialog(null,"Goodbye");
			}
		//Opens a file
		if ( result == JFileChooser.APPROVE_OPTION)
		{
			//This try block checks to see if a file can be open 
			try
			{
				//Allow files that needs a different application to run in to be opened in the respective application
				Runtime featherRun = Runtime.getRuntime();
				featherRun.exec("cmd /c start " + filechoose.getSelectedFile());
			}
			catch(Throwable e)
			{
			
			}
		}
		
		File fileName = filechoose.getSelectedFile();
		
		if((fileName== null) || (fileName.getName().equals("")))
		{
			JOptionPane.showMessageDialog(this, "Invalid File Name","Invalid File Name",JOptionPane.ERROR_MESSAGE);
			//System.exit(1);
		}
	}
	
	// This is a recursive function list all the files in the directory and shows it in the table
	public void setDirectory(String dir)
	{
		filePath = dir;
		
		ftmodel.setNumRows(0);
		File ftfolder = new File(dir);
		
		if(ftfolder.listFiles() != null)
		{
			File[] listOfFiles =ftfolder.listFiles();
			for (int z=0; z< listOfFiles.length;z++)
			{
				if(listOfFiles[z].isFile()&& !listOfFiles[z].isHidden())
				{
				
					String fileName=listOfFiles[z].getName();
					int dotPos = fileName.lastIndexOf(".");
					String fileType = fileName.substring(dotPos);
					
					//String fileType = fileName.substring(0, fileName.lastIndexOf(".")+1);
					fileName = fileName.substring(0,fileName.lastIndexOf("."));
					
					Icon featherIcon = null;
					
					try
					{
						File ftfile= File.createTempFile("icon", "." +fileType);
						FileSystemView view = FileSystemView.getFileSystemView();
						featherIcon= view.getSystemIcon(ftfile);
						ftfile.delete();
					}
					catch(IOException e)
					{
						e.printStackTrace();
					}
					
					Object row[] ={featherIcon, fileName, fileType.toUpperCase()};
					
					ftmodel.addRow(row);
					
				}
				//This lists the files if they are directories
				else if(listOfFiles[z].isDirectory())
				{
					Icon icon= new ImageIcon("..\\icon.png");
					Object row[] = {icon, listOfFiles[z].getName(), "Folder"};
					ftmodel.addRow(row);
					
				}
				
				
			}
			
			
		}
		
		
		
	}
	
	

}
// Unrolled and not inlined version with 2 readers and 2 writers
// No data structure used for readers and writers to work with
// Specific notification locks are used to improve performance

class RWnotif {
  static Controller ctl;

  public static void main (String argv[]) {
    ctl = new Controller();

      new Reader1(ctl).start();
      new Reader2(ctl).start();
      new Writer1(ctl).start();
      new Writer2(ctl).start();
  }
}


final class Reader1 extends Thread {
  protected Controller ctl;

  public Reader1(Controller c) { ctl = c;}

  public void run()
  {
    while (true) {
      ctl.startRead();
      System.out.println("reader reading:");
      System.out.println("done reading");
      ctl.stopRead();
    }

  } // end public void run()
}
final class Reader2 extends Thread {
  protected Controller ctl;

  public Reader2(Controller c) { ctl = c;}

  public void run()
  {
    while (true) {
      ctl.startRead();
      System.out.println("reader reading:");
      System.out.println("done reading");
      ctl.stopRead();
    }
  } // end public void run()
}

final class Writer1 extends Thread {
  protected Controller ctl;

  public Writer1(Controller c) { ctl = c;}  

  public void run()  
  {  
    while (true) {
      ctl.startWrite();
      System.out.println("writer writing:");
      System.out.println("done writing");
      ctl.stopWrite();
    }
  } // end public void run()
}

final class Writer2 extends Thread {
  protected Controller ctl;
    
  public Writer2(Controller c) { ctl = c;}

  public void run()
  {
    while (true) {
      ctl.startWrite();
      System.out.println("writer writing:");
      System.out.println("done writing");
      ctl.stopWrite();
    }
  } // end public void run()
}


class Controller
{
    private int nr = 0;
    private int nw = 0;
    private Object or = new Object();
    private Object ow =  new Object();
   
    public void startRead()
    {
	synchronized(or)
	{
	    while(!checkRead())
		try{or.wait();
		   }catch(InterruptedException e){}
	}
    }

    private synchronized boolean checkRead()
    {
	if(nw == 0)
	{
	    nr++;
	    return true;
      	}
	else return false;
    }

    public void stopRead()
    {
	synchronized(this){nr--;}
	synchronized(ow){ow.notify();}
    }

    public void startWrite()
    {
	synchronized(ow)
	{
	    while(!checkWrite())
		try{ow.wait();
		   }catch(InterruptedException e) {}
	}
    }

    private synchronized boolean checkWrite()
    {
	if((nw == 0) && (nr == 0))
	{
	    nw++;
	    return true;
	}
	else return false;
    }

    public void stopWrite()
    {
	synchronized(this){nw--;}
	synchronized(or){or.notifyAll();}
	synchronized(ow){ow.notify();}
    }
}

If anyone can help sort out the bugs, which include:

+ We can't seem to get pics in the background even though the code seems to have no visible syntax or logic errors.
+ Changing the directories of each of the nodes in the tree is buggy.
+ Locking of files is also a problem.

I know this may be wordy and lengthy but I wanted to make sure that any one who can help understands what we are trying to accomplish...any HELP would be appreciated whether CODE SNIPPETS or by other means... THANK YOU to all those who take the time to read this. p.s. It is due this Friday.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.