Coverage Report - org.melati.admin.Admin
 
Classes in this File Line Coverage Branch Coverage Complexity
Admin
92%
276/297
88%
122/138
4.257
Admin$1
100%
3/3
N/A
4.257
Admin$2
100%
2/2
N/A
4.257
Admin$3
100%
2/2
N/A
4.257
Admin$3$1
100%
2/2
N/A
4.257
 
 1  
 /*
 2  
  * $Source: /usr/cvsroot/melati/melati/src/main/java/org/melati/admin/Admin.java,v $
 3  
  * $Revision: 1.154 $
 4  
  *
 5  
  * Copyright (C) 2000 William Chesters
 6  
  *
 7  
  * Part of Melati (http://melati.org), a framework for the rapid
 8  
  * development of clean, maintainable web applications.
 9  
  *
 10  
  * Melati is free software; Permission is granted to copy, distribute
 11  
  * and/or modify this software under the terms either:
 12  
  *
 13  
  * a) the GNU General Public License as published by the Free Software
 14  
  *    Foundation; either version 2 of the License, or (at your option)
 15  
  *    any later version,
 16  
  *
 17  
  *    or
 18  
  *
 19  
  * b) any version of the Melati Software License, as published
 20  
  *    at http://melati.org
 21  
  *
 22  
  * You should have received a copy of the GNU General Public License and
 23  
  * the Melati Software License along with this program;
 24  
  * if not, write to the Free Software Foundation, Inc.,
 25  
  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA to obtain the
 26  
  * GNU General Public License and visit http://melati.org to obtain the
 27  
  * Melati Software License.
 28  
  *
 29  
  * Feel free to contact the Developers of Melati (http://melati.org),
 30  
  * if you would like to work out a different arrangement than the options
 31  
  * outlined here.  It is our intention to allow Melati to be used by as
 32  
  * wide an audience as possible.
 33  
  *
 34  
  * This program is distributed in the hope that it will be useful,
 35  
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 36  
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 37  
  * GNU General Public License for more details.
 38  
  *
 39  
  * Contact details for copyright holder:
 40  
  *
 41  
  *     William Chesters <williamc At paneris.org>
 42  
  *     http://paneris.org/~williamc
 43  
  *     Obrechtstraat 114, 2517VX Den Haag, The Netherlands
 44  
  */
 45  
 
 46  
 package org.melati.admin;
 47  
 
 48  
 import java.util.Vector;
 49  
 import java.util.Enumeration;
 50  
 
 51  
 import javax.servlet.http.HttpServletResponse;
 52  
 
 53  
 import org.apache.commons.httpclient.Header;
 54  
 import org.apache.commons.httpclient.HttpClient;
 55  
 import org.apache.commons.httpclient.HttpMethod;
 56  
 import org.apache.commons.httpclient.methods.GetMethod;
 57  
 import org.apache.commons.httpclient.methods.HeadMethod;
 58  
 import org.apache.commons.httpclient.methods.PostMethod;
 59  
 import org.apache.commons.httpclient.methods.PutMethod;
 60  
 import org.melati.Melati;
 61  
 import org.melati.PoemContext;
 62  
 import org.melati.servlet.FormDataAdaptor;
 63  
 import org.melati.servlet.InvalidUsageException;
 64  
 import org.melati.servlet.Form;
 65  
 import org.melati.servlet.TemplateServlet;
 66  
 import org.melati.template.ServletTemplateContext;
 67  
 import org.melati.template.FormParameterException;
 68  
 
 69  
 import org.melati.poem.AccessToken;
 70  
 import org.melati.poem.AccessPoemException;
 71  
 import org.melati.poem.BaseFieldAttributes;
 72  
 import org.melati.poem.Capability;
 73  
 import org.melati.poem.Column;
 74  
 import org.melati.poem.ColumnInfo;
 75  
 import org.melati.poem.ColumnInfoTable;
 76  
 import org.melati.poem.ColumnTypePoemType;
 77  
 import org.melati.poem.Database;
 78  
 import org.melati.poem.DeletionIntegrityPoemException;
 79  
 import org.melati.poem.DisplayLevel;
 80  
 import org.melati.poem.ExecutingSQLPoemException;
 81  
 import org.melati.poem.Field;
 82  
 import org.melati.poem.FieldAttributes;
 83  
 import org.melati.poem.Initialiser;
 84  
 import org.melati.poem.Persistent;
 85  
 import org.melati.poem.PoemException;
 86  
 import org.melati.poem.PoemThread;
 87  
 import org.melati.poem.PoemTypeFactory;
 88  
 import org.melati.poem.ReferencePoemType;
 89  
 import org.melati.poem.Setting;
 90  
 import org.melati.poem.Table;
 91  
 import org.melati.poem.TableInfo;
 92  
 import org.melati.poem.TableInfoTable;
 93  
 import org.melati.poem.ValidationPoemException;
 94  
 
 95  
 import org.melati.util.CountedDumbPagedEnumeration;
 96  
 import org.melati.poem.util.EnumUtils;
 97  
 import org.melati.poem.util.MappedEnumeration;
 98  
 import org.melati.util.MelatiBugMelatiException;
 99  
 import org.melati.util.MelatiIOException;
 100  
 import org.melati.util.MelatiRuntimeException;
 101  
 
 102  
 /**
 103  
  * Melati template servlet for database administration.
 104  
  * <p>
 105  
  * This class defines {@link #doTemplateRequest(Melati, ServletTemplateContext)}
 106  
  * and methods it calls to interpret requests, depending on the current table
 107  
  * and object, if any.
 108  
  * <p>
 109  
  * Java methods with names ending "<code>Template</code>" and taking a
 110  
  * {@link ServletTemplateContext} and {@link Melati} as arguments are generally
 111  
  * called by {@link #doTemplateRequest(Melati, ServletTemplateContext)}) to
 112  
  * implement corresponding request methods.
 113  
  * {@link #modifyTemplate(ServletTemplateContext, Melati)} and associated
 114  
  * methods are slight variations.
 115  
  * <p>
 116  
  * {@link #adminTemplate(String)} is called in all cases
 117  
  * to return the template path. The name of the template is usually the same as
 118  
  * the request method but not if the same template is used for more than one
 119  
  * method or the template served depends on how request processing proceeds.
 120  
  * <p>
 121  
  * These methods are called to modify the context:
 122  
  * <ul>
 123  
  * <li>{@link #popupSelect(ServletTemplateContext, Melati)}</li>
 124  
  * </ul>
 125  
  * 
 126  
  * TODO Review working of where clause for dates
 127  
  * TODO Move Nav icons into PrimarySelect
 128  
  * TODO Make Chooser JS agnostic
 129  
  * TODO Make Navigation JS agnostic
 130  
  * TODO Logout fails to work if remember me is ticked
 131  
  * TODO Order by field f orders on fields troid, not field ordering
 132  
  * TODO Enable non-paged output of selection by adding paged parameter to selectionTemplate
 133  
  * FIXME primaryDisplayTable should not be static as this messes with DB switching
 134  
  */
 135  
 
 136  1
 public class Admin extends TemplateServlet {
 137  
 
 138  1
   private static String screenStylesheetURL = null;
 139  1
   private static String primaryDisplayTable = null;
 140  1
   private static String homepageURL = null;
 141  
 
 142  
   /**
 143  
    * Creates a row for a table using field data in a template context.
 144  
    */
 145  
   protected static Persistent create(Table<?> table,
 146  
       final ServletTemplateContext context) {
 147  7
     Persistent result = table.create(new Initialiser() {
 148  
       public void init(Persistent object) throws AccessPoemException,
 149  
           ValidationPoemException {
 150  7
         Form.extractFields(context, object);
 151  7
       }
 152  
     });
 153  7
     result.postEdit(true);
 154  7
     return result;
 155  
   }
 156  
 
 157  
   /**
 158  
    * Return the resource path for an admin template.
 159  
    */
 160  
   protected static String adminTemplate(String name) {
 161  404
     return "org/melati/admin/" + name;
 162  
   }
 163  
 
 164  
   /**
 165  
    * @return a DSD for the database
 166  
    */
 167  
   protected static String dsdTemplate(ServletTemplateContext context) {
 168  
     // Webmacro security prevents access from within template
 169  
 
 170  
     // Note: getPackage() can return null dependant upon
 171  
     // the classloader so we have to chomp the class name
 172  
 
 173  1
     String c = PoemThread.database().getClass().getName();
 174  1
     int dot = c.lastIndexOf('.');
 175  1
     String p = c.substring(0, dot);
 176  
 
 177  1
     context.put("package", p);
 178  1
     return adminTemplate("DSD");
 179  
   }
 180  
 
 181  
   /**
 182  
    * @return primary select template
 183  
    */
 184  
    @SuppressWarnings({ "unchecked", "rawtypes" })
 185  
   protected static String primarySelectTemplate(ServletTemplateContext context,
 186  
       Melati melati) throws PoemException {
 187  39
     final Table table = melati.getTable();
 188  
 
 189  
     Field<Object> primaryCriterion;
 190  
 
 191  39
     Column<?> column = table.primaryCriterionColumn();
 192  39
     if (column != null) {
 193  30
       String sea = context.getFormField("field_" + column.getName());
 194  30
       primaryCriterion = new Field<Object>(
 195  
           sea == null ? 
 196  
            (
 197  
             melati.getObject() == null ? 
 198  
                 null : column.getRaw(melati.getObject()))
 199  
           : column.getType().rawOfString(sea), 
 200  
           new BaseFieldAttributes(column,column.getType().withNullable(true)));
 201  30
     } else
 202  9
       primaryCriterion = null;
 203  
 
 204  39
     context.put("primaryCriterion", primaryCriterion);
 205  39
     return adminTemplate("PrimarySelect");
 206  
   }
 207  
 
 208  
 
 209  
   /**
 210  
    * Return template for a selection of records from a table.
 211  
    */
 212  
   protected static String selectionTemplate(ServletTemplateContext context,
 213  
       Melati melati) {
 214  53
     String templateName = context.getFormField("template");
 215  53
     if (templateName == null) {
 216  52
       selection(context, melati, true);
 217  52
       return adminTemplate("Selection");
 218  
     } else { 
 219  1
       selection(context, melati, false);
 220  1
       return adminTemplate(templateName);
 221  
     }
 222  
   }
 223  
 
 224  
   /**
 225  
    * Implements request to display a selection of records from a table in the
 226  
    * right hand pane.
 227  
    * 
 228  
    * @return SelectionRight template.
 229  
    */
 230  
   protected static String selectionRightTemplate(
 231  
       ServletTemplateContext context, Melati melati) {
 232  2
     selection(context, melati, true);
 233  2
     context.put("inRight", Boolean.TRUE);
 234  2
     return adminTemplate("Selection");
 235  
   }
 236  
 
 237  
   /**
 238  
    * Modifies the context in preparation for serving a template to view a
 239  
    * selection of rows.
 240  
    * <p>
 241  
    * Any form fields in the context with names starting "field_" are assumed to
 242  
    * hold values that must be matched in selected rows (if not null).
 243  
    * <p>
 244  
    * An encoding of the resulting whereClause is added to the context. "AND" is
 245  
    * replaced by an &amp; separator.
 246  
    * <p>
 247  
    * A form field with name "start" is assumed to hold the number of the start
 248  
    * row in the result set. The default is zero. The next 20 rows are selected
 249  
    * and added as to the context as "results".
 250  
    * 
 251  
    * @return The modified context.
 252  
    */
 253  
   @SuppressWarnings({ "unchecked", "rawtypes" })
 254  
   protected static ServletTemplateContext selection(
 255  
       ServletTemplateContext context, Melati melati, boolean paged) {
 256  57
     final Table<?> table = melati.getTable();
 257  
 
 258  57
     final Database database = table.getDatabase();
 259  
 
 260  
     // sort out search criteria
 261  
 
 262  57
     final Persistent criteria = table.newPersistent();
 263  
 
 264  57
     Vector<Object> whereClause = new Vector<Object>();
 265  
 
 266  57
     for (Enumeration<Column<?>> c = table.columns(); c.hasMoreElements();) {
 267  750
       Column<?> column = c.nextElement();
 268  750
       String name = "field_" + column.getName();
 269  750
       String fieldValue = Form.getFieldNulled(context, name);
 270  750
       if (fieldValue != null) {
 271  5
         column
 272  
             .setRaw_unsafe(criteria, column.getType().rawOfString(fieldValue));
 273  
 
 274  
         // FIXME Needs to work for dates
 275  5
         whereClause.addElement(name + "=" + melati.urlEncode(fieldValue));
 276  
       }
 277  750
     }
 278  
 
 279  57
     context.put("whereClause", EnumUtils.concatenated("&", whereClause
 280  
         .elements()));
 281  
 
 282  
     // sort out ordering 
 283  
 
 284  57
     ReferencePoemType searchColumnsType = getSearchColumnsType(database, table);
 285  
 
 286  57
     Vector<Object> orderings = new Vector<Object>();
 287  57
     Vector<Object> orderClause = new Vector<Object>();
 288  
 
 289  
     
 290  252
     for (int o = 1; o <= table.displayColumnsCount(DisplayLevel.summary); ++o) {
 291  195
       String name = "field_order-" + o;
 292  195
       String orderColumnIDString = Form.getFieldNulled(context, name);
 293  
       Integer orderColumnID;
 294  
 
 295  195
       if (orderColumnIDString != null) {
 296  10
         String toggleName = "field_order-" + o + "-toggle";
 297  10
         String orderColumnSortOrderToggle = Form.getFieldNulled(context,
 298  
             toggleName);
 299  10
         Boolean toggle = new Boolean(orderColumnSortOrderToggle);
 300  10
         orderColumnID = (Integer) searchColumnsType
 301  
             .rawOfString(orderColumnIDString);
 302  10
         ColumnInfo info = (ColumnInfo) searchColumnsType
 303  
             .cookedOfRaw(orderColumnID);
 304  10
         String desc = Boolean.TRUE.equals(info.getSortdescending()) ? (Boolean.TRUE
 305  
             .equals(toggle) ? "" : " DESC")
 306  
             : (Boolean.TRUE.equals(toggle) ? " DESC" : "");
 307  10
         orderings.addElement(database.quotedName(info.getName()) + desc);
 308  10
         orderClause.addElement(name + "=" + orderColumnIDString);
 309  
       }
 310  
     }
 311  
 
 312  57
     String orderBySQL = null;
 313  57
     if (orderings.elements().hasMoreElements())
 314  9
       orderBySQL = EnumUtils.concatenated(", ", orderings.elements());
 315  57
     context.put("orderClause", EnumUtils.concatenated("&", orderClause
 316  
         .elements()));
 317  
 
 318  57
     int start = 0;
 319  57
     String startString = Form.getFieldNulled(context, "start");
 320  57
     if (startString != null) {
 321  
       try {
 322  6
         start = Math.max(0, Integer.parseInt(startString));
 323  0
       } catch (NumberFormatException e) {
 324  0
         throw new MelatiBugMelatiException("How did you get that in there?",
 325  
             new FormParameterException("start", "Param must be an Integer"));
 326  6
       }
 327  
     }
 328  57
     if (paged) { 
 329  56
       final int resultsPerPage = 20;
 330  56
       context.put("results", 
 331  
                   new CountedDumbPagedEnumeration(
 332  
                           table.selection(criteria, orderBySQL, false, false),
 333  
                           start, resultsPerPage,
 334  
                           table.cachedCount(criteria, false, false).count())
 335  
       );
 336  56
     } else { 
 337  1
       context.put("results", table.selection(criteria, orderBySQL, false, false));
 338  
     }
 339  57
     return context;
 340  
   }
 341  
 
 342  
   /**
 343  
    * Implements the field search/selection request method.
 344  
    */
 345  
   protected static String popupSelectTemplate(ServletTemplateContext context,
 346  
       Melati melati) throws PoemException {
 347  3
     popupSelect(context, melati);
 348  3
     return adminTemplate("PopupSelect");
 349  
   }
 350  
 
 351  
   @SuppressWarnings({ "rawtypes", "unchecked"})
 352  
   protected static ServletTemplateContext popupSelect(ServletTemplateContext context,
 353  
       Melati melati) throws PoemException {
 354  3
     final Table table = melati.getTable();
 355  
 
 356  3
     final Database database = table.getDatabase();
 357  
 
 358  
     // sort out search criteria
 359  
 
 360  3
     final Persistent criteria = table.newPersistent();
 361  
 
 362  3
     MappedEnumeration<Field<?>, Column<?>> criterias = new MappedEnumeration<Field<?>, Column<?>>(table
 363  13
         .getSearchCriterionColumns()) {
 364  
       public Field<?> mapped(Column<?> c) {
 365  10
         return c.asField(criteria).withNullable(true);
 366  
       }
 367  
     };
 368  
 
 369  3
     context.put("criteria", EnumUtils.vectorOf(criterias));
 370  3
     ReferencePoemType searchColumnsType = getSearchColumnsType(database, table);
 371  
 
 372  3
     Vector<Field<?>> orderings = new Vector<Field<?>>();
 373  
     // NOTE Order by searchable columns, this could be summary columns
 374  3
     Enumeration<Integer> searchColumns = searchColumnsType.possibleRaws();
 375  3
     int o = 0;
 376  13
     while (searchColumns.hasMoreElements()) {
 377  10
       String name = "order-" + o++;
 378  10
       orderings.addElement(new Field(searchColumns.nextElement(), 
 379  
           new BaseFieldAttributes(name, searchColumnsType)));
 380  10
     }
 381  
 
 382  3
     context.put("orderings", orderings);
 383  
 
 384  3
     return context;
 385  
   }
 386  
 
 387  
   /**
 388  
    * @return a type whose whose possible members are the search columns of the table
 389  
    */
 390  
   private static ReferencePoemType getSearchColumnsType(final Database database, final Table<?> table) {
 391  60
     return new ReferencePoemType(database
 392  60
         .getColumnInfoTable(), false) {
 393  
       protected Enumeration<Integer> _possibleRaws() {
 394  57
         return new MappedEnumeration<Integer, Column<?>>(table.getSearchCriterionColumns()) {
 395  
           public Integer mapped(Column<?> column) {
 396  44
             return column.getColumnInfo().getTroid();
 397  
           }
 398  
         };
 399  
       }
 400  
     };
 401  
   }
 402  
 
 403  
   /**
 404  
    * @return primary select template
 405  
    */
 406  
   protected static String selectionWindowPrimarySelectTemplate(
 407  
       ServletTemplateContext context, Melati melati) throws PoemException {
 408  2
     context.put("inPopup", Boolean.TRUE);
 409  2
     return primarySelectTemplate(context, melati);
 410  
   }
 411  
 
 412  
   /**
 413  
    * @return select template (a selection of records from a table)
 414  
    */
 415  
   protected static String selectionWindowSelectionTemplate(
 416  
       ServletTemplateContext context, Melati melati) {
 417  2
     selection(context, melati, true);
 418  2
     context.put("inPopup", Boolean.TRUE);
 419  2
     return adminTemplate("Selection");
 420  
   }
 421  
 
 422  
   /**
 423  
    * Returns the Add template after placing the table and fields for the new row
 424  
    * in the context using any field values already in the context.
 425  
    * 
 426  
    * If the table is a table meta data table, or a column meta data table then
 427  
    * the appropriate extras are added to the co0ntext.
 428  
    * 
 429  
    * The Form does not normally contain values, but this could be used as a
 430  
    * mechanism for providing defaults.
 431  
    */
 432  
   @SuppressWarnings("unchecked")
 433  
   protected static String addTemplate(final ServletTemplateContext context,
 434  
       Melati melati) throws PoemException {
 435  
 
 436  
     /*
 437  
      * Enumeration fields = new MappedEnumeration(melati.getTable().columns()) {
 438  
      * public Object mapped(Object column) { String stringValue =
 439  
      * context.getForm("field_" + ((Column)column).getName()); Object value =
 440  
      * null; if (stringValue != null) value =
 441  
      * ((Column)column).getType().rawOfString(stringValue); return new
 442  
      * Field(value, (Column)column); } }; context.put("fields", fields);
 443  
      */
 444  
 
 445  
     // getDetailDisplayColumns() == columns() but could exclude some in theory
 446  7
     Enumeration<Column<?>> columns = melati.getTable().getDetailDisplayColumns();
 447  7
     Vector<Field<?>> fields = new Vector<Field<?>>();
 448  58
     while (columns.hasMoreElements()) {
 449  51
       Column<?> column = columns.nextElement();
 450  51
       String stringValue = context.getFormField("field_" + column.getName());
 451  51
       Object value = null;
 452  51
       if (stringValue != null)
 453  1
         value = column.getType().rawOfString(stringValue);
 454  50
       else if (column.getType() instanceof ColumnTypePoemType)
 455  1
         value = PoemTypeFactory.STRING.getCode();
 456  51
       fields.add(new Field<Object>(value, (FieldAttributes<Object>) column));
 457  51
     }
 458  7
     if (melati.getTable() instanceof TableInfoTable) {
 459  1
       Database database = melati.getDatabase();
 460  
 
 461  
       // Compose field for naming the TROID column: the display name and
 462  
       // description are redundant, since they not used in the template
 463  
 
 464  1
       final int troidHeight = 1;
 465  1
       final int troidWidth = 20;
 466  1
       Field<String> troidNameField = new Field<String>("id", new BaseFieldAttributes<String>(
 467  
           "troidName", "Troid column", "Name of TROID column", database
 468  
               .getColumnInfoTable().getNameColumn().getType(), troidWidth,
 469  
           troidHeight, null, false, true, true));
 470  
 
 471  1
       fields.add(troidNameField);
 472  
     }
 473  7
     context.put("fields", fields.elements());
 474  7
     return adminTemplate("Add");
 475  
   }
 476  
 
 477  
   /**
 478  
    * Returns the Updated template after creating a new row using field data in
 479  
    * the context.
 480  
    * <p>
 481  
    * If successful the template will say so while reloading according to the
 482  
    * returnTarget and returnURL values from the Form in context.
 483  
    */
 484  
   protected static String addUpdateTemplate(ServletTemplateContext context,
 485  
       Melati melati) throws PoemException {
 486  
 
 487  7
     Persistent newPersistent = create(melati.getTable(), context);
 488  
 
 489  7
     if (melati.getTable() instanceof TableInfoTable)
 490  1
       melati.getDatabase().addTableAndCommit((TableInfo) newPersistent,
 491  
           context.getFormField("field_troidName"));
 492  7
     if (melati.getTable() instanceof ColumnInfoTable)
 493  1
       ((ColumnInfo) newPersistent).getTableinfo().actualTable()
 494  
           .addColumnAndCommit((ColumnInfo) newPersistent);
 495  7
     melati.setPoemContext(new PoemContext(newPersistent));
 496  7
     melati.loadTableAndObject();
 497  
     //context.put("object", newPersistent);
 498  7
     melati.getResponse().setStatus(201);
 499  7
     return adminTemplate("Updated");
 500  
   }
 501  
 
 502  
   /**
 503  
    * Returns the Updated template after modifying the current row according to
 504  
    * field values in the context.
 505  
    * <p>
 506  
    * If successful the template will say so while reloading according to the
 507  
    * returnTarget and returnURL values from the Form in context.
 508  
    */
 509  
   protected static String updateTemplate(ServletTemplateContext context,
 510  
       Melati melati) throws PoemException {
 511  2
     Persistent object = melati.getObject();
 512  2
     object.preEdit();
 513  2
     Form.extractFields(context, object);
 514  2
     object.postEdit(false);
 515  2
     return adminTemplate("Updated");
 516  
   }
 517  
 
 518  
   protected static String deleteTemplate(ServletTemplateContext context,
 519  
       Melati melati) throws PoemException {
 520  
     try {
 521  5
       if (melati.getTable().getName().equalsIgnoreCase("tableinfo")) {
 522  1
         TableInfo tableInfo = (TableInfo) melati.getObject();
 523  1
         melati.getDatabase().deleteTableAndCommit(tableInfo);
 524  1
       } else if (melati.getTable().getName().equalsIgnoreCase("columninfo")) {
 525  2
         ColumnInfo columnInfo = (ColumnInfo) melati.getObject();
 526  2
         columnInfo.getTableinfo().actualTable().deleteColumnAndCommit(
 527  
             columnInfo);
 528  2
       } else
 529  2
         melati.getObject().delete();
 530  5
       melati.getPoemContext().setTroid(null);
 531  5
       melati.loadTableAndObject();
 532  
       
 533  5
       return adminTemplate("Updated");
 534  0
     } catch (DeletionIntegrityPoemException e) {
 535  0
       context.put("references", e.references);
 536  0
       context.put("returnURL", melati.getSameURL() + "?action=Delete");
 537  0
       return adminTemplate("DeleteFailure");
 538  
     }
 539  
   }
 540  
 
 541  
   protected static String duplicateTemplate(ServletTemplateContext context,
 542  
       Melati melati) throws PoemException {
 543  1
     Persistent dup = melati.getObject().duplicated();
 544  1
     Form.extractFields(context, dup);
 545  
     try {
 546  1
       dup.getTable().create(dup);
 547  0
     } catch (ExecutingSQLPoemException e) {
 548  0
       throw new NonUniqueKeyValueAnticipatedException(e);
 549  1
     }
 550  1
     melati.setPoemContext(new PoemContext(dup));
 551  1
     melati.loadTableAndObject();
 552  
     //context.put("object", dup);
 553  1
     return adminTemplate("Updated");
 554  
   }
 555  
 
 556  
   /**
 557  
    * Implements request method "Update".
 558  
    * <p>
 559  
    * Calls another method depending on the requested action.
 560  
    * 
 561  
    * @see #updateTemplate(ServletTemplateContext, Melati)
 562  
    * @see #deleteTemplate(ServletTemplateContext, Melati)
 563  
    * @see #duplicateTemplate(ServletTemplateContext, Melati)
 564  
    */
 565  
   protected static String modifyTemplate(ServletTemplateContext context,
 566  
       Melati melati) throws FormParameterException {
 567  8
     String action = melati.getRequest().getParameter("action");
 568  8
     if ("Update".equals(action))
 569  2
       return updateTemplate(context, melati);
 570  6
     if ("Delete".equals(action))
 571  5
       return deleteTemplate(context, melati);
 572  1
     if ("Duplicate".equals(action))
 573  1
       return duplicateTemplate(context, melati);
 574  
     else
 575  0
       throw new MelatiBugMelatiException("How did you get that in there?",
 576  
           new FormParameterException(
 577  
             "action", "Bad action from Edit: " + action));
 578  
   }
 579  
 
 580  
   protected static String uploadTemplate(ServletTemplateContext context)
 581  
       throws PoemException {
 582  2
     context.put("field", context.getFormField("field"));
 583  2
     return adminTemplate("Upload");
 584  
   }
 585  
 
 586  
   /**
 587  
    * Finished uploading.
 588  
    * 
 589  
    * If you want the system to display the file you need to set your melati-wide
 590  
    * FormDataAdaptorFactory, in org.melati.MelatiConfig.properties, to something
 591  
    * that returns a valid URL, for instance, PoemFileDataAdaptorFactory;
 592  
    * (remember to set your UploadDir and UploadURL in the Setting table).
 593  
    * 
 594  
    * @param context
 595  
    *          the {@link ServletTemplateContext} in use
 596  
    * @return a template name
 597  
    */
 598  
 
 599  
   protected static String uploadDoneTemplate(ServletTemplateContext context)
 600  
       throws PoemException {
 601  1
     String field = context.getFormField("field");
 602  1
     context.put("field", field);
 603  1
     String url = context.getMultipartFormField("file").getDataURL();
 604  1
     if (url == null)
 605  0
       throw new NullUrlDataAdaptorException(context.getMultipartFormField("file").getFormDataAdaptor());
 606  1
     context.put("url", url);
 607  1
     return adminTemplate("UploadDone");
 608  
   }
 609  
 
 610  1
   static class NullUrlDataAdaptorException extends MelatiRuntimeException {
 611  
     private static final long serialVersionUID = 1L;
 612  
     private FormDataAdaptor fda;
 613  
     NullUrlDataAdaptorException(FormDataAdaptor fda) { 
 614  
       this.fda = fda;
 615  
     }
 616  
 
 617  
     /** @return the message */
 618  
     public String getMessage() {
 619  
       return "The configured FormDataAdaptor (" + fda.getClass().getName() + ") returns a null URL.";
 620  
     }
 621  
   }
 622  
 
 623  
   protected static String setupTemplate(ServletTemplateContext context,
 624  
       Melati melati) {
 625  2
     screenStylesheetURL = melati.getDatabase().getSettingTable().ensure(
 626  
         Admin.class.getName() + ".ScreenStylesheetURL", "/blue.css",
 627  
         "ScreenStylesheetURL",
 628  
         "path to stylesheet, relative to melati-static, starting with a slash")
 629  
         .getValue();
 630  2
     primaryDisplayTable = melati.getDatabase().getSettingTable().ensure(
 631  
         Admin.class.getName() + ".PrimaryDisplayTable", "setting",
 632  
         "PrimaryDisplayTable", "The default table to display").getValue();
 633  2
     Setting homepageURLSetting = melati.getDatabase().getSettingTable().ensure(
 634  
         Admin.class.getName() + ".HomepageURL", "http://www.melati.org/",
 635  
         "HomepageURL", "The home page for this database");
 636  2
     homepageURL = homepageURLSetting.getValue();
 637  
     // HACK Not very satisfactory, but only to enable testing
 638  
     //context.put("object", homepageURLSetting);
 639  
     // If we wanted to get RESTful at this point, but it is a bit nasty as a UI
 640  
     // melati.getResponse().setHeader("Location",melati.sameURLWith("action", ""));
 641  
     
 642  2
     return adminTemplate("Updated");
 643  
   }
 644  
 
 645  
   protected String doTemplateRequest(Melati melati,
 646  
       ServletTemplateContext context) throws Exception {
 647  413
     if (melati.getMethod().equals("Proxy"))
 648  2
       return proxy(melati, context);
 649  411
     melati.getSession().setAttribute("generatedByMelatiClass",this.getClass().getName());
 650  
 
 651  411
     context.put("admin", new AdminUtils(melati));
 652  
     
 653  411
     String table = Form.getFieldNulled(context, "table");
 654  411
     if (table != null) {
 655  8
       if (!table.equals(melati.getTable().getName())) {
 656  4
         melati.getPoemContext().setTable(table);
 657  4
         melati.getPoemContext().setTroid(null);
 658  4
         melati.loadTableAndObject();
 659  
       }
 660  
     }
 661  411
     if (Form.getFieldNulled(context, "goto") != null)
 662  0
       melati.getResponse().sendRedirect(Form.getField(context, "goto", null));
 663  
 
 664  411
     melati.setPassbackExceptionHandling();
 665  411
     melati.setResponseContentType("text/html");
 666  
 
 667  411
     Capability admin = PoemThread.database().getCanAdminister();
 668  411
     AccessToken token = PoemThread.accessToken();
 669  411
     if (!token.givesCapability(admin))
 670  1
       throw new AccessPoemException(token, admin);
 671  
 
 672  
 
 673  410
     if (melati.getMethod() == null)
 674  0
       return adminTemplate("Main");
 675  410
     if (melati.getMethod().equals("blank"))
 676  54
       return adminTemplate("blank");
 677  356
     if (melati.getMethod().equals("setup"))
 678  2
       return setupTemplate(context, melati);
 679  354
     if (melati.getMethod().equals("Main"))
 680  23
       return adminTemplate("Main");
 681  331
     if (melati.getMethod().equals("Top"))
 682  30
       return adminTemplate("Top");
 683  301
     if (melati.getMethod().equals("UploadDone"))
 684  1
       return uploadDoneTemplate(context);
 685  300
     if (melati.getMethod().equals("Record"))
 686  37
       return adminTemplate("Record");
 687  263
     if (melati.getMethod().equals("Selection"))
 688  53
       return selectionTemplate(context, melati);
 689  
 
 690  210
     if (melati.getObject() != null) {
 691  51
       if (melati.getMethod().equals("Update"))
 692  8
         return modifyTemplate(context, melati);
 693  43
       if (melati.getObject() instanceof AdminSpecialised) {
 694  6
         String templateName = ((AdminSpecialised) melati.getObject())
 695  
             .adminHandle(melati, melati.getMarkupLanguage());
 696  6
         if (templateName != null)
 697  5
           return templateName;
 698  
       }
 699  
     }
 700  
 
 701  197
     if (melati.getTable() != null) {
 702  195
       if (melati.getMethod().equals("Tree"))
 703  3
         return adminTemplate("Tree");
 704  192
       if (melati.getMethod().equals("Bottom"))
 705  32
         return adminTemplate("Bottom");
 706  160
       if (melati.getMethod().equals("Table"))
 707  33
         return adminTemplate("Table");
 708  127
       if (melati.getMethod().equals("PrimarySelect"))
 709  37
         return primarySelectTemplate(context, melati);
 710  90
       if (melati.getMethod().equals("EditHeader"))
 711  11
         return adminTemplate("EditHeader");
 712  79
       if (melati.getMethod().equals("Edit"))
 713  20
         return adminTemplate("Edit");
 714  59
       if (melati.getMethod().equals("Upload"))
 715  2
         return uploadTemplate(context);
 716  
 
 717  57
       if (melati.getMethod().equals("SelectionRight"))
 718  2
         return selectionRightTemplate(context, melati);
 719  55
       if (melati.getMethod().equals("Navigation"))
 720  33
         return adminTemplate("Navigation");
 721  22
       if (melati.getMethod().equals("PopUp"))
 722  3
         return popupSelectTemplate(context, melati);
 723  19
       if (melati.getMethod().equals("SelectionWindow"))
 724  1
         return adminTemplate("SelectionWindow");
 725  18
       if (melati.getMethod().equals("SelectionWindowPrimarySelect"))
 726  2
         return selectionWindowPrimarySelectTemplate(context, melati);
 727  16
       if (melati.getMethod().equals("SelectionWindowSelection"))
 728  2
         return selectionWindowSelectionTemplate(context, melati);
 729  14
       if (melati.getMethod().equals("Add"))
 730  7
         return addTemplate(context, melati);
 731  7
       if (melati.getMethod().equals("Created"))
 732  7
         return addUpdateTemplate(context, melati);
 733  
     }
 734  2
     if (melati.getMethod().equals("DSD"))
 735  1
       return dsdTemplate(context);
 736  
 
 737  1
     throw new InvalidUsageException(this, melati.getPoemContext());
 738  
   }
 739  
 
 740  
   private String proxy(Melati melati, ServletTemplateContext context) {
 741  2
     if (melati.getSession().getAttribute("generatedByMelatiClass") == null)
 742  1
       throw new AnticipatedException("Only available from within an Admin generated page");
 743  1
     String method = melati.getRequest().getMethod();
 744  1
     String url =  melati.getRequest().getQueryString();
 745  1
     HttpServletResponse response = melati.getResponse();
 746  1
     HttpMethod httpMethod = null; 
 747  
     try { 
 748  
 
 749  1
       HttpClient client = new HttpClient();
 750  1
       if (method.equals("GET"))
 751  1
         httpMethod = new GetMethod(url);
 752  0
       else if (method.equals("POST"))
 753  0
         httpMethod = new PostMethod(url);
 754  0
       else if (method.equals("PUT"))
 755  0
         httpMethod = new PutMethod(url);
 756  0
       else if (method.equals("HEAD"))
 757  0
         httpMethod = new HeadMethod(url);
 758  
       else
 759  0
         throw new RuntimeException("Unexpected method '" + method + "'");
 760  
       try {
 761  1
         httpMethod.setFollowRedirects(true);
 762  1
         client.executeMethod(httpMethod);
 763  12
         for (Header h : httpMethod.getResponseHeaders()) { 
 764  11
           response.setHeader(h.getName(), h.getValue());
 765  
         }
 766  1
         response.setStatus(httpMethod.getStatusCode());
 767  1
         response.setHeader("Cache-Control", "no-cache");
 768  1
         byte[] outputBytes = httpMethod.getResponseBody();
 769  1
         if (outputBytes != null) { 
 770  1
           response.setBufferSize(outputBytes.length);
 771  1
           response.getWriter().write(new String(outputBytes));
 772  1
           response.getWriter().flush();
 773  
         }
 774  0
       } catch (Exception e) {
 775  0
         throw new MelatiIOException(e);
 776  1
       }
 777  
     } finally {
 778  1
       if (httpMethod != null)
 779  1
         httpMethod.releaseConnection();
 780  
     }
 781  1
     return null;
 782  
   }
 783  
 
 784  
   /**
 785  
    * @return the screenStylesheetURL
 786  
    */
 787  
   static String getScreenStylesheetURL() {
 788  849
     return screenStylesheetURL;
 789  
   }
 790  
 
 791  
   /**
 792  
    * @param screenStylesheetURL the screenStylesheetURL to set
 793  
    */
 794  
   static void setScreenStylesheetURL(String screenStylesheetURL) {
 795  2
     Admin.screenStylesheetURL = screenStylesheetURL;
 796  2
   }
 797  
 
 798  
   /**
 799  
    * @return the primaryDisplayTable
 800  
    */
 801  
   static String getPrimaryDisplayTable() {
 802  720
     return primaryDisplayTable;
 803  
   }
 804  
 
 805  
   /**
 806  
    * @param primaryDisplayTable the primaryDisplayTable to set
 807  
    */
 808  
   static void setPrimaryDisplayTable(String primaryDisplayTable) {
 809  2
     Admin.primaryDisplayTable = primaryDisplayTable;
 810  2
   }
 811  
 
 812  
   /**
 813  
    * @return the homepageURL
 814  
    */
 815  
   static String getHomepageURL() {
 816  180
     return homepageURL;
 817  
   }
 818  
 
 819  
   /**
 820  
    * @param homepageURL the homepageURL to set
 821  
    */
 822  
   static void setHomepageURL(String homepageURL) {
 823  2
     Admin.homepageURL = homepageURL;
 824  2
   }
 825  
 }