Project

General

Profile

« Previous | Next » 

Revision 5025

Added by daigle over 15 years ago

Move document specific utilities to DocumentUtil from MetacatUtil. This makes it easier to define a layer between the core metacat services and the rest of the code.

View differences:

src/edu/ucsb/nceas/metacat/MetaCatVersion.java
1
/**
2
 *  '$RCSfile$'
3
 *  Copyright: 2004 Regents of the University of California and the
4
 *             National Center for Ecological Analysis and Synthesis
5
 *
6
 *   '$Author$'
7
 *     '$Date$'
8
 * '$Revision$'
9
 *
10
 * This program is free software; you can redistribute it and/or modify
11
 * it under the terms of the GNU General Public License as published by
12
 * the Free Software Foundation; either version 2 of the License, or
13
 * (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU General Public License
21
 * along with this program; if not, write to the Free Software
22
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
 */
24
package edu.ucsb.nceas.metacat;
25

  
26
import edu.ucsb.nceas.metacat.service.PropertyService;
27
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
28

  
29
/**
30
 * @author jones
31
 *
32
 * Version represents the current version information for this Metacat instance.
33
 */
34
public class MetaCatVersion extends Version {
35
    public MetaCatVersion(String versionID) {
36
    	super(versionID);
37
    }
38
	
39
	/**
40
	 * Get the current version string for this metacat instance. It is currently
41
	 * stored in the metacat.properties file.
42
	 * 
43
	 * @return a string indicating the version of Metacat running
44
	 */
45
	public static String getVersionID() throws PropertyNotFoundException {
46
		String version = PropertyService.getProperty("application.metacatVersion");
47
		return version;
48
	}
49
    
50
    /**
51
	 * Get the version number in an XML document.
52
	 * 
53
	 * @return the version wrapped in an XML document
54
	 */
55
    public static String getVersionAsXml() throws PropertyNotFoundException {
56
        StringBuffer sb = new StringBuffer();
57
        sb.append("<?xml version=\"1.0\"?>");
58
        sb.append("<version>");
59
        sb.append(getVersionID());
60
        sb.append("</version>");
61
        return sb.toString();
62
    }
63
}
64 0

  
src/edu/ucsb/nceas/metacat/MetaCatServlet.java
86 86
import edu.ucsb.nceas.metacat.service.SessionService;
87 87
import edu.ucsb.nceas.metacat.service.SkinPropertyService;
88 88
import edu.ucsb.nceas.metacat.service.XMLSchemaService;
89
import edu.ucsb.nceas.metacat.shared.BaseException;
90 89
import edu.ucsb.nceas.metacat.shared.HandlerException;
91 90
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
92 91
import edu.ucsb.nceas.metacat.shared.ServiceException;
93 92
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
94 93
import edu.ucsb.nceas.metacat.spatial.SpatialQuery;
95 94
import edu.ucsb.nceas.metacat.util.AuthUtil;
95
import edu.ucsb.nceas.metacat.util.ConfigurationUtil;
96 96
import edu.ucsb.nceas.metacat.util.ErrorSendingErrorException;
97
import edu.ucsb.nceas.metacat.util.DocumentUtil;
97 98
import edu.ucsb.nceas.metacat.util.MetacatUtil;
98 99
import edu.ucsb.nceas.metacat.util.RequestUtil;
99
import edu.ucsb.nceas.metacat.util.ResponseUtil;
100 100
import edu.ucsb.nceas.metacat.util.SystemUtil;
101 101
import edu.ucsb.nceas.metacat.util.SessionData;
102
import edu.ucsb.nceas.metacat.workflow.WorkflowScheduler;
103 102
import edu.ucsb.nceas.utilities.FileUtil;
104 103
import edu.ucsb.nceas.utilities.GeneralPropertyException;
105 104
import edu.ucsb.nceas.utilities.LSIDUtil;
......
129 128
 *     searchmode --
130 129
 *     anyfield --
131 130
 * action=spatial_query -- run a spatial query.  these queries may include any of the
132
 *     queries supported by the WFS / WMS standards
131
 *                         queries supported by the WFS / WMS standards
133 132
 *     xmax --
134 133
 *     ymax --
135 134
 *     xmin --
......
204 203
 *     event -- filter on event type (e.g., read, insert, update, delete)
205 204
 *     start -- filter out events before the start date-time
206 205
 *     end -- filter out events before the end date-time
207
 * action=shrink --
206
 * action=shrink -- Shrink the database connection pool size if it has grown and 
207
 *                  extra connections are no longer being used.
208 208
 * action=buildindex --
209 209
 *     docid --
210
 * action=gohome --
211 210
 * action=refreshServices --
212
 * action=scheduleWorkflow --
213
 *     delay --
214
 *     starttime --
215
 *     endtime --
216
 *     intervalvalue -- 
217
 *     intervalunit --
218
 *     workflowid --
219
 *     karid --
220
 *     workflowname --
221
 *     forwardto --
222
 *     qformat --
223
 * action=unscheduleWorkflow --
224
 *     workflowjobid --
225
 *     forwardto --
226
 *     qformat --
227
 * action=rescheduleWorkflow --
228
 *     workflowjobid --
229
 *     forwardto --
230
 *     qformat --
231
 * action=deleteScheduledWorkflow --
232
 *     workflowjobid --
233
 *     forwardto --
234
 *     qformat --
211
 * action=scheduleWorkflow -- Schedule a workflow to be run.  Scheduling a workflow 
212
 *                            registers it with the scheduling engine and creates a row
213
 *                            in the scheduled_job table.  Note that this may be 
214
 *                            extracted into a separate servlet.
215
 *     delay -- The amount of time from now before the workflow should be run.  The 
216
 *              delay can be expressed in number of seconds, minutes, hours and days, 
217
 *              for instance 30s, 2h, etc.
218
 *     starttime -- The time that the workflow should first run.  If both are provided
219
 *                  this takes precedence over delay.  The time should be expressed as: 
220
 *                  MM/dd/yyyy HH:mm:ss with the timezone assumed to be that of the OS.
221
 *     endtime -- The time when the workflow should end. The time should be expressed as: 
222
 *                  MM/dd/yyyy HH:mm:ss with the timezone assumed to be that of the OS.
223
 *     intervalvalue -- The numeric value of the interval between runs
224
 *     intervalunit -- The unit of the interval between runs.  Can be s, m, h, d for 
225
 *                     seconds, minutes, hours and days respectively
226
 *     workflowid -- The lsid of the workflow that we want to schedule.  This workflow
227
 *                   must already exist in the database.
228
 *     karid -- The karid for the workflow that we want to schedule.
229
 *     workflowname -- The name of the workflow.
230
 *     forwardto -- If provided, forward to this page when processing is done.
231
 *     qformat -- If provided, render results using the stylesheets associated with
232
 *                this skin.  Default is xml.
233
 * action=unscheduleWorkflow -- Unschedule a workflow.  Unscheduling a workflow 
234
 *                            removes it from the scheduling engine and changes the 
235
 *                            status in the scheduled_job table to " unscheduled.  Note 
236
 *                            that this may be extracted into a separate servlet.
237
 *     workflowjobid -- The job ID for the workflow run that we want to unschedule.  This
238
 *                      is held in the database as scheduled_job.name
239
 *     forwardto -- If provided, forward to this page when processing is done.
240
 *     qformat -- If provided, render results using the stylesheets associated with
241
 *                this skin.  Default is xml.
242
 * action=rescheduleWorkflow -- Unschedule a workflow.  Rescheduling a workflow 
243
 *                            registers it with the scheduling engine and changes the 
244
 *                            status in the scheduled_job table to " scheduled.  Note 
245
 *                            that this may be extracted into a separate servlet.
246
 *     workflowjobid -- The job ID for the workflow run that we want to reschedule.  This
247
 *                      is held in the database as scheduled_job.name
248
 *     forwardto -- If provided, forward to this page when processing is done.
249
 *     qformat -- If provided, render results using the stylesheets associated with
250
 *                this skin.  Default is xml.
251
 * action=deleteScheduledWorkflow -- Delete a workflow.  Deleting a workflow 
252
 *                            removes it from the scheduling engine and changes the 
253
 *                            status in the scheduled_job table to " deleted.  Note 
254
 *                            that this may be extracted into a separate servlet.
255
 *     workflowjobid -- The job ID for the workflow run that we want to delete.  This
256
 *                      is held in the database as scheduled_job.name
257
 *     forwardto -- If provided, forward to this page when processing is done.
258
 *     qformat -- If provided, render results using the stylesheets associated with
259
 *                this skin.  Default is xml.
235 260
 *     
236 261
 *     
237 262
 * Here are some of the common parameters for actions
......
266 291
    public static final String SCHEMALOCATIONKEYWORD = ":schemaLocation";
267 292
    public static final String NONAMESPACELOCATION = ":noNamespaceSchemaLocation";
268 293
    public static final String EML2KEYWORD = ":eml";
269
    public static final String XMLFORMAT = "xml";
270 294
    private static final String FALSE = "false";
271 295
    private static final String TRUE  = "true";
272 296
    private static String LOG_CONFIG_NAME = null;
......
302 326
    		// Check to see if the user has requested to bypass configuration 
303 327
            // (dev option) and check see if metacat has been configured.
304 328
    		// If both are false then stop the initialization
305
            if (!MetacatUtil.bypassConfiguration() && !MetacatUtil.isMetacatConfigured()) {
329
            if (!ConfigurationUtil.bypassConfiguration() && !ConfigurationUtil.isMetacatConfigured()) {
306 330
            	return;
307 331
            }  
308 332
            
......
430 454

  
431 455
			fullyInitialized = true;
432 456
			
433
			logMetacat.warn("Metacat (" + MetaCatVersion.getVersionID()
457
			logMetacat.warn("Metacat (" + MetacatVersion.getVersionID()
434 458
					+ ") initialized.");
435 459
			
436 460
		} catch (SQLException e) {
......
641 665
		
642 666
		// Each time metacat is called, check to see if metacat has been 
643 667
		// configured. If not then forward to the administration servlet
644
		if (!MetacatUtil.isMetacatConfigured()) {
645
			RequestUtil.forwardRequest(request, response, "/admin?action=configure");
668
		if (!ConfigurationUtil.isMetacatConfigured()) {
669
			RequestUtil.forwardRequest(request, response, "/admin?action=configure", null);
646 670
			return;
647 671
		}
648 672

  
......
927 951
				} else if (action.equals("getversion")) {
928 952
					response.setContentType("text/xml");
929 953
					PrintWriter out = response.getWriter();
930
					out.println(MetaCatVersion.getVersionAsXml());
954
					out.println(MetacatVersion.getVersionAsXml());
931 955
					out.close();
932 956
				} else if (action.equals("getlog")) {
933 957
					handleGetLogAction(params, request, response, userName, groupNames);
......
985 1009
					 * out.println(mue.getMessage()); mue.printStackTrace(out);
986 1010
					 * out.close(); }
987 1011
					 */
988
				} else if (action.equals("gohome")) {
989
					// forward to the default page
990
					RequestUtil.forwardRequest(request, response, "/");
991 1012
				} else if (action.equals("refreshServices")) {
992 1013
					// TODO MCD this interface is for testing.  It should go through a 
993 1014
					// ServiceService class and only work for an admin user.  Move to the
994 1015
					// MetacatAdminServlet
995 1016
					ServiceService.refreshService("XMLSchemaService");
996 1017
					return;
997
				} else if (action.equals("scheduleWorkflow")) {
998
					try {
999
						WorkflowScheduler.getInstance().scheduleJob(request, response, params, 
1000
							userName, groupNames);
1001
						return;
1002
					} catch (BaseException be) {
1003
						ResponseUtil.sendErrorXML(response, ResponseUtil.SCHEDULE_WORKFLOW_ERROR, be);
1004
						return;						
1005
					}
1006
				} else if (action.equals("unscheduleWorkflow")) {
1007
					try {
1008
						WorkflowScheduler.getInstance().unScheduleJob(request, response, params, 
1009
							userName, groupNames);
1010
						return;
1011
					} catch (BaseException be) {
1012
						ResponseUtil.sendErrorXML(response, ResponseUtil.UNSCHEDULE_WORKFLOW_ERROR, be);
1013
						return;						
1014
					}
1015
				} else if (action.equals("rescheduleWorkflow")) {
1016
					try {
1017
						WorkflowScheduler.getInstance().reScheduleJob(request, response, params, 
1018
							userName, groupNames);
1019
						return;
1020
					} catch (BaseException be) {
1021
						ResponseUtil.sendErrorXML(response, ResponseUtil.RESCHEDULE_WORKFLOW_ERROR, be);
1022
						return;						
1023
					}
1024
				} else if (action.equals("getScheduledWorkflow")) {
1025
					try {
1026
						WorkflowScheduler.getInstance().getJobs(request, response, params, 
1027
								userName, groupNames);				
1028
						return;
1029
					} catch (BaseException be) {
1030
						ResponseUtil.sendErrorXML(response, ResponseUtil.GET_SCHEDULED_WORKFLOW_ERROR, be);
1031
						return;						
1032
					}
1033
				} else if (action.equals("deleteScheduledWorkflow")) {
1034
					try {
1035
						WorkflowScheduler.getInstance().deleteJob(request, response, params, 
1036
								userName, groupNames);				
1037
						return;
1038
					} catch (BaseException be) {
1039
						ResponseUtil.sendErrorXML(response, ResponseUtil.DELETE_SCHEDULED_WORKFLOW_ERROR, be);
1040
						return;						
1041
					}
1018
//				} else if (action.equals("scheduleWorkflow")) {
1019
//					try {
1020
//						WorkflowScheduler.getInstance().scheduleJob(request, response, params, 
1021
//							userName, groupNames);
1022
//						return;
1023
//					} catch (BaseException be) {
1024
//						ResponseUtil.sendErrorXML(response, ResponseUtil.SCHEDULE_WORKFLOW_ERROR, be);
1025
//						return;						
1026
//					}
1027
//				} else if (action.equals("unscheduleWorkflow")) {
1028
//					try {
1029
//						WorkflowScheduler.getInstance().unScheduleJob(request, response, params, 
1030
//							userName, groupNames);
1031
//						return;
1032
//					} catch (BaseException be) {
1033
//						ResponseUtil.sendErrorXML(response, ResponseUtil.UNSCHEDULE_WORKFLOW_ERROR, be);
1034
//						return;						
1035
//					}
1036
//				} else if (action.equals("rescheduleWorkflow")) {
1037
//					try {
1038
//						WorkflowScheduler.getInstance().reScheduleJob(request, response, params, 
1039
//							userName, groupNames);
1040
//						return;
1041
//					} catch (BaseException be) {
1042
//						ResponseUtil.sendErrorXML(response, ResponseUtil.RESCHEDULE_WORKFLOW_ERROR, be);
1043
//						return;						
1044
//					}
1045
//				} else if (action.equals("getScheduledWorkflow")) {
1046
//					try {
1047
//						WorkflowScheduler.getInstance().getJobs(request, response, params, 
1048
//								userName, groupNames);				
1049
//						return;
1050
//					} catch (BaseException be) {
1051
//						ResponseUtil.sendErrorXML(response, ResponseUtil.GET_SCHEDULED_WORKFLOW_ERROR, be);
1052
//						return;						
1053
//					}
1054
//				} else if (action.equals("deleteScheduledWorkflow")) {
1055
//					try {
1056
//						WorkflowScheduler.getInstance().deleteJob(request, response, params, 
1057
//								userName, groupNames);				
1058
//						return;
1059
//					} catch (BaseException be) {
1060
//						ResponseUtil.sendErrorXML(response, ResponseUtil.DELETE_SCHEDULED_WORKFLOW_ERROR, be);
1061
//						return;						
1062
//					}
1042 1063
				} else {
1043 1064
					PrintWriter out = response.getWriter();
1044 1065
					out.println("<?xml version=\"1.0\"?>");
......
1336 1357
                response.setContentType("text/html");
1337 1358
                trans.transformXMLDocument(sess.getMessage(),
1338 1359
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
1339
                        out, null);
1360
                        out, null, null);
1340 1361
            } catch (Exception e) {               
1341 1362
                logMetacat.error("Error in MetaCatServlet.handleLoginAction: "
1342 1363
                        + e.getMessage());
......
1385 1406
                response.setContentType("text/html");
1386 1407
                trans.transformXMLDocument(output.toString(),
1387 1408
                        "-//NCEAS//login//EN", "-//W3C//HTML//EN", qformat,
1388
                        out, null);
1409
                        out, null, null);
1389 1410
            } catch (Exception e) {
1390 1411
                logMetacat.error(
1391 1412
                        "Error in MetaCatServlet.handleLogoutAction"
......
1578 1599
                throw new Exception("You didn't specify requested inlinedataid"); }
1579 1600
            
1580 1601
            // check for permission
1581
            docId = MetacatUtil
1582
                    .getDocIdWithoutRevFromInlineDataID(inlineDataId);
1602
            docId = 
1603
            	DocumentUtil.getDocIdWithoutRevFromInlineDataID(inlineDataId);
1583 1604
            PermissionController controller = new PermissionController(docId);
1584 1605
            // check top level read permission
1585 1606
            if (!controller.hasPermission(user, groups,
......
1593 1614
                    Hashtable<String,String> unReadableInlineDataList =
1594 1615
                            PermissionController.getUnReadableInlineDataIdList(docId,
1595 1616
                            user, groups, false);
1596
                    String inlineDataIdWithoutRev = MetacatUtil.getInlineDataIdWithoutRev(inlineDataId);
1617
                    String inlineDataIdWithoutRev = DocumentUtil.getInlineDataIdWithoutRev(inlineDataId);
1597 1618
                    if (unReadableInlineDataList.containsValue(inlineDataIdWithoutRev)) {
1598 1619
                        throw new Exception("User " + user
1599 1620
                                + " doesn't have permission " + " to read inlinedata "
......
2011 2032
                    DBTransform dbt = new DBTransform();
2012 2033
                    dbt.transformXMLDocument(doc.toString(user, groups,
2013 2034
                            withInlineData), doctype, "-//W3C//HTML//EN",
2014
                            qformat, out, params);
2035
                            qformat, out, params, null);
2015 2036
                }
2016 2037
                
2017 2038
            }
......
2405 2426
                response.setContentType("text/html");
2406 2427
                trans.transformXMLDocument(output,
2407 2428
                        "message", "-//W3C//HTML//EN", qformat,
2408
                        out, null);
2429
                        out, null, null);
2409 2430
            } catch (Exception e) {
2410 2431
                
2411 2432
                logMetacat.error(
......
2517 2538
                    // Delete from spatial cache if runningSpatialOption
2518 2539
                    if ( PropertyService.getProperty("spatial.runSpatialOption").equals("true") ) {
2519 2540
                        SpatialHarvester sh = new SpatialHarvester();
2520
                        sh.addToDeleteQue( MetacatUtil.getSmartDocId( docid[0] ) );
2541
                        sh.addToDeleteQue( DocumentUtil.getSmartDocId( docid[0] ) );
2521 2542
                        sh.destroy();
2522 2543
                    }
2523 2544
                    
......
3418 3439
                response.setContentType("text/html");
3419 3440
                trans.transformXMLDocument(output,
3420 3441
                        "message", "-//W3C//HTML//EN", qformat,
3421
                        out, null);
3442
                        out, null, null);
3422 3443
            } catch (Exception e) {
3423 3444
                
3424 3445
                logMetacat.error(
......
3610 3631
        int serialNumber = -1;
3611 3632
        
3612 3633
        // get rid of revision if access number has
3613
        docId = MetacatUtil.getDocIdFromString(accessionNumber);
3634
        docId = DocumentUtil.getDocIdFromString(accessionNumber);
3614 3635
        try {
3615 3636
            //check out DBConnection
3616 3637
            conn = DBConnectionPool
src/edu/ucsb/nceas/metacat/ContentTypeProvider.java
59 59
import edu.ucsb.nceas.metacat.database.DBConnection;
60 60
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
61 61
import edu.ucsb.nceas.metacat.service.PropertyService;
62
import edu.ucsb.nceas.metacat.util.DocumentUtil;
62 63
import edu.ucsb.nceas.metacat.util.MetacatUtil;
63 64
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
64 65
/**
......
123 124
   */
124 125
  public ContentTypeProvider(String docIdWithRevision)
125 126
  {
126
    dataFileId = MetacatUtil.getDocIdFromString(docIdWithRevision);
127
    dataFileId = DocumentUtil.getDocIdFromString(docIdWithRevision);
127 128
    //get relative doclist for data file and package type
128 129
    Vector docLists = null;
129 130
    docLists = getRelativeDocIdList(dataFileId);
......
344 345
          if (URLData.indexOf(DBSAXHandler.ECOGRID) != -1 )
345 346
          {
346 347
            // Get docid from url
347
            String docId = MetacatUtil.
348
                               getAccessionNumberFromEcogridIdentifier(URLData);
348
            String docId = 
349
            	DocumentUtil.getAccessionNumberFromEcogridIdentifier(URLData);
349 350
            // Get rid of revision
350
            docId = MetacatUtil.getDocIdFromAccessionNumber(docId);
351
            docId = DocumentUtil.getDocIdFromAccessionNumber(docId);
351 352
            logMetacat.info("docid from url element in xml is: " +
352 353
                                     docId);
353 354
            //if this docid equals target one, we find it
src/edu/ucsb/nceas/metacat/PermissionController.java
39 39
import edu.ucsb.nceas.metacat.database.DBConnection;
40 40
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
41 41
import edu.ucsb.nceas.metacat.service.PropertyService;
42
import edu.ucsb.nceas.metacat.util.DocumentUtil;
42 43
import edu.ucsb.nceas.metacat.util.MetacatUtil;
43 44
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
44 45

  
......
61 62
   public PermissionController(String myDocid) throws McdbException
62 63
   {
63 64
     // Get rid of rev number
64
     docId = MetacatUtil.getSmartDocId(myDocid);
65
     docId = DocumentUtil.getSmartDocId(myDocid);
65 66
     //hasSubTreeAccessControl = checkSubTreeAccessControl();
66 67
   }
67 68

  
......
78 79
     }
79 80
     else
80 81
     {
81
         docId = MetacatUtil.getDocIdFromAccessionNumber(myDocid);
82
         docId = DocumentUtil.getDocIdFromAccessionNumber(myDocid);
82 83
     }
83 84
   }
84 85

  
......
433 434
	 */
434 435
	private boolean isAccessDocument(String docId) throws SQLException {
435 436
		// detele the rev number if docid contains it
436
		docId = MetacatUtil.getDocIdFromString(docId);
437
		docId = DocumentUtil.getDocIdFromString(docId);
437 438
		PreparedStatement pStmt = null;
438 439
		DBConnection conn = null;
439 440
		int serialNumber = -1;
......
1112 1113
            {
1113 1114
                logMetacat.info("Put subtree id " + subTreeId +
1114 1115
                                         " and " + "inline data file name " +
1115
                                         MetacatUtil.
1116
                                         getInlineDataIdWithoutRev(fileId) +
1116
                                         DocumentUtil.getInlineDataIdWithoutRev(fileId) +
1117 1117
                                         " into " + "un" + permission +
1118 1118
                                         " hash");
1119
                unAccessibleIdList.put(subTreeId, MetacatUtil.
1120
                                      getInlineDataIdWithoutRev(fileId));
1119
                unAccessibleIdList.put(subTreeId, 
1120
                		DocumentUtil.getInlineDataIdWithoutRev(fileId));
1121 1121
            }
1122 1122
        }
1123 1123
      }
src/edu/ucsb/nceas/metacat/DocumentImpl.java
64 64
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
65 65
import edu.ucsb.nceas.metacat.spatial.SpatialHarvester;
66 66
import edu.ucsb.nceas.metacat.util.AuthUtil;
67
import edu.ucsb.nceas.metacat.util.DocumentUtil;
67 68
import edu.ucsb.nceas.metacat.util.MetacatUtil;
68 69
import edu.ucsb.nceas.metacat.util.SystemUtil;
69 70
import edu.ucsb.nceas.utilities.FileUtil;
......
190 191
    {
191 192
        try {
192 193
            //this.conn = conn;
193
            this.docid = MetacatUtil.getDocIdFromAccessionNumber(accNum);
194
            this.rev   = MetacatUtil.getRevisionFromAccessionNumber(accNum);
194
            this.docid = DocumentUtil.getDocIdFromAccessionNumber(accNum);
195
            this.rev   = DocumentUtil.getRevisionFromAccessionNumber(accNum);
195 196

  
196 197
            // Look up the document information
197 198
            getDocumentInfo(docid, rev);
......
341 342
            serialNumber = conn.getCheckOutSerialNumber();
342 343
            conn.setAutoCommit(false);
343 344
            String action = null;
344
            String docIdWithoutRev = MetacatUtil.getDocIdFromAccessionNumber(accnum);
345
            int userSpecifyRev = MetacatUtil.getRevisionFromAccessionNumber(accnum);
345
            String docIdWithoutRev = DocumentUtil.getDocIdFromAccessionNumber(accnum);
346
            int userSpecifyRev = DocumentUtil.getRevisionFromAccessionNumber(accnum);
346 347
            action = checkRevInXMLDocuments(docIdWithoutRev, userSpecifyRev);
347 348
            logMetacat.warn("after check rev, the action is "+action);
348 349
            if (action.equals("UPDATE"))
......
421 422
            serialNumber = conn.getCheckOutSerialNumber();
422 423
            conn.setAutoCommit(false);
423 424
            String action = null;
424
            String docIdWithoutRev = MetacatUtil.getDocIdFromAccessionNumber(accnum);
425
            int userSpecifyRev = MetacatUtil.getRevisionFromAccessionNumber(accnum);
425
            String docIdWithoutRev = DocumentUtil.getDocIdFromAccessionNumber(accnum);
426
            int userSpecifyRev = DocumentUtil.getRevisionFromAccessionNumber(accnum);
426 427
            if (tableName.equals(DOCUMENTTABLE))
427 428
            {
428 429
                action = checkRevInXMLDocuments(docIdWithoutRev, userSpecifyRev);
......
750 751
            throws Exception
751 752
    {
752 753
        boolean flag = true;
753
        String docid = MetacatUtil.getDocIdFromString(accnum);
754
        int rev = MetacatUtil.getVersionFromString(accnum);
754
        String docid = DocumentUtil.getDocIdFromString(accnum);
755
        int rev = DocumentUtil.getVersionFromString(accnum);
755 756

  
756 757
        if (serverCode == 1) {
757 758
            flag = true;
......
1207 1208
                    // if it is inline data first to get the inline data
1208 1209
                    // internal id
1209 1210
                    String fileName = currentNode.getNodeData();
1210
                    String accessfileName = MetacatUtil
1211
                            .getDocIdWithoutRevFromInlineDataID(fileName);
1211
                    String accessfileName = 
1212
                    	DocumentUtil.getDocIdWithoutRevFromInlineDataID(fileName);
1212 1213
                    // check if user has read permision for this inline data
1213 1214
                    boolean readInlinedata = false;
1214 1215
                    try {
......
2569 2570
            }
2570 2571

  
2571 2572
            //DocumentIdentifier id = new DocumentIdentifier(accnum);
2572
            int revision = MetacatUtil.getRevisionFromAccessionNumber(accnum);
2573
            int revision = DocumentUtil.getRevisionFromAccessionNumber(accnum);
2573 2574
            String updaterev = (new Integer(revision)).toString();
2574 2575
            String server = ReplicationService
2575 2576
                    .getServerNameForServerCode(serverCode);
......
2800 2801
        String catalogId = null;
2801 2802
        logMetacat.info("user in replication" + user);
2802 2803
        // Docid without revision
2803
        String docid = MetacatUtil.getDocIdFromAccessionNumber(accnum);
2804
        String docid = DocumentUtil.getDocIdFromAccessionNumber(accnum);
2804 2805
        logMetacat.warn("The docid without rev is " + docid);
2805 2806
        // Revision specified by user (int)
2806
        int userSpecifyRev = MetacatUtil.getRevisionFromAccessionNumber(accnum);
2807
        int userSpecifyRev = DocumentUtil.getRevisionFromAccessionNumber(accnum);
2807 2808
        logMetacat.warn("The user specifyRev: " + userSpecifyRev);
2808 2809
        // Revision for this docid in current database
2809 2810
        int revInDataBase = DBUtil.getLatestRevisionInDocumentTable(docid);
......
2953 2954
            String packagedoctype = PropertyService.getProperty("xml.packagedoctype");
2954 2955
            Vector<String> packagedoctypes = new Vector<String>();
2955 2956
            packagedoctypes = MetacatUtil.getOptionList(packagedoctype);
2956
            String docIdWithoutRev = MetacatUtil.getDocIdFromAccessionNumber(accnumber);
2957
            int revision = MetacatUtil.getRevisionFromAccessionNumber(accnumber);
2957
            String docIdWithoutRev = DocumentUtil.getDocIdFromAccessionNumber(accnumber);
2958
            int revision = DocumentUtil.getRevisionFromAccessionNumber(accnumber);
2958 2959
            if (documenttype != null &&
2959 2960
                    packagedoctypes.contains(documenttype)) {
2960 2961
                dbconn = DBConnectionPool.getDBConnection(
......
2965 2966
                String aclidWithRev = RelationHandler.getAccessFileIDWithRevision(docIdWithoutRev);
2966 2967
                if (aclidWithRev != null)
2967 2968
                {
2968
                  String aclid = MetacatUtil.getDocIdFromAccessionNumber(aclidWithRev);
2969
                  revision = MetacatUtil.getRevisionFromAccessionNumber(aclidWithRev);
2969
                  String aclid = DocumentUtil.getDocIdFromAccessionNumber(aclidWithRev);
2970
                  revision = DocumentUtil.getRevisionFromAccessionNumber(aclidWithRev);
2970 2971
                 
2971 2972
                  // if there are access file, write ACL for that package
2972 2973
                  if (aclid != null) {
......
3034 3035
        int serialNumber = -1;
3035 3036
        try {
3036 3037
            //get rid of revision number
3037
            docid = MetacatUtil.getDocIdFromString(accnumber);
3038
            docid = DocumentUtil.getDocIdFromString(accnumber);
3038 3039
            dbConnection = DBConnectionPool.getDBConnection(
3039 3040
                    "DocumentImpl.getDocTypeFromDBForCurrentDoc");
3040 3041
            serialNumber = dbConnection.getCheckOutSerialNumber();
......
3088 3089
            // NEW - WHEN CLIENT ALWAYS PROVIDE ACCESSION NUMBER INCLUDING REV
3089 3090
            // IN IT
3090 3091
            //AccessionNumber ac = new AccessionNumber(accnum, "DELETE");
3091
            String docid = MetacatUtil.getDocIdFromAccessionNumber(accnum);
3092
            String docid = DocumentUtil.getDocIdFromAccessionNumber(accnum);
3092 3093
            //String rev = ac.getRev();
3093 3094

  
3094 3095
            // Check if the document exists.
......
3686 3687
            throws SQLException
3687 3688
    {
3688 3689
        //get rid of revNum part
3689
        String docId = MetacatUtil.getDocIdFromString(accNum);
3690
        String docId = DocumentUtil.getDocIdFromString(accNum);
3690 3691
        PreparedStatement pStmt = null;
3691 3692
        int serverLocation = 1;
3692 3693
        DBConnection conn = null;
......
4170 4171
            dbconn = DBConnectionPool.getDBConnection(
4171 4172
                    "DeletedDocumentImpl.registerDeletedDataFile");
4172 4173
            serialNumber = dbconn.getCheckOutSerialNumber();
4173
            String docIdWithoutRev = MetacatUtil
4174
                    .getDocIdFromAccessionNumber(accnum);
4175
            String rev = MetacatUtil.getRevisionStringFromString(accnum);
4174
            String docIdWithoutRev = 
4175
            	DocumentUtil.getDocIdFromAccessionNumber(accnum);
4176
            String rev = DocumentUtil.getRevisionStringFromString(accnum);
4176 4177
            writeDocumentToRevisionTable(dbconn, docIdWithoutRev, 
4177 4178
                    rev, doctype, docname, user,
4178 4179
                    null, serverCode, -1, createDate, updateDate); 
src/edu/ucsb/nceas/metacat/RelationHandler.java
24 24
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
25 25
import edu.ucsb.nceas.metacat.service.PropertyService;
26 26
import edu.ucsb.nceas.metacat.util.MetacatUtil;
27
import edu.ucsb.nceas.metacat.util.DocumentUtil;
27 28
import edu.ucsb.nceas.morpho.datapackage.Triple;
28 29
import edu.ucsb.nceas.morpho.datapackage.TripleCollection;
29 30
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
......
114 115
        logMetacat.info("relationship from triple:"+triple.getRelationship());
115 116
        logMetacat.info("object from triple: "+triple.getObject());
116 117
        //subject = (new DocumentIdentifier(triple.getSubject())).getIdentifier();
117
        subject = MetacatUtil.getDocIdFromString(triple.getSubject());
118
        subject = DocumentUtil.getDocIdFromString(triple.getSubject());
118 119
        relationship = triple.getRelationship();
119 120
        //object = (new DocumentIdentifier(triple.getObject())).getIdentifier();
120
        object = MetacatUtil.getDocIdFromString(triple.getObject());
121
        object = DocumentUtil.getDocIdFromString(triple.getObject());
121 122
        
122 123
        if (subject != null && relationship != null && object != null)
123 124
        {
src/edu/ucsb/nceas/metacat/DBUtil.java
50 50
import edu.ucsb.nceas.metacat.database.DBConnection;
51 51
import edu.ucsb.nceas.metacat.database.DBConnectionPool;
52 52
import edu.ucsb.nceas.metacat.service.PropertyService;
53
import edu.ucsb.nceas.metacat.util.MetacatUtil;
53
import edu.ucsb.nceas.metacat.util.DocumentUtil;
54 54
import edu.ucsb.nceas.metacat.util.SystemUtil;
55 55
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
56 56

  
......
632 632
    String docType = null;
633 633
    
634 634
    // Get docid without rev
635
    docIdWithoutRevision = MetacatUtil.getDocIdFromString(givenDocId);
635
    docIdWithoutRevision = DocumentUtil.getDocIdFromString(givenDocId);
636 636
    // SQL comand is:
637 637
    sqlCommand = "select rev, doctype from xml_documents where docid like ?";
638 638
    
src/edu/ucsb/nceas/metacat/util/MetacatUtil.java
33 33
import java.io.PrintWriter;
34 34
import java.net.MalformedURLException;
35 35
import java.util.Hashtable;
36
import java.util.Stack;
37 36
import java.util.Vector;
38 37

  
39 38
import org.apache.log4j.Logger;
......
41 40
import com.oreilly.servlet.multipart.FilePart;
42 41

  
43 42
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
44
import edu.ucsb.nceas.metacat.DBSAXHandler;
45
import edu.ucsb.nceas.metacat.NodeRecord;
46 43
import edu.ucsb.nceas.metacat.service.PropertyService;
47
import edu.ucsb.nceas.metacat.service.ServiceService;
48
import edu.ucsb.nceas.metacat.service.SkinPropertyService;
49
import edu.ucsb.nceas.metacat.shared.MetacatUtilException;
50
import edu.ucsb.nceas.metacat.shared.ServiceException;
51
import edu.ucsb.nceas.utilities.GeneralPropertyException;
52 44
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
53 45
import edu.ucsb.nceas.utilities.FileUtil;
54
import edu.ucsb.nceas.utilities.UtilException;
55 46

  
56 47
/**
57 48
 * A suite of utility classes for the metadata catalog server
......
59 50
public class MetacatUtil
60 51
{
61 52

  
53
    public static final String XMLFORMAT = "xml";	
62 54
    public static AbstractDatabase dbAdapter;
63 55
    
64 56
    private static boolean debugErrorDisplayed = false;
65 57
    
66 58
    private static Logger logMetacat = Logger.getLogger(MetacatUtil.class);
67
    private static char separator = '.';
68 59

  
69
    static {
70
        try {
71
        	separator = PropertyService.getProperty("document.accNumSeparator").charAt(0);
72
        } catch (PropertyNotFoundException pnfe) {
73
        	logMetacat.error("Could not retrieve account number separator. " 
74
        			+ "Separator set to '.' : " + pnfe.getMessage());
75
        }
76
    }
77

  
78 60
    /**
79 61
     * Utility method to parse the query part of a URL into parameters. This
80
     * method assumes the format of the query par tof the url is an ampersand
62
     * method assumes the format of the query part of the url is an ampersand
81 63
     * separated list of name/value pairs, with equal signs separating the name
82 64
     * from the value (e.g., name=tom&zip=99801 ). Returns a has of the name
83 65
     * value pairs, hashed on name.
......
290 272
    }
291 273

  
292 274
    /**
293
     * Get docid from online/url string
294
     */
295
    public static String getDocIdWithRevFromOnlineURL(String url)
296
    {
297
        String docid = null;
298
        String DOCID = "docid";
299
        boolean find = false;
300
        char limited = '&';
301
        int count = 0; //keep track how many & was found
302
        Vector list = new Vector();// keep index number for &
303
        if (url == null) {
304
            logMetacat.info("url is null and null will be returned");
305
            return docid;
306
        }
307
        // the first element in list is 0
308
        list.add(new Integer(0));
309
        for (int i = 0; i < url.length(); i++) {
310
            if (url.charAt(i) == limited) {
311
                // count plus 1
312
                count++;
313
                list.add(new Integer(i));
314
                // get substring beween two &
315
                String str = url.substring(
316
                        ((Integer) list.elementAt(count - 1)).intValue(), i);
317
                logMetacat.info("substring between two & is: " + str);
318
                //if the subString contains docid, we got it
319
                if (str.indexOf(DOCID) != -1) {
320
                    //get index of '="
321
                    int start = getIndexForGivenChar(str, '=') + 1;
322
                    int end = str.length();
323
                    docid = str.substring(start, end);
324
                    find = true;
325
                }//if
326
            }//if
327
        }//for
328
        //if not find, we need check the subtring between the index of last &
329
        // and
330
        // the end of string
331
        if (!find) {
332
            logMetacat.info("Checking the last substring");
333
            String str = url.substring(((Integer) list.elementAt(count))
334
                    .intValue() + 1, url.length());
335
            logMetacat.info("Last substring is: " + str);
336
            if (str.indexOf(DOCID) != -1) {
337
                //get index of '="
338
                int start = getIndexForGivenChar(str, '=') + 1;
339
                int end = str.length();
340
                docid = str.substring(start, end);
341
                find = true;
342
            }//if
343
        }//if
344
        logMetacat.info("The docid from online url is:" + docid);
345
        return docid.trim();
346
    }
347

  
348

  
349
    /**
350
     * Eocgorid identifier will look like: ecogrid://knb/tao.1.1
351
     * The AccessionNumber tao.1.1 will be returned. If the given doesn't
352
     * contains ecogrid, null will be returned.
353
     * @param identifier String
354
     * @return String
355
     */
356
    public static String getAccessionNumberFromEcogridIdentifier(String identifier)
357
    {
358
      String accessionNumber = null;
359
      if (identifier != null && identifier.startsWith(DBSAXHandler.ECOGRID))
360
      {
361
        // find the last "/" in identifier
362
        int indexOfLastSlash = identifier.lastIndexOf("/");
363
        int start = indexOfLastSlash+1;
364
        int end   = identifier.length();
365
        accessionNumber = identifier.substring(start, end);
366
      }
367
      logMetacat.warn("The accession number from url is " +
368
                                 accessionNumber);
369
      return accessionNumber;
370
    }
371

  
372
    private static int getIndexForGivenChar(String str, char character)
373
    {
374
        int index = -1;
375
        // make sure str is not null
376
        if (str == null) {
377
            logMetacat.info(
378
                    "The given str is null and -1 will be returned");
379
            return index;
380
        }
381
        // got though the string
382
        for (int i = 0; i < str.length(); i++) {
383
            // find the first one then break the loop
384
            if (str.charAt(i) == character) {
385
                index = i;
386
                break;
387
            }//if
388
        }//for
389
        logMetacat.info("the index for char " + character + " is: "
390
                + index);
391
        return index;
392
    }
393

  
394
    /**
395
     * Utility method to get docid from a given string
396
     *
397
     * @param string, the given string should be these two format: 1) str1.str2
398
     *            in this case docid= str1.str2 2) str1.str2.str3, in this case
399
     *            docid =str1.str2
400
     * @param the sperator char
401
     */
402
    public static String getDocIdFromString(String str)
403
    {
404
        String docId = null;
405
        if (str == null) {
406
            logMetacat.info(
407
                    "The given str is null and null will be returned"
408
                            + " in getDocIdfromString");
409
            return docId;
410
        } //make sure docid is not null
411
        int dotNumber = 0;//count how many dots in given string
412
        int indexOfLastDot = 0;
413

  
414
        for (int i = 0; i < str.length(); i++) {
415
            if (str.charAt(i) == separator) {
416
                dotNumber++;//count how many dots
417
                indexOfLastDot = i;//keep the last dot postion
418
            }
419
        }//for
420

  
421
        //The string formatt is wrong, because it has more than two or less
422
        // than
423
        //one seperator
424
        if (dotNumber > 2 || dotNumber < 1) {
425
            docId = null;
426
        } else if (dotNumber == 2) //the case for str1.str2.str3
427
        {
428
            docId = str.substring(0, indexOfLastDot);
429
        } else if (dotNumber == 1) //the case for str1.str2
430
        {
431
            docId = str;
432
        }
433

  
434
        return docId;
435
    }//getDocIdFromString
436

  
437
    /**
438
     * Utility method to get version number from a given string
439
     *
440
     * @param string, the given string should be these two format: 1)
441
     *            str1.str2(no version) version =-1; 2) str1.str2.str3, in this
442
     *            case version = str3; 3) other, vresion =-2
443
     */
444
    public static int getVersionFromString(String str)
445
            throws NumberFormatException
446
    {
447
        int version = -1;
448
        String versionString = null;
449
        int dotNumber = 0;//count how many dots in given string
450
        int indexOfLastDot = 0;
451

  
452
        for (int i = 0; i < str.length(); i++) {
453
            if (str.charAt(i) == separator) {
454
                dotNumber++;//count how many dots
455
                indexOfLastDot = i;//keep the last dot postion
456
            }
457
        }//for
458

  
459
        //The string formatt is wrong, because it has more than two or less
460
        // than
461
        //one seperator
462
        if (dotNumber > 2 || dotNumber < 1) {
463
            version = -2;
464
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1)))
465
        //the case for str1.str2.str3
466
        {
467
            versionString = str.substring((indexOfLastDot + 1), str.length());
468
            version = Integer.parseInt(versionString);
469
        } else if (dotNumber == 1) //the case for str1.str2
470
        {
471
            version = -1;
472
        }
473

  
474
        return version;
475
    }//getVersionFromString
476

  
477
    /**
478
     * Utility method to get version string from a given string
479
     *
480
     * @param string, the given string should be these two format: 1)
481
     *            str1.str2(no version) version=null; 2) str1.str2.str3, in
482
     *            this case version = str3; 3) other, vresion =null;
483
     */
484
    public static String getRevisionStringFromString(String str)
485
            throws NumberFormatException
486
    {
487
        // String to store the version
488
        String versionString = null;
489
        int dotNumber = 0;//count how many dots in given string
490
        int indexOfLastDot = 0;
491

  
492
        for (int i = 0; i < str.length(); i++) {
493
            if (str.charAt(i) == separator) {
494
                dotNumber++;//count how many dots
495
                indexOfLastDot = i;//keep the last dot postion
496
            }
497
        }//for
498

  
499
        //The string formatt is wrong, because it has more than two or less
500
        // than
501
        //one seperator
502
        if (dotNumber > 2 || dotNumber < 1) {
503
            versionString = null;
504
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1))) {
505
            //the case for str1.str2.str3
506
            // indexOfLastDot != (str.length() -1) means get rid of str1.str2.
507
            versionString = str.substring((indexOfLastDot + 1), str.length());
508
        } else if (dotNumber == 1) //the case for str1.str2 or str1.str2.
509
        {
510
            versionString = null;
511
        }
512

  
513
        return versionString;
514
    }//getVersionFromString
515

  
516
    /**
517
     * This method will get docid from an AccessionNumber. There is no
518
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
519
     * we think the docid will be get rid of last part
520
     */
521
    public static String getDocIdFromAccessionNumber(String accessionNumber)
522
    {
523
        String docid = null;
524
        if (accessionNumber == null) { return docid; }
525
        int indexOfLastSeperator = accessionNumber.lastIndexOf(separator);
526
        docid = accessionNumber.substring(0, indexOfLastSeperator);
527
        logMetacat.info("after parsing accessionnumber, docid is "
528
                + docid);
529
        return docid;
530
    }
531

  
532
    /**
533
     * This method will get inline data id without the revision number.
534
     * So if inlineData.1.2 is passed as input, inlineData.2 is returned.
535
     */
536
    public static String getInlineDataIdWithoutRev(String accessionNumber)
537
    {
538
        String docid = null;
539
        if (accessionNumber == null) { return docid; }
540
        int indexOfLastSeperator = accessionNumber.lastIndexOf(separator);
541
        String version = accessionNumber.substring(indexOfLastSeperator,
542
                                                   accessionNumber.length());
543
        accessionNumber = accessionNumber.substring(0, indexOfLastSeperator);
544
        indexOfLastSeperator = accessionNumber.lastIndexOf(separator);
545
        docid = accessionNumber.substring(0, indexOfLastSeperator) + version;
546
        logMetacat.info("after parsing accessionnumber, docid is "
547
                                 + docid);
548

  
549
        return docid;
550
    }
551

  
552
    /**
553
     * This method will call both getDocIdFromString and
554
     * getDocIdFromAccessionNumber. So first, if the string looks str1.str2,
555
     * the docid will be str1.str2. If the string is str1.str2.str3, the docid
556
     * will be str1.str2. If the string is str1.str2.str3.str4 or more, the
557
     * docid will be str1.str2.str3. If the string look like str1, null will be
558
     * returned
559
     *
560
     */
561
    public static String getSmartDocId(String str)
562
    {
563
        String docid = null;
564
        //call geDocIdFromString first.
565
        docid = getDocIdFromString(str);
566
        // If docid is null, try to call getDocIdFromAccessionNumber
567
        // it will handle the seperator more than2
568
        if (docid == null) {
569
            docid = getDocIdFromAccessionNumber(str);
570
        }
571
        logMetacat.info("The docid get from smart docid getor is "
572
                + docid);
573
        return docid;
574
    }
575

  
576
    /**
577
     * This method will get revision from an AccessionNumber. There is no
578
     * assumption the accessnumber will be str1.str2.str3. It can be more. So
579
     * we think the docid will be get rid of last part
580
     */
581
    public static int getRevisionFromAccessionNumber(String accessionNumber)
582
            throws NumberFormatException
583
    {
584
        String rev = null;
585
        int revNumber = -1;
586
        if (accessionNumber == null) { return revNumber; }
587
        int indexOfLastSeperator = accessionNumber.lastIndexOf(separator);
588
        rev = accessionNumber.substring(indexOfLastSeperator + 1,
589
                accessionNumber.length());
590
        revNumber = Integer.parseInt(rev);
591
        logMetacat.info("after parsing accessionnumber, rev is "
592
                + revNumber);
593
        return revNumber;
594
    }
595

  
596
    /**
597 275
     * Method to get the name of local replication server
598 276
     */
599 277
    public static String getLocalReplicationServerName()
......
616 294

  
617 295
    }
618 296

  
619
    /**
620
     * Method to get docidwithrev from eml2 inline data id The eml inline data
621
     * id would look like eml.200.2.3
622
     */
623
    public static String getDocIdWithoutRevFromInlineDataID(String inlineDataID)
624
    {
625
        String docidWithoutRev = null;
626
        if (inlineDataID == null) { return docidWithoutRev; }
627
        char charSeperator = separator;
628
        int targetNumberOfSeperator = 2;// we want to know his index
629
        int numberOfSeperator = 0;
630
        for (int i = 0; i < inlineDataID.length(); i++) {
631
            // meet seperator, increase number of seperator
632
            if (inlineDataID.charAt(i) == charSeperator) {
633
                numberOfSeperator++;
634
            }
635
            // if number of seperator reach the target one, record the index(i)
636
            // and get substring and terminate the loop
637
            if (numberOfSeperator == targetNumberOfSeperator) {
638
                docidWithoutRev = inlineDataID.substring(0, i);
639
                break;
640
            }
641
        }
642

  
643
        logMetacat.info("Docid without rev from inlinedata id: "
644
                + docidWithoutRev);
645
        return docidWithoutRev;
646

  
647
    }
648

  
649
    /**
650
     * Revise stack change a stack to opposite order
651
     */
652
    public static Stack<NodeRecord> reviseStack(Stack<NodeRecord> stack)
653
    {
654
        Stack result = new Stack();
655
        // make sure the parameter is correct
656
        if (stack == null || stack.isEmpty()) {
657
            result = stack;
658
            return result;
659
        }
660

  
661
        while (!stack.isEmpty()) {
662
            Object obj = stack.pop();
663
            result.push(obj);
664
        }
665
        return result;
666
    }
667

  
668 297
    /** A method to replace whitespace in url */
669 298
    public static String replaceWhiteSpaceForURL(String urlHasWhiteSpace)
670 299
    {
......
909 538
        }
910 539
        return new File(dirname);
911 540
    }
912

  
913
	/**
914
	 * Reports whether metacat is fully configured.
915
	 * 
916
	 * @return a boolean that is true if all sections are configured and 
917
	 * false otherwise
918
	 */
919
	public static boolean isMetacatConfigured() {
920
		boolean metacatConfigured = false;
921
		try {			
922
			metacatConfigured = PropertyService.arePropertiesConfigured()
923
					&& AuthUtil.isAuthConfigured()
924
					&& SkinUtil.areSkinsConfigured()
925
					&& DatabaseUtil.isDatabaseConfigured()
926
					&& GeoserverUtil.isGeoserverConfigured()
927
					&& isBackupDirConfigured();
928
		} catch (MetacatUtilException ue) {
929
			logMetacat.error("Could not determine if metacat is configured due to utility exception: "
930
					+ ue.getMessage());
931
		} catch (PropertyNotFoundException pnfe) {
932
			logMetacat.error("Could not determine if metacat is configured due to property exception: "
933
					+ pnfe.getMessage());
934
		}
935

  
936
		return metacatConfigured;
937
	}
938

  
939
	/**
940
	 * Check if the application.backupDir property is populated in
941
	 * metacat.properties and that it points to a writable directory.
942
	 * 
943
	 * @return false if the application.backupDir property does not point to a
944
	 *         writable directory.
945
	 */
946
	public static boolean isBackupDirConfigured() throws MetacatUtilException, PropertyNotFoundException {
947
		String backupDir = PropertyService.getProperty("application.backupDir");
948
		if (backupDir == null || backupDir.equals("")) {
949
			return false;
950
		}		
951
		if (FileUtil.getFileStatus(backupDir) < FileUtil.EXISTS_READ_WRITABLE) {
952
			return false;
953
		}	
954
		return true;
955
	}
956
		
957
	/**
958
	 * Reports whether the metacat configuration utility should be run. Returns
959
	 * false if 
960
	 *   -- dev.runConfiguration=false and 
961
	 *   -- backup properties file exists 
962
	 * Note that dev.runConfiguration should only be set to false when reinstalling the 
963
	 * same version of the application in development.
964
	 * 
965
	 * @return a boolean that is false if dev.runConfiguration is false and the
966
	 *         backup properties file exists.
967
	 */
968
	public static boolean bypassConfiguration() throws MetacatUtilException, ServiceException {
969
		try {
970
			// If the system is not configured to do bypass, return false.
971
			if (!PropertyService.doBypass()) {
972
				return false;
973
			}
974

  
975
			// Get the most likely backup files.  If these cannot be found, we 
976
			// cannot do the configuration bypass.
977
			String ExternalBaseDir = SystemUtil.discoverExternalDir();
978
			if (ExternalBaseDir == null) {
979
				logMetacat.error("bypassConfiguration: Could not find backup directory.");
980
				// could not find backup files ... force the configuration
981
				return false;
982
			}
983
			String realContext = ServiceService.getRealApplicationContext();
984
			PropertyService.setRecommendedExternalDir(ExternalBaseDir);
985
			PropertyService.setProperty("application.backupDir", 
986
					ExternalBaseDir + FileUtil.getFS() + "." + realContext);
987

  
988
			// Refresh the property service and skin property service.  This will pick up 
989
			// the backup directory and populate backup properties in caches.
990
			ServiceService.refreshService("PropertyService");
991
			ServiceService.refreshService("SkinPropertyService");
992

  
993
			// Call bypassConfiguration to make sure backup properties get persisted 
994
			// to active properties for both main and skin properties.
995
			PropertyService.bypassConfiguration();
996
			SkinPropertyService.bypassConfiguration();
997

  
998
			return true;
999
		} catch (GeneralPropertyException gpe) {
1000
			throw new MetacatUtilException("Property error while discovering backup directory: "
1001
					+ gpe.getMessage());
1002
		} catch (MetacatUtilException mue) {
1003
			throw new MetacatUtilException("Utility error while discovering backup directory: "
1004
					+ mue.getMessage());
1005
		}
1006

  
1007
	}
1008
		
1009 541
}
src/edu/ucsb/nceas/metacat/util/DocumentUtil.java
1
/**
2
 *  '$RCSfile$'
3
 *    Purpose: A Class that implements utility methods for a metadata catalog
4
 *  Copyright: 2009 Regents of the University of California and the
5
 *             National Center for Ecological Analysis and Synthesis
6
 *    Authors: Michael Daigle
7
 *
8
 *   '$Author: daigle $'
9
 *     '$Date: 2009-08-04 14:32:58 -0700 (Tue, 04 Aug 2009) $'
10
 * '$Revision: 5015 $'
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 2 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program; if not, write to the Free Software
24
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
 */
26

  
27
package edu.ucsb.nceas.metacat.util;
28

  
29
import java.util.Stack;
30
import java.util.Vector;
31

  
32
import org.apache.log4j.Logger;
33

  
34
import edu.ucsb.nceas.dbadapter.AbstractDatabase;
35
import edu.ucsb.nceas.metacat.DBSAXHandler;
36
import edu.ucsb.nceas.metacat.NodeRecord;
37
import edu.ucsb.nceas.metacat.service.PropertyService;
38
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
39

  
40
/**
41
 * A suite of utility classes for the metadata catalog server
42
 */
43
public class DocumentUtil
44
{
45
	
46
    public static AbstractDatabase dbAdapter;
47
    
48
    private static Logger logMetacat = Logger.getLogger(DocumentUtil.class);
49
    private static char separator = '.';
50

  
51
    static {
52
        try {
53
        	separator = PropertyService.getProperty("document.accNumSeparator").charAt(0);
54
        } catch (PropertyNotFoundException pnfe) {
55
        	logMetacat.error("Could not retrieve account number separator. " 
56
        			+ "Separator set to '.' : " + pnfe.getMessage());
57
        }
58
    }
59

  
60
    /**
61
     * Get docid from online/url string
62
     */
63
    public static String getDocIdWithRevFromOnlineURL(String url)
64
    {
65
        String docid = null;
66
        String DOCID = "docid";
67
        boolean find = false;
68
        char limited = '&';
69
        int count = 0; //keep track how many & was found
70
        Vector list = new Vector();// keep index number for &
71
        if (url == null) {
72
            logMetacat.info("url is null and null will be returned");
73
            return docid;
74
        }
75
        // the first element in list is 0
76
        list.add(new Integer(0));
77
        for (int i = 0; i < url.length(); i++) {
78
            if (url.charAt(i) == limited) {
79
                // count plus 1
80
                count++;
81
                list.add(new Integer(i));
82
                // get substring beween two &
83
                String str = url.substring(
84
                        ((Integer) list.elementAt(count - 1)).intValue(), i);
85
                logMetacat.info("substring between two & is: " + str);
86
                //if the subString contains docid, we got it
87
                if (str.indexOf(DOCID) != -1) {
88
                    //get index of '="
89
                    int start = getIndexForGivenChar(str, '=') + 1;
90
                    int end = str.length();
91
                    docid = str.substring(start, end);
92
                    find = true;
93
                }//if
94
            }//if
95
        }//for
96
        //if not find, we need check the subtring between the index of last &
97
        // and
98
        // the end of string
99
        if (!find) {
100
            logMetacat.info("Checking the last substring");
101
            String str = url.substring(((Integer) list.elementAt(count))
102
                    .intValue() + 1, url.length());
103
            logMetacat.info("Last substring is: " + str);
104
            if (str.indexOf(DOCID) != -1) {
105
                //get index of '="
106
                int start = getIndexForGivenChar(str, '=') + 1;
107
                int end = str.length();
108
                docid = str.substring(start, end);
109
                find = true;
110
            }//if
111
        }//if
112
        logMetacat.info("The docid from online url is:" + docid);
113
        return docid.trim();
114
    }
115

  
116

  
117
    /**
118
     * Eocgorid identifier will look like: ecogrid://knb/tao.1.1
119
     * The AccessionNumber tao.1.1 will be returned. If the given doesn't
120
     * contains ecogrid, null will be returned.
121
     * @param identifier String
122
     * @return String
123
     */
124
    public static String getAccessionNumberFromEcogridIdentifier(String identifier)
125
    {
126
      String accessionNumber = null;
127
      if (identifier != null && identifier.startsWith(DBSAXHandler.ECOGRID))
128
      {
129
        // find the last "/" in identifier
130
        int indexOfLastSlash = identifier.lastIndexOf("/");
131
        int start = indexOfLastSlash+1;
132
        int end   = identifier.length();
133
        accessionNumber = identifier.substring(start, end);
134
      }
135
      logMetacat.warn("The accession number from url is " +
136
                                 accessionNumber);
137
      return accessionNumber;
138
    }
139

  
140
    private static int getIndexForGivenChar(String str, char character)
141
    {
142
        int index = -1;
143
        // make sure str is not null
144
        if (str == null) {
145
            logMetacat.info(
146
                    "The given str is null and -1 will be returned");
147
            return index;
148
        }
149
        // got though the string
150
        for (int i = 0; i < str.length(); i++) {
151
            // find the first one then break the loop
152
            if (str.charAt(i) == character) {
153
                index = i;
154
                break;
155
            }//if
156
        }//for
157
        logMetacat.info("the index for char " + character + " is: "
158
                + index);
159
        return index;
160
    }
161

  
162
    /**
163
     * Utility method to get docid from a given string
164
     *
165
     * @param string, the given string should be these two format: 1) str1.str2
166
     *            in this case docid= str1.str2 2) str1.str2.str3, in this case
167
     *            docid =str1.str2
168
     * @param the sperator char
169
     */
170
    public static String getDocIdFromString(String str)
171
    {
172
        String docId = null;
173
        if (str == null) {
174
            logMetacat.info(
175
                    "The given str is null and null will be returned"
176
                            + " in getDocIdfromString");
177
            return docId;
178
        } //make sure docid is not null
179
        int dotNumber = 0;//count how many dots in given string
180
        int indexOfLastDot = 0;
181

  
182
        for (int i = 0; i < str.length(); i++) {
183
            if (str.charAt(i) == separator) {
184
                dotNumber++;//count how many dots
185
                indexOfLastDot = i;//keep the last dot postion
186
            }
187
        }//for
188

  
189
        //The string formatt is wrong, because it has more than two or less
190
        // than
191
        //one seperator
192
        if (dotNumber > 2 || dotNumber < 1) {
193
            docId = null;
194
        } else if (dotNumber == 2) //the case for str1.str2.str3
195
        {
196
            docId = str.substring(0, indexOfLastDot);
197
        } else if (dotNumber == 1) //the case for str1.str2
198
        {
199
            docId = str;
200
        }
201

  
202
        return docId;
203
    }//getDocIdFromString
204

  
205
    /**
206
     * Utility method to get version number from a given string
207
     *
208
     * @param string, the given string should be these two format: 1)
209
     *            str1.str2(no version) version =-1; 2) str1.str2.str3, in this
210
     *            case version = str3; 3) other, vresion =-2
211
     */
212
    public static int getVersionFromString(String str)
213
            throws NumberFormatException
214
    {
215
        int version = -1;
216
        String versionString = null;
217
        int dotNumber = 0;//count how many dots in given string
218
        int indexOfLastDot = 0;
219

  
220
        for (int i = 0; i < str.length(); i++) {
221
            if (str.charAt(i) == separator) {
222
                dotNumber++;//count how many dots
223
                indexOfLastDot = i;//keep the last dot postion
224
            }
225
        }//for
226

  
227
        //The string formatt is wrong, because it has more than two or less
228
        // than
229
        //one seperator
230
        if (dotNumber > 2 || dotNumber < 1) {
231
            version = -2;
232
        } else if (dotNumber == 2 && (indexOfLastDot != (str.length() - 1)))
233
        //the case for str1.str2.str3
234
        {
235
            versionString = str.substring((indexOfLastDot + 1), str.length());
236
            version = Integer.parseInt(versionString);
237
        } else if (dotNumber == 1) //the case for str1.str2
238
        {
239
            version = -1;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff