Results 1 to 16 of 16
Like Tree1Likes
  • 1 Post By DarrylBurke

Thread: Java Based Application to Map Network Drive

  1. #1
    Wraithier is offline Member
    Join Date
    Jun 2008
    Posts
    10
    Rep Power
    0

    Default Java Based Application to Map Network Drive

    I have been working on this application for a couple weeks now and I'm running into a few problems I need some help/advice on. This application is supposed to make it easier (yes I know it's not hard) to map a network drive for users at my work who don't know how to do so. The users will choose from 3 potential usernames, will input the terminal name, and the password, which is the same for all will be input for them. All the variable are passing except for terminal name, whenever I run the program the entry for the terminal is being passed as null, a secondary problem is that currently the program tries to log on for all 3 usernames every time it is run. Any insight into what I am doing wrong would be greatly appreciated. I have posted my code below but obviously the usernames and password have been changed.

    Java Code:
    import java.awt.event.*;
    import javax.swing.*;
    
    
    
    public class MapDrive extends javax.swing.JFrame implements ActionListener, ItemListener {
        
        
        
        
        
        JFrame frame;
        public javax.swing.JTextField CompName; 
        public javax.swing.JButton ConnectButton;
        public javax.swing.JLabel LblCompName;
        public javax.swing.JLabel UsernameLbl;
        public javax.swing.JComboBox Username;
            
           
        static String usernames[] = {"Username1", "Username2", "Username3"}; //username
        static String password = ("password");  //password
        public String terminal; //The Compname
        public String username; //The Username
        
        
        
        public MapDrive() {       
            
            CompName = new javax.swing.JTextField();
            LblCompName = new javax.swing.JLabel();
            ConnectButton = new javax.swing.JButton();
            UsernameLbl = new javax.swing.JLabel();
            Username = new javax.swing.JComboBox(usernames);      
            Username.setSelectedIndex(-1);     
            Username.addActionListener(this);
            Username.addItemListener(this);        
            ConnectButton.addActionListener(this);
            
            this.setLocationRelativeTo(null);
            
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Map Network Drive");
            setName("Connect"); 
            setResizable(false);
    
            LblCompName.setText("Computer Name");
    
            ConnectButton.setText("Connect");
    
            UsernameLbl.setText("Username");       
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(55, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(LblCompName)
                        .addComponent(UsernameLbl))
                    .addGap(42, 42, 42)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(Username, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(CompName, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))
                    .addGap(95, 95, 95))
                .addGroup(layout.createSequentialGroup()
                    .addGap(138, 138, 138)
                    .addComponent(ConnectButton)
                    .addContainerGap(160, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap(47, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(LblCompName)
                        .addComponent(CompName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(Username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(UsernameLbl))
                    .addGap(33, 33, 33)
                    .addComponent(ConnectButton)
                    .addGap(60, 60, 60))
            );
    
            pack();
            
        }     
       
       public void connect()
       {       
       Drives dr = new Drives();
       dr.scanDrives();
       dr.getFreeDrive();
       dr.run();   
       } 
          
       public void error()
       {             
           if (CompName.getText().isEmpty() == true)
           {
               JOptionPane.showMessageDialog(MapDrive.this, "Please Input a Computer Name","Error", JOptionPane.ERROR_MESSAGE);              
           }          
           else
           {
               terminal = CompName.getText(); 
           } 
           if (Username.getSelectedItem() == null)
           {
             JOptionPane.showMessageDialog(MapDrive.this, "Please Select a Username","Error", JOptionPane.ERROR_MESSAGE);  
           }
       } 
       
       public void setVariable()
       {
               terminal = CompName.getText();
       }
       
         
        public void actionPerformed(ActionEvent e) {        
            if (e.getSource() == ConnectButton) 
            { 
                        
              error();
              connect(); 
                     
              System.out.println(terminal); 
              System.out.println(username);
              System.out.println(password);
              
            }
            
        } 
        
        public void itemStateChanged( ItemEvent event ){
            if (event.getSource() == Username && event.getStateChange() == ItemEvent.SELECTED )
            {
                System.out.println( "Change:"+ Username.getSelectedItem() );
                username = (String) Username.getSelectedItem();
            }
        }
        
        
         public static void main(String args[]){ 
           MapDrive md = new MapDrive();
           md.setVisible(true);
        }
    }

  2. #2
    Wraithier is offline Member
    Join Date
    Jun 2008
    Posts
    10
    Rep Power
    0

    Default

    Here is the second .java file that contains most of the functions.

    Java Code:
    import java.io.*;
    import java.util.Hashtable;
    
    /**
    * Maintains the list of available drives
    */
    public class Drives implements Runnable
    {
        
           	public String terminal;  // the terminal
    
    	public boolean connected = false;  // tells if the conection to this terminal was possible or not
    	        
    	public boolean finished = false;  // tels if the thread has finished its work
            
    	Hashtable drives = new Hashtable();        
    	public Drives()
    	{
    		scanDrives();
    	}
    
    	/**
    	* Scan the available drives with the "net use drive:" command
    	*/
    	public void scanDrives()
    	{
    		for (char ch='Z'; ch > 'F'; ch--)
    		{
    			String command = "net use " + ch + ":";
    			String result = runCommand(command);
    
    			// if found a free drive
    			if (result.toUpperCase().indexOf(ch+":") == -1)
    			{
    				// add it to the list
                                    //System.out.println(result.toUpperCase().indexOf(ch+":") == -1);
    				drives.put(""+ch, new Boolean(true));
    			}
    		}
    	}
    
    	/**
    	* @return the first free drive found
    	*/
    	public synchronized String getFreeDrive()
    	{
    		for (char ch='Z'; ch > 'F'; ch--)
    		{
    			Boolean res = (Boolean)(drives.get(""+ch));
    			if (res != null && res.booleanValue())
    			{
    				// set the free drive found as busy
                                
                                    
                                    setBusyDrive(""+ch);				
    				return ""+ch;
    			}
    		}
    
    		return null;
    	}
    
    	/**
    	* Sets this drive as free and available to be used
    	*/
    	public synchronized void setFreeDrive(String drive)
    	{
    		drives.put(drive, new Boolean(true));
    	}
    
    	/**
    	* Sets the drive as busy and unavailable
    	*/
    	public synchronized void setBusyDrive(String drive)
    	{
    		drives.put(drive, new Boolean(false));
    	}
            
            public void run()
    	{
    		System.out.println("Start thread ");
    
    		String drive;
    
    		while (true)
    		{
    			// get an available drive letter
                            
    			drive = getFreeDrive();
    			if (drive != null)
    			{
    				break;
    			}
    
    			// if no drive letter found, sleep for 5 sec then try again
    			try
    			{
    				Thread.sleep(5000);
    				System.out.println("Waiting for a free drive");
    			} catch (InterruptedException e1)
    			{
    			}
    		}
    
    		// connect with the given list of passwords
    		for (int i = 0; i < MapDrive.usernames.length; i++)
    		{
    			boolean success = mapDrive(drive, terminal, MapDrive.usernames[i],
    			MapDrive.password);
    
    			// if connection is successful, break
    			if (success)
    			{
    				connected = true;
    				break;
    			}
    		}
    
    		// if no connection was possible, log and quit thread
    		if (!connected)
    		{
    			System.out.println("Connection to " + terminal + " failed");
    		}
    		else // if connection possible
    		{
    			System.out.println("Connected to " + terminal);
    
    		}
    
    		// at the end disconnect the drive and free it
    		disconnectDrive(drive);
    		setFreeDrive(drive);
    
    		// mark thread status as finished
    		finished = true;
    	}
            
         private void disconnectDrive(String drive)
    	{
    		String command = "net use " + drive + ": /delete";
    		runCommand(command);
    	}
                    
          private boolean mapDrive(String drive, String terminal, String user,
    	String pwd)
    	{
    		String command = null;
    
    		if (user == null)
    		{
    			command = "net use " + drive + ": \\\\" + terminal + "\\C$ ";
    		} else
    		{
    			command = "net use " + drive + ": \\\\" + terminal + "\\C$ " + pwd
    			+ " /user:" + user;
    		}
    		return runCommandToBoolean(command);
    	}
          
          public static String runCommand(String param)
    	{
    		try
    		{
    			StringBuffer sb = new StringBuffer();
    			Process process = Runtime.getRuntime().exec(param);
    			InputStream standardInput = process.getInputStream();
    			BufferedReader br = new BufferedReader(new InputStreamReader(
    			standardInput));
    			InputStream standardError = process.getErrorStream();
    			BufferedReader brError = new BufferedReader(new InputStreamReader(
    			standardError));
    			//OutputStream standardOutput = process.getOutputStream();
    			String s;
    
    			while ((s = br.readLine()) != null)
    			{
    				sb.append(s + "\n");
    			}
    
    			while ((s = brError.readLine()) != null)
    			{
    				sb.append(s + "\n");
    			}
    
    			standardInput.close();
    			standardError.close();
    			return sb.toString();
    		}
    		catch (Exception e)
    		{
    			System.out.println(e);
    			return null;
    		}
    	}
          
          public static boolean runCommandToBoolean(String param)
    	{
    		try
    		{
    			boolean flag = false;
    			System.out.println("Running: " + param);
    			StringBuffer sb = new StringBuffer();
    			Process process = Runtime.getRuntime().exec(param);
    			InputStream standardInput = process.getInputStream();
    			BufferedReader br = new BufferedReader(new InputStreamReader(
    			standardInput));
    			InputStream standardError = process.getErrorStream();
    			BufferedReader brError = new BufferedReader(new InputStreamReader(
    			standardError));
    			//OutputStream standardOutput = process.getOutputStream();
    			String s;
    			while ((s = br.readLine()) != null)
    			{
    				sb.append(s + "\n");
    				flag = true;
    			}
    			while ((s = brError.readLine()) != null)
    			{
    				sb.append(s + "\n");
    				flag = false;
    			}
    			standardInput.close();
    			standardError.close();
    			return flag;
    		} catch (Exception e)
    		{
    			System.out.println(e);
    			return false;
    		}
    	}
    }

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    Too much code to wade thru.
    You need to use some debugging techniques.
    Add some println() to the code to show where and what.
    Run the code and look at the output to see what is happening.

  4. #4
    Wraithier is offline Member
    Join Date
    Jun 2008
    Posts
    10
    Rep Power
    0

    Default

    I am using some println(), I know what is happening the variable I have for the terminal isn't being passed somehow and I can't figure out why. The println()s allow me to see what variable is the problem, but they don't allow me to see why. There really isn't that much code, I posted it all in case someone wants to copy/paste it and see what it does. A lot of the MapDrive stuff is the GUI a lot of the functionality is in the Drives file, I was just hoping someone could help me identify exactly what is wrong with my variable, because after hours I just don't see what it is.

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    "the variable I have for the terminal isn't being passed somehow"

    Where is this happening? Could you identify the lines of code with a comment?
    Something like: //**** Here the variable is null but should NOT be*****
    "allow me to see what variable is the problem"
    What variable IS THE PROBLEM?

  6. #6
    Wraithier is offline Member
    Join Date
    Jun 2008
    Posts
    10
    Rep Power
    0

    Default

    The variable terminal. The user inputs this information and the program gets it with .getText. I successfully save the text in the CompName using .getText, I then have to pass this information from MapDrive.java to Drives.Java, it is successfully saved in MapDrive.java (I know this because of a println(), but when I try to use the same information again in Drives.Java the println() comes out as null...basically I get Y: \\null\\username\\password where null is supposed to be whatever is held in the variable terminal. Hopefully that helps, but again I'm not sure if I'm passing the variable incorrectly or what. Thanks for your help so far.

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    If you could put those comments in the code and post that, it would help. Otherwise its too much scrolling up and down.
    How does the value of terminal get from MapDrive (where its saved) to Drives where it is null? I don't see where terminal is passed or referenced!
    Where is the constructor for Drives?

  8. #8
    Wraithier is offline Member
    Join Date
    Jun 2008
    Posts
    10
    Rep Power
    0

    Default

    Thanks for all your help Norm, I guess that is the problem. How do I go about passing the variable from the text field (CompName) in MapDrive to Drives? Both variables have the same name (Terminal) but I need to pass the value from MapDrive to Drives.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    One way would be via Drives Constructor:
    Java Code:
     ... = new Drives(terminal);
    ...
    
      public Drives(String t) {
          terminal = t:
     ...

  10. #10
    Wraithier is offline Member
    Join Date
    Jun 2008
    Posts
    10
    Rep Power
    0

    Default

    would something like

    Java Code:
    MapDrive md = new MapDrive();
            
    public String terminal = md.CompName.getText();
    This would be in the Drives.java something like :

    Java Code:
    public class Drives implements Runnable
    {
            MapDrive md = new MapDrive();
            
            public String terminal = md.CompName.getText();
    
    	public boolean connected = false;  // tells if the conection to this terminal was possible or not
    	        
    	public boolean finished = false;  // tels if the thread has finished its work      
               
            Hashtable drives = new Hashtable();
    work? I'm not exactly sure how to use the constructor to get the info from the text field. Use Drives constructor? I am trying to pass the info from MapDrives, which is assigned to the variable terminal. The value of terminal is determined by what the user inputs in the text field, this value then needs to be passed to Drives and used in the methods. So bascially the user inputs a computer name (terminal) and then the program maps the drives using net use commands. Sorry I am still fairly new at this and want to make sure I am understanding correctly.
    Last edited by Wraithier; 07-02-2008 at 03:48 PM.

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    How does the program run? Is this the way: It starts by creating the GUI in MapDrives, the user enters the terminal and then the Drives object is created. At this point you have the terminal value and need to pass it to the Drives object. You'd do that as I suggested above, by using the Drives constructor.

    If you don't know how to use constructors and as basic as that is to Java programming, I'd suggest you find a java programming text and read up some before continuing. You are going to have LOTS of cases like this to solve and you need some basic understanding of how to create classes.

    Good luck.
    Norm

  12. #12
    Wraithier is offline Member
    Join Date
    Jun 2008
    Posts
    10
    Rep Power
    0

    Default

    Thanks for your help again Norm. I was blowing the whole thing out of proportion. All I changed was this:
    Java Code:
    boolean success = mapDrive(drive, terminal, MapDrive.usernames[i],
    			MapDrive.password);
    to this

    Java Code:
    boolean success = mapDrive(drive, MapDrive.terminal, MapDrive.usernames[i],
    			MapDrive.password);
    I was forgetting to add in MapDrive. Now it's working.

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    A comment: Using public static isn't considered a good OOP technique. It's better to use methods/constructors to pass data from one class to another.

  14. #14
    Wraithier is offline Member
    Join Date
    Jun 2008
    Posts
    10
    Rep Power
    0

    Default

    Thanks for the advice, I am pretty new at this so I appreciate any good programming tips.

  15. #15
    Hendry is offline Member
    Join Date
    May 2012
    Posts
    3
    Rep Power
    0

    Default Re: Java Based Application to Map Network Drive

    I have try this code, but I got the follow error. Connect to server failed. How to set the value of terminal?

    Change:6067
    Start thread
    Running: net use Y: \\\\10.215.127.241\test\C$ 123456 /user:6067
    Running: net use Y: \\\\10.215.127.241\test\C$ 123456 /user:6067
    Running: net use Y: \\\\10.215.127.241\test\C$ 123456 /user:6067
    Connection to \\10.215.127.241\test failed
    \\10.215.127.241\test
    6067
    123456

  16. #16
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default Re: Java Based Application to Map Network Drive

    When you have a question, start your own thread. Don't post to an old dead thread and don't hijack another poster's thread.

    I'm closing this thread, it's nearly 4 years old.

    db

    THREAD CLOSED
    quad64bit likes this.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. i need an example of JSR179 ((Location based Ser)implementation for CDC based device
    By talk_to_vivekmishra in forum CDC and Personal Profile
    Replies: 3
    Last Post: 12-30-2010, 10:07 AM
  2. best Java Network API to use?
    By San_Andreas in forum Networking
    Replies: 1
    Last Post: 04-30-2008, 08:42 PM
  3. Replies: 0
    Last Post: 03-25-2008, 12:45 AM
  4. (Location based Service) application for Pocket PC
    By talk_to_vivekmishra in forum CLDC and MIDP
    Replies: 0
    Last Post: 08-14-2007, 08:23 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •