alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is Forte for Java, Community Edition. The Initial
 * Developer of the Original Code is Sun Microsystems, Inc. Portions
 * Copyright 1997-2000 Sun Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.modules.javacvs.passwd;

/**
 *
 * @author  mkleint
 */

import org.openide.filesystems.*;
import org.openide.util.*;

import org.netbeans.modules.javacvs.util.*;
import org.netbeans.lib.cvsclient.connection.*;
import org.netbeans.modules.javacvs.commands.ClientCreationException;

import java.io.*;
import java.net.*;
import java.beans.PropertyVetoException;
import java.util.LinkedList;
import java.util.ListIterator;

/** The purpose of this class is to handle everything around pserver authentication 
 * and the .cvspass file stuff. It finds, reads and writes to the file. If the configuration is not found in the file,
 * it can connect to the server and check it. Then adds the item to the .cvspass file
 */

public class CVSPasswd extends Object {
    private Debug E=new Debug("CVSPasswd", true); // NOI18N
    private Debug D=E;
    PrintWriter bf;
    
//    private static CVSPasswd instance;
                                                                                                                                                                  
    /** The standard name of the file, where CVS stores passwords and cvs root directories
     * (for pserver type of connection only)
 */
    public static final String STD_FILE = ".cvspass"; //NOI18N
    private LinkedList entries = new LinkedList();
    private PasswdEntry lastEntry;
//    private volatile String homeDir = System.getProperty("user.home");
    
    private File passFile = null;
    /** Creates new CVSPasswd */

    private CVSPasswd(File fil) {
      passFile = fil;
//      loadPassFile();
    }    
    
    public CVSPasswd(String dir, String fileName) {
      String sep = File.separator;  
/*      if (File.separatorChar == '\\') {
         sep = "\\\\";
      } else {
      }           
 */
      passFile = new File(dir, fileName);
    }

    public CVSPasswd(String dirAndFile) {
      this(new File(dirAndFile));
    }

    
    /** This is the preffered constuctor. Since it tries to do the standard cvs way
     * of finding the .cvspass file. For  Windoze we need to add some backslashes. 
     * 
     */
    
/*    public CVSPasswd() {
      JavaCvsSettings settings = (JavaCvsSettings)SharedClassObject.findObject(
                                       JavaCvsSettings.class, true); 
      String dir = settings.getCvsHome().getAbsolutePath();
      String sep = File.separator;  
//      if (File.separatorChar == '\\') {
//         sep = "\\\\";
//         D("win!");
//      } else {
//      }           
 
      passFile = new File(dir, STD_FILE);
//      System.out.println("passfile = " + passFile.getAbsolutePath());
 //     D("HOME=" +dir + sep + STD_FILE);
        
    }
 */
    
/*    public static CVSPasswd getInstance() {
        if (instance != null) { 
           return instance;
        }
        instance = new CVSPasswd();
        return instance;
    }
 */
    
    /** This method tries to find out the path to the .cvspass file. Generally it does just
 * look for the user.home property. On Windoze it's a bit more complicated. 
 * Due to the 2-face nature of the system (Win/DOS) we need to look for the DOS env variables.
 * these are not accessible from java alone. Thus we need to run an external java program in the command shell,
 * and it'll read the enviroment variables we need (HOME or HOMEDRIVE+HOMEPATH). 
 * if not found this way, we return the user.home at least.
 * @return the found path to the user's home directory.
 */
/*    public String getHome() {
        if (Utilities.isWindows()) {
           Process proc=null;
           Thread stdoutThread=null;
           Thread stderrThread=null;
            try {    
                try {
                    String loc = File.separator + "modules" + File.separator + "javacvs.jar";
                    String command = "cmd /c \"java -DHOME=%HOME% -DHOMEPATH=%HOMEPATH% -DHOMEDRIVE=%HOMEDRIVE% -cp " 
                    + System.getProperty("netbeans.user") +  loc 
                    + File.pathSeparator + System.getProperty("netbeans.home") + loc
                    + " org.netbeans.modules.cvsclient.passwd.ExternalCheckHome \"";
                    proc=Runtime.getRuntime().exec(command);
                } catch (IOException e){
                    D.deb("Runtime.exec failed."); // NOI18N
                    homeDir = System.getProperty("user.home");
                }
                final BufferedReader out = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                stdoutThread = new Thread(
                new Runnable() {
                    public void run() {
                        try {  
                            homeDir = out.readLine();
                        } catch (IOException io) {
                            D.deb("Error reading output of ExternalCheckHome");    
                            homeDir = System.getProperty("user.home");
                        }      
                    }                               
                }
                );            
                stdoutThread.start();
                int exit=proc.waitFor();
                D.deb("exit=" + exit);
                stdoutThread.join();
                if (homeDir == null) { 
                     homeDir =  System.getProperty("user.home");}
                else if (homeDir.equals("")) { 
                    homeDir =  System.getProperty("user.home");}    
            } catch (InterruptedException inter) {
                stdoutThread.stop();
                long stopTimeout=1000;
                try{
                    stdoutThread.join(stopTimeout);
                }catch (InterruptedException e){
                }  
                proc.destroy();
                homeDir =  System.getProperty("user.home");
                D.deb("interrupted!");
            }     
            return homeDir;  
        }    
        else { //IT is not windows
            homeDir =  System.getProperty("user.home");
            D.deb("is not windows!");
            return homeDir;
        }  
    }    
  */
    
    /** Reads the .cvspass file.
     */ 
    
    public boolean loadPassFile() throws ClientCreationException {
      entries = new LinkedList();  
      if (!passFile.exists()) {
          try {
              passFile.createNewFile();
          } catch (IOException exc) {
             ClientCreationException exc2 = new ClientCreationException("Error creating .cvspass file",  //NOI18N
                org.openide.util.NbBundle.getMessage(CVSPasswd.class, "CVSPasswd.errorCreatingPass", passFile.getAbsolutePath())); //NOI18N
//??             throw exc2;
          }
      }
      BufferedReader bf = null;
      try {
        bf = new BufferedReader(new FileReader(passFile.getAbsolutePath()));
        String line;
        do {
          line = bf.readLine();
          D.deb("cvspass line=" + line); //NOI18N
          if (line != null) {
            PasswdEntry entr = new PasswdEntry();
            boolean ok = entr.setEntry(line);
            if (!ok) {  //TODO - corrupted line prolly ignore (should write back or skip?)
//              E.err("Line corrupted. (.cvspass file)"); //NOI18N
              continue;
            }
            entries.add(entr);
          }  
        } while (line != null); 
      } catch (IOException exc) {
         ClientCreationException exc2 = new ClientCreationException("Error reading .cvspass file",  //NOI18N
             org.openide.util.NbBundle.getMessage(CVSPasswd.class, "CVSPasswd.errorReadingPass", passFile.getAbsolutePath())); //NOI18N
         D.deb(".cvspass reading error"); //NOI18N
         if (bf != null) {
             try {
                bf.close();
             } catch (IOException clEx) {
                 // Ignore
             }
         }    
         throw exc2;
      } finally {
         if (bf != null) {
             try {
                bf.close();
             } catch (IOException clEx) {
                 // Ignore
             }
         }
      }
      return true;
    }
    
    /** Writes the current passwd database to the .cvspass file.
     */
    public boolean savePassFile() throws ClientCreationException {
      try {
//        if (!passFile.canWrite()) return false;
        bf = new PrintWriter(new BufferedWriter(new FileWriter(passFile.getAbsolutePath(), false)));
        ListIterator it = entries.listIterator();
        while (it.hasNext()) {
          PasswdEntry ent = (PasswdEntry)it.next();
          bf.println(ent.getEntry(true));
        } 
        bf.close();
        
      } catch (IOException exc) {
         ClientCreationException exc2 = new ClientCreationException("Error writing .cvspass file",  //NOI18N
             org.openide.util.NbBundle.getMessage(CVSPasswd.class, "CVSPasswd.errorWritingPass", passFile.getAbsolutePath())); //NOI18N
         D.deb(".cvspass writing error:" +passFile.getAbsolutePath()); //NOI18N
         if (bf != null) {
            bf.close();
         }                               
         throw exc2;
      }
      return true;
    }

    /**
     * Remove the entry form the cvs pass file..
     */ 
    public boolean remove(String entry) {
            PasswdEntry old = find(entry);
            if (old != null) {
                return entries.remove(old);
            }
            return true;
    }

/** Adds a new entry into the dtabase. Will be written to the file after savePassFile is run.
 * @param entry - entry supplied by the Customizer
 * @param passwd unscrambled password for the account
 * @return the added PasswdEntry. if not added, then null.
 */
    public PasswdEntry add(String entry, String passwd) {
        PasswdEntry psw = new PasswdEntry();
        Scrambler scr = StandardScrambler.getInstance();
        boolean ok = psw.setEntry(entry + " " + scr.scramble(passwd));
        if (ok) {
            // remove old one with the same cvsroot first
            PasswdEntry old = find(entry);
            if (old != null) {
                entries.remove(old);
            }
            entries.add(psw);
            return psw;
        }
        return null;
    }
          
    public PasswdEntry add(String type, String user, String server, String root, int port, String passwd) {
      if (port != PServerConnection.DEFAULT_PORT) {
          String ent = ":" + type + ":" + user + "@" + server + ":" + port + root;  //NOI18N
          return add(ent, passwd); 
      }
      String ent = ":" + type + ":" + user + "@" + server + ":" + root;  //NOI18N
      return add(ent, passwd); 
    }
    
   
/** Looks for the  current setting (:pserver:username@server:/rootdir) in the database.
 * @return the found PasswdEntry, or if not found null.
 * @param current The current cvs root directory
 */
    public PasswdEntry find(String current) {
      D.deb("current=" + current); //NOI18N
      ListIterator it = entries.listIterator();
      PasswdEntry ent = null; 
      String toReturn = null;
      while (it.hasNext()) {
        ent = (PasswdEntry)it.next();
        if (ent.matchToCurrent(current)) {
          return ent;
        }
      }
      
      return null;
    }
    
    public java.util.Collection getAllEntries() {
        return this.entries;
    }

//--------------------------------------------------------------------------------------
// ------------------------- server check ----------------------------------------------
 
    /** The method connects to the server specified in the PasswdEntry parameter.
     * After opening, it does the authentification (See CVS cleint/server protocol).
     * Then it disconnects.
     * @return true if authentification succeed, othewise false.
     * @param toCheck The info about the Cvs root. (server + repository + user and password)
 */
    public boolean checkServer(PasswdEntry toCheck, int port) throws AuthenticationException {
       PServerConnection c = new PServerConnection();
       c.setUserName(toCheck.getUser());
       c.setEncodedPassword(toCheck.getPasswd());
       c.setHostName(toCheck.getServer());
       c.setRepository(toCheck.getRoot());
       c.setPort(port);
       c.verify();
       return true;
    }

    public static String scramble(String unScrambled) {
      Scrambler scr = StandardScrambler.getInstance();
      return scr.scramble(unScrambled);
    }
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.