head	1.6;
access;
symbols
	TIGRIS_NOV_12_2000:1.5
	OLDHELM:1.5.0.2
	TIGRIS_NOV_11_2000:1.5
	TIGRIS_SEP_13_2000:1.4.0.2
	TIGRIS_BASELINE:1.4;
locks; strict;
comment	@# @;


1.6
date	2000.11.12.23.12.08;	author dlr;	state dead;
branches;
next	1.5;

1.5
date	2000.09.29.19.55.46;	author dlr;	state Exp;
branches;
next	1.4;

1.4
date	2000.09.20.03.13.16;	author brian;	state Exp;
branches;
next	1.3;

1.3
date	2000.04.18.00.10.34;	author jrobbins;	state Exp;
branches;
next	1.2;

1.2
date	2000.02.03.04.21.32;	author jrobbins;	state Exp;
branches;
next	1.1;

1.1
date	2000.01.30.01.59.38;	author jrobbins;	state Exp;
branches;
next	;


desc
@@


1.6
log
@Does not exist in newhelm.
@
text
@/* ================================================================
 * Copyright (c) 2000 CollabNet.  All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * 
 * 1. Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 
 * 2. Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 
 * 3. The end-user documentation included with the redistribution, if
 * any, must include the following acknowlegement: "This product includes
 * software developed by Collab.Net (http://www.Collab.Net/)."
 * Alternately, this acknowlegement may appear in the software itself, if
 * and wherever such third-party acknowlegements normally appear.
 * 
 * 4. The hosted project names must not be used to endorse or promote
 * products derived from this software without prior written
 * permission. For written permission, please contact info@@collab.net.
 * 
 * 5. Products derived from this software may not use the "Tigris" name
 * nor may "Tigris" appear in their names without prior written
 * permission of Collab.Net.
 * 
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL COLLAB.NET OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ====================================================================
 * 
 * This software consists of voluntary contributions made by many
 * individuals on behalf of Collab.Net.
 */


package org.tigris.helm.database;

import javax.servlet.*;

import java.util.*;
import com.sun.java.util.collections.*;
import java.sql.*;
import org.tigris.helm.tool.UpdateException;
import org.tigris.helm.tool.TigrisUpdate;

public class ProjectPrivs {
    /**
     * An array of the names of the privileges
     */
    private static String[] optList = {
	//"grant_priv",
	//"modules_priv",
	//"config_priv",
	"checkout_priv", 
	"commit_priv"

    };
    protected List initPrivList() {
	return Arrays.asList(optList);
    }


  private static HashMap optTable;
  static {
    // Initialize the list of privileges. Eventually this should probably
    // be serialized. For now this will do.
    optTable = new HashMap(optList.length);
    //optTable.put("grant_priv",
    //"grant privileges for this project to other users");
    //optTable.put("modules_priv",
    //"add, edit, remove modules in this project");
    //optTable.put("config_priv", "configure project properties");
    optTable.put("checkout_priv",
		  "read all non-private CVS modules in this project");
    optTable.put("commit_priv",
		  "write to all non-private CVS modules in this project");
  };
  protected Map initPrivTable() {
    return optTable;
  }

  public static class PPEntry {
    private String name;
    private boolean value;
	
    PPEntry(String optName, boolean val) {
	name = optName;
	value = val;
    }

    /**
     * Get the internal name of this option. This generally corresponds
     * to the database column this name is found under
     */
    public String getName() { return name; }
    /**
     * Returns a short description of this option, usually about
     * a sentence in length.
     */
    public String getText() { return (String)optTable.get(name); }
    /**
     * Obtain the default value of this option.  All values default to false.
     *
     * @@return true if and only if the option exists and is valid
     */
    public boolean getValue() { return value; }
  } /* end class PPEntry */

  /**
   * Returns a List of ProjectPrivs.PPEntry entries for the
   * default values for a mailing list for the boolean options.
   */
  public static List getDefaultValues() {
    PPEntry[] opts = new PPEntry[optList.length];
    for (int i = 0; i < optList.length; i++)
	    opts[i] = new PPEntry(optList[i], false);
    return Arrays.asList(opts);
  }

  /**
   * A list of the names of the privileges. They should correspond
   * to the columns of the privilege table, and should map to the keys
   * of the privTable table below.
   */
  private List privList = initPrivList();

  /**
   * The current privileges. The keys are the names of the privs.
   * The values are instances of class Boolean (true for Y)
   */
  private HashMap privValues;

  
  /**
   * A map with the (db) names of the privileges as keys and
   * a short description of them as values.
   */
  private Map privTable = initPrivTable();

  /**
   * Does a row for this set of privileges exist in the table?
   */
  protected boolean rowExists;

  /**
   * The table used to find the current privileges in.
   */
  private String tableName;
  
  /**
   * Non-boolean list option: list owner (null if none)
   */
  private String owner;

  /**
   * Non-boolean list option: sublist of another list (null if main list)
   */
  private String subList;

  private Connection connection;

  /**
   * A Map containing as keys Strings naming the columns of the
   * database table named in tableName used to identify uniquely
   * the row of the table for this instance, and as values Strings
   * giving the proper value for the mapped key.
   */
  private Map queryMap;

  public static class ProjectDoesNotExist extends Exception {
    private ProjectDoesNotExist(String project) {
	    super("Project " + project + " does not exist");
    }
    private ProjectDoesNotExist() {
	    super("Project does not exist");
    }
  } /* end class ProjectDoesNotExist */ 

  /**
   * Create a new ProjectPrivs object based on the given mailing list. 
   *
   * @@param project the project
   *
   * @@exception DoesNotExist if the mailing list does not exist
   * @@exception SQLException if there is a database error
   */
  public ProjectPrivs(Connection connection, String username, String project)
    throws SQLException, ProjectDoesNotExist {
    
    queryMap = mpQueryMap(username, project);
    tableName = "project_privs";
    this.connection = connection;
    
    StringBuffer cols = new StringBuffer();
    for (Iterator i = privList.iterator(); i.hasNext();) {
	    cols.append((String)i.next());
	    if (i.hasNext())
        cols.append(',');
    }
    
    Statement s = connection.createStatement();
    ResultSet r = s.executeQuery("SELECT " + cols + " FROM " + tableName
                                 + " WHERE " + whereQuery());
    
    rowExists = r.next();
    
    // Fill up the privValues table with either the results from the
    // database, or default values if no row exists
    privValues = new HashMap(privList.size());
    for (ListIterator i = privList.listIterator(); i.hasNext();) {
	    int idx = i.nextIndex();
	    String name = (String)i.next();
	    privValues.put(name, new Boolean(rowExists
                                       ? r.getString(idx+1).equals("Y")
                                       : false));
    }
    
  }

  private static Map mpQueryMap(String username, String project) {
    HashMap queryMap = new HashMap(3);
    queryMap.put("username", username);
    queryMap.put("project", project);
    return queryMap;
  }


    /**
     * Returns a List of PEntry objects that represent the
     * domain privileges for this object
     *
     * @@see ProjectPrivs.PEntry
     */
    public List getPrivList() {
	return Arrays.asList(getPrivArray());
    }

    public PPEntry[] getPrivArray() {
	PPEntry[] privs = new PPEntry[privList.size()];
	for (ListIterator i = privList.listIterator(); i.hasNext();) {
	    int idx = i.nextIndex();
	    String priv = (String) i.next();
	    privs[idx] = new PPEntry(priv,
				     Boolean.TRUE.equals(privValues.get(priv)));
	}
	return privs;
    }

  /**
   * Returns a List of Strings corresponding to the names of the
   * privileges
   */
  public List getPrivNames() {
    return Collections.unmodifiableList(privList);
  }

  /**
   * Changes a privilege. This method presumes the privilege is a
   * valid name; if not, an SQL error may occur.
   *
   * @@param privilege the name of the privilege to change
   * @@param value true if and only if the given privilege should exist
   */
  public void setPrivilege(String privilege, boolean value)
    throws SQLException {
    Statement s = connection.createStatement();
    
    // only bother changing if we're making a change
    if (value == getPrivilege(privilege))
	    return;
    
    if (rowExists) {
	    s.executeUpdate("UPDATE " + tableName + " SET " + privilege
                      + " = '" + (value ? 'Y' : 'N') + "' WHERE "
                      + whereQuery());
    } else {
	    StringBuffer insertCols = new StringBuffer();
	    StringBuffer insertVals = new StringBuffer();
	    insertQuery(insertCols, insertVals);
      
	    // Note that both strings now end with a comma. We use this fact
	    // below.
      
	    s.executeUpdate("INSERT INTO " + tableName + " (" + insertCols
                      + privilege + ") VALUES (" + insertVals
                      + (value ? "'Y'" : "'N'") + ')');
	    rowExists = true;
    }
    
    privValues.put(privilege, new Boolean(value));
  }

  /**
   * Generate the appropriate columns and values for an INSERT statement.
   * Matching comma-seperated lists of colums and values will be written
   * into the StringBuffer objects passed as arguments. Both strings
   * will be comma-terminated, to allow for another column/value to
   * be present after them with ease.
   *
   * <p>The StringBuffer arguments should be empty when this function
   * is called; the function simply appends to them, and does not clear
   * the values first.
   *
   * @@param insertCols an allocated StringBuffer for the columns
   * @@param insertVals an allocated StringBuffer for the values
   */
  protected void insertQuery(StringBuffer insertCols,
                             StringBuffer insertVals) {
    Iterator i = queryMap.entrySet().iterator();
    while (i.hasNext()) {
	    Map.Entry entry = (Map.Entry)i.next();
	    insertCols.append((String)entry.getKey());
	    insertCols.append(',');
	    insertVals.append('\'');
	    insertVals.append((String)entry.getValue());
      insertVals.append("',");
    }
  }

  /**
   * Generate the appropriate WHERE statement for this query, not
   * including the "WHERE" phrase. For example, for the privileges
   * for user <code>akosut</code>, this method would return
   * "username = 'akosut'"
   */
  protected String whereQuery() {
    StringBuffer query = new StringBuffer();
    
    Iterator i = queryMap.entrySet().iterator(); 
    while (i.hasNext()) {
	    Map.Entry entry = (Map.Entry)i.next();
	    query.append((String)entry.getKey());
	    query.append(" = '");
	    query.append((String)entry.getValue());
	    query.append('\'');
	    if (i.hasNext())
        query.append(" AND ");
    }
    
    return query.toString();
  }


  

  /**
   * Returns the value of the given privilege
   *
   * @@param privilege the name of the privilege to query
   * @@return true if and only if the privilege exists and is valid
   */
  public boolean getPrivilege(String privilege) {
    try {
      return ((Boolean)privValues.get(privilege)).booleanValue();
    } catch (NullPointerException e) {
      return false;
    }
  }
  
  /**
   * Returns a short (sentence-long) description of the abilities
   * granted by the given privilege
   *
   * @@param privilege the name of the privilege to describe
   * @@return a description, or null if the named privilege does not exist
   */
  public String getDescription(String privilege) {
    return (String)privTable.get(privilege);
  }
  
} /* end class ProjectPrivs */
@


1.5
log
@Collab.Net --> CollabNet in copyright.
@
text
@@


1.4
log
@
Obtained from:
Submitted by:
Reviewed by:

Moved from org.helm to org.tigris.helm
Moved from org/helm to org/tigris/helm

perl -pi.bak -e, how I love thee

note: this update was done POST-CVS-REPOSITORY surgury.  In order to
get this right, you may need to remove the directories

$CVSROOT/helm/java/org/helm
$CVSROOT/helm/data/htdoc/look/www/org/helm
$CVSROOT/helm/templates/org/helm

before doing the "CVS update" call, since those directories don't
exist anymore and CVS will try to create lockfiles for you in them,
giving you an error.
@
text
@d2 1
a2 1
 * Copyright (c) 2000 Collab.Net.  All rights reserved.
@


1.3
log
@switched from collections2.jar to collections.jar
@
text
@d48 1
a48 1
package org.helm.database;
d55 2
a56 2
import org.helm.tool.UpdateException;
import org.helm.tool.TigrisUpdate;
@


1.2
log
@Added tigris.org license
PR:
Obtained from:
Submitted by:
Reviewed by:
@
text
@d53 1
@


1.1
log
@initial checking
@
text
@d1 46
a46 1
// Copyright (c) 2000 Collab.Net, Inc. All Rights Reserved.
@

