Project

General

Profile

« Previous | Next » 

Revision 4967

Added by daigle over 15 years ago

Workflow scheduler and archiving fixes for TPC workflow engine

View differences:

src/edu/ucsb/nceas/shared/xsd/IOException.java
1
/**
2
 * IOException.java
3
 *
4
 * This file was auto-generated from WSDL
5
 * by the Apache Axis 1.3 Oct 05, 2005 (05:23:37 EDT) WSDL2Java emitter.
6
 */
7

  
8
package edu.ucsb.nceas.shared.xsd;
9

  
10
public class IOException  extends org.kepler.executionWS.xsd.Exception  implements java.io.Serializable {
11
    public IOException() {
12
    }
13

  
14
    public IOException(
15
           java.lang.Object exception) {
16
        super(
17
            exception);
18
    }
19

  
20
    private java.lang.Object __equalsCalc = null;
21
    public synchronized boolean equals(java.lang.Object obj) {
22
        if (!(obj instanceof IOException)) return false;
23
        IOException other = (IOException) obj;
24
        if (obj == null) return false;
25
        if (this == obj) return true;
26
        if (__equalsCalc != null) {
27
            return (__equalsCalc == obj);
28
        }
29
        __equalsCalc = obj;
30
        boolean _equals;
31
        _equals = super.equals(obj);
32
        __equalsCalc = null;
33
        return _equals;
34
    }
35

  
36
    private boolean __hashCodeCalc = false;
37
    public synchronized int hashCode() {
38
        if (__hashCodeCalc) {
39
            return 0;
40
        }
41
        __hashCodeCalc = true;
42
        int _hashCode = super.hashCode();
43
        __hashCodeCalc = false;
44
        return _hashCode;
45
    }
46

  
47
    // Type metadata
48
    private static org.apache.axis.description.TypeDesc typeDesc =
49
        new org.apache.axis.description.TypeDesc(IOException.class, true);
50

  
51
    static {
52
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://io.java/xsd", "IOException"));
53
    }
54

  
55
    /**
56
     * Return type metadata object
57
     */
58
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
59
        return typeDesc;
60
    }
61

  
62
    /**
63
     * Get Custom Serializer
64
     */
65
    public static org.apache.axis.encoding.Serializer getSerializer(
66
           java.lang.String mechType, 
67
           java.lang.Class _javaType,  
68
           javax.xml.namespace.QName _xmlType) {
69
        return 
70
          new  org.apache.axis.encoding.ser.BeanSerializer(
71
            _javaType, _xmlType, typeDesc);
72
    }
73

  
74
    /**
75
     * Get Custom Deserializer
76
     */
77
    public static org.apache.axis.encoding.Deserializer getDeserializer(
78
           java.lang.String mechType, 
79
           java.lang.Class _javaType,  
80
           javax.xml.namespace.QName _xmlType) {
81
        return 
82
          new  org.apache.axis.encoding.ser.BeanDeserializer(
83
            _javaType, _xmlType, typeDesc);
84
    }
85

  
86
}
src/edu/ucsb/nceas/shared/xsd/FileNotFoundException.java
1
/**
2
 * FileNotFoundException.java
3
 *
4
 * This file was auto-generated from WSDL
5
 * by the Apache Axis 1.3 Oct 05, 2005 (05:23:37 EDT) WSDL2Java emitter.
6
 */
7

  
8
package edu.ucsb.nceas.shared.xsd;
9

  
10
public class FileNotFoundException  extends edu.ucsb.nceas.shared.xsd.IOException  implements java.io.Serializable {
11

  
12
	private static final long serialVersionUID = -9077623505512220104L;
13
	
14
	public FileNotFoundException() {
15
    }
16

  
17
    public FileNotFoundException(
18
           java.lang.Object exception) {
19
        super(
20
            exception);
21
    }
22

  
23
    private java.lang.Object __equalsCalc = null;
24
    public synchronized boolean equals(java.lang.Object obj) {
25
        if (!(obj instanceof FileNotFoundException)) return false;
26
        FileNotFoundException other = (FileNotFoundException) obj;
27
        if (obj == null) return false;
28
        if (this == obj) return true;
29
        if (__equalsCalc != null) {
30
            return (__equalsCalc == obj);
31
        }
32
        __equalsCalc = obj;
33
        boolean _equals;
34
        _equals = super.equals(obj);
35
        __equalsCalc = null;
36
        return _equals;
37
    }
38

  
39
    private boolean __hashCodeCalc = false;
40
    public synchronized int hashCode() {
41
        if (__hashCodeCalc) {
42
            return 0;
43
        }
44
        __hashCodeCalc = true;
45
        int _hashCode = super.hashCode();
46
        __hashCodeCalc = false;
47
        return _hashCode;
48
    }
49

  
50
    // Type metadata
51
    private static org.apache.axis.description.TypeDesc typeDesc =
52
        new org.apache.axis.description.TypeDesc(FileNotFoundException.class, true);
53

  
54
    static {
55
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://io.java/xsd", "FileNotFoundException"));
56
    }
57

  
58
    /**
59
     * Return type metadata object
60
     */
61
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
62
        return typeDesc;
63
    }
64

  
65
    /**
66
     * Get Custom Serializer
67
     */
68
    public static org.apache.axis.encoding.Serializer getSerializer(
69
           java.lang.String mechType, 
70
           java.lang.Class _javaType,  
71
           javax.xml.namespace.QName _xmlType) {
72
        return 
73
          new  org.apache.axis.encoding.ser.BeanSerializer(
74
            _javaType, _xmlType, typeDesc);
75
    }
76

  
77
    /**
78
     * Get Custom Deserializer
79
     */
80
    public static org.apache.axis.encoding.Deserializer getDeserializer(
81
           java.lang.String mechType, 
82
           java.lang.Class _javaType,  
83
           javax.xml.namespace.QName _xmlType) {
84
        return 
85
          new  org.apache.axis.encoding.ser.BeanDeserializer(
86
            _javaType, _xmlType, typeDesc);
87
    }
88

  
89
}
src/edu/ucsb/nceas/metacat/ArchiveHandler.java
39 39
import edu.ucsb.nceas.metacat.util.MetacatUtilException;
40 40
import edu.ucsb.nceas.metacat.util.ResponseUtil;
41 41
import edu.ucsb.nceas.utilities.FileUtil;
42
import edu.ucsb.nceas.utilities.LSIDUtil;
43
import edu.ucsb.nceas.utilities.ParseLSIDException;
42 44
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
43 45
import edu.ucsb.nceas.utilities.UtilException;
44 46

  
......
80 82
            if (params.containsKey("docid")) {
81 83
                docs = params.get("docid");
82 84
                docid = docs[0];
85
                if (docid.startsWith("urn:")) {
86
                	docid = LSIDUtil.getDocId(docid, true);               	
87
                }
83 88
            } else { 
84
            	throw new HandlerException("Could not find doc id in params when reading archive entry");
89
            	throw new HandlerException("ArchiveHandler.readArchiveEntry - Could not find doc " 
90
            			+ "id in params when reading archive entry");
85 91
            } 
86 92
            
87 93
            // read the archive file entry name from params
......
89 95
            	archiveEntryNames = params.get("archiveEntryName");
90 96
            	archiveEntryName = archiveEntryNames[0];
91 97
            } else { 
92
            	throw new HandlerException("Could not find archiveEntryName in params when reading archive entry");
98
            	throw new HandlerException("ArchiveHandler.readArchiveEntry - Could not find " 
99
            			+ "archiveEntryName in params when reading archive entry");
93 100
            } 
94 101
            
95 102
            // qformat is used to hold the type of archive and the format of the content that we wish to 
......
102 109
            	qformat = "jar-file";
103 110
            }       
104 111
            
105
            //check the permission for read
106
            try {
107
            	if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
108
            		String errorString = "User " + user + " does not have permission"
109
    					+ " to read the document with the docid " + docid;
110
            		ResponseUtil.sendErrorXML(response, ResponseUtil.NO_READ_PERMISSION, errorString);
111
            		return;
112
            	}
113
            } catch (McdbException mcdbe) {
114
            	throw new HandlerException("Error getting permissions for docid: " 
115
            			+ docid + " for user: " + user + " : " + mcdbe.getMessage());
116
            } catch (SQLException sqle) {
117
            	throw new HandlerException("SQL error getting permissions for docid: " 
118
            			+ docid + " for user: " + user + " : " + sqle.getMessage());
119
            } 
112
//            //check the permission for read
113
//            try {
114
//            	if (!DocumentImpl.hasReadPermission(user, groups, docid)) {
115
//            		String errorString = "User " + user + " does not have permission"
116
//    					+ " to read the document with the docid " + docid;
117
//            		ResponseUtil.sendErrorXML(response, ResponseUtil.NO_READ_PERMISSION, errorString);
118
//            		return;
119
//            	}
120
//            } catch (McdbException mcdbe) {
121
//            	throw new HandlerException("ArchiveHandler.readArchiveEntry - Error getting " 
122
//            			+ "permissions for docid: " + docid + " for user: " + user 
123
//            			+ " : " + mcdbe.getMessage());
124
//            } catch (SQLException sqle) {
125
//            	throw new HandlerException("ArchiveHandler.readArchiveEntry - SQL error getting " 
126
//            			+ "permissions for docid: " + docid + " for user: " + user 
127
//            			+ " : " + sqle.getMessage());
128
//            } 
120 129
            
121 130
            // Get the path to the archive file
122 131
            String archiveFileBasePath = PropertyService.getProperty("application.datafilepath");
......
148 157
            ResponseUtil.writeFileToOutput(response, expandedArchivePath, archiveEntryName);            
149 158
                        
150 159
        } catch (UtilException ue) {
151
        	String errorString = "Utility error reading archive entry for docid: " 
160
        	String errorString = "ArchiveHandler.readArchiveEntry - Utility error reading archive entry for docid: " 
152 161
    			+ docid + " : " + ue.getMessage();
153 162
        	ResponseUtil.sendErrorXML(response, ResponseUtil.GENERAL_UTILITY_ERROR, errorString);
154 163
        	throw new ErrorHandledException(null);
155 164
        } catch (PropertyNotFoundException pnfe) {
156
        	String errorString = "Property error reading archive entry for docid: " 
165
        	String errorString = "ArchiveHandler.readArchiveEntry -  Property error reading archive entry for docid: " 
157 166
        		+ docid + " : " + pnfe.getMessage();
158 167
        	ResponseUtil.sendErrorXML(response, ResponseUtil.PROPERTY_NOT_FOUND, errorString);
159 168
        	throw new ErrorHandledException(null);
160 169
        } catch (MetacatUtilException mue) {
161
        	String errorString = "Metacat utility error reading archive entry for docid: " 
170
        	String errorString = "ArchiveHandler.readArchiveEntry -  Metacat utility error reading archive entry for docid: " 
162 171
        		+ docid + " : " + mue.getMessage();
163 172
        	ResponseUtil.sendErrorXML(response, ResponseUtil.METACAT_UTILITY_ERROR, errorString);
164 173
        	throw new ErrorHandledException(null);
165
        } 
174
        } catch (ParseLSIDException ple) {
175
        	String errorString = "ArchiveHandler.readArchiveEntry -  LSID parsing error reading archive entry for docid: " 
176
        		+ docid + " : " + ple.getMessage();
177
        	ResponseUtil.sendErrorXML(response, ResponseUtil.METACAT_UTILITY_ERROR, errorString);
178
        	throw new ErrorHandledException(null);
179
        }
166 180
	}
167 181

  
168 182
}
src/edu/ucsb/nceas/metacat/MetaCatServlet.java
246 246
			ServiceService.registerService("XMLSchemaService", XMLSchemaService.getInstance());
247 247
			ServiceService.registerService("SchedulerService", SchedulerService.getInstance());
248 248

  
249
			// check if eml201 document were corrected or not. if not, correct
250
			// eml201 documents.
251
			// Before Metacat 1.8.1, metacat uses tag RELEASE_EML_2_0_1_UPDATE_6
252
			// as eml
253
			// schema, which accidentily points to wrong version of
254
			// eml-resource.xsd.
249
			// check if eml201 document were corrected or not. if not, correct eml201 documents.
250
			// Before Metacat 1.8.1, metacat uses tag RELEASE_EML_2_0_1_UPDATE_6 as eml
251
			// schema, which accidentily points to wrong version of eml-resource.xsd.
255 252
			String correctedEML201Doc = PropertyService
256 253
					.getProperty("document.eml201DocumentCorrected");
257 254
			if (correctedEML201Doc != null && correctedEML201Doc.equals(FALSE)) {
......
877 874
					return;
878 875
				} else if (action.equals("scheduleWorkflow")) {
879 876
					try {
880
						String resultString = 
881
							WorkflowScheduler.getInstance().scheduleJob(params, request, response, 
882
								userName, groupNames);
883
						ResponseUtil.sendSuccessXML(response, resultString);
877
						WorkflowScheduler.getInstance().scheduleJob(request, response, params, 
878
							userName, groupNames);
884 879
						return;
885 880
					} catch (BaseException be) {
886 881
						ResponseUtil.sendErrorXML(response, ResponseUtil.SCHEDULE_WORKFLOW_ERROR, be);
887 882
						return;						
888 883
					}
884
				} else if (action.equals("unscheduleWorkflow")) {
885
					try {
886
						WorkflowScheduler.getInstance().unScheduleJob(request, response, params, 
887
							userName, groupNames);
888
						return;
889
					} catch (BaseException be) {
890
						ResponseUtil.sendErrorXML(response, ResponseUtil.UNSCHEDULE_WORKFLOW_ERROR, be);
891
						return;						
892
					}
893
				} else if (action.equals("rescheduleWorkflow")) {
894
					try {
895
						WorkflowScheduler.getInstance().reScheduleJob(request, response, params, 
896
							userName, groupNames);
897
						return;
898
					} catch (BaseException be) {
899
						ResponseUtil.sendErrorXML(response, ResponseUtil.RESCHEDULE_WORKFLOW_ERROR, be);
900
						return;						
901
					}
889 902
				} else if (action.equals("getScheduledWorkflow")) {
890 903
					try {
891
						String resultString = 
892
							WorkflowScheduler.getInstance().getJobs(params, request, response, 
893
								userName, groupNames);
894
						ResponseUtil.sendSuccessXML(response, resultString);
904
						WorkflowScheduler.getInstance().getJobs(request, response, params, 
905
								userName, groupNames);				
895 906
						return;
896 907
					} catch (BaseException be) {
897
						ResponseUtil.sendErrorXML(response, ResponseUtil.SCHEDULE_WORKFLOW_ERROR, be);
908
						ResponseUtil.sendErrorXML(response, ResponseUtil.GET_SCHEDULED_WORKFLOW_ERROR, be);
898 909
						return;						
899 910
					}
900 911
				} else {
src/edu/ucsb/nceas/metacat/workflow/WorkflowJob.java
25 25
 */
26 26
package edu.ucsb.nceas.metacat.workflow;
27 27

  
28
import java.util.Calendar;
28
import java.rmi.RemoteException;
29
import javax.xml.rpc.ServiceException;
29 30

  
30 31
import org.apache.log4j.Logger;
31 32

  
32 33
import org.quartz.InterruptableJob;
34
import org.quartz.JobDetail;
35
import org.quartz.JobDataMap;
33 36
import org.quartz.JobExecutionContext;
34 37
import org.quartz.JobExecutionException;
35 38

  
36
import edu.ucsb.nceas.utilities.FileUtil;
37
import edu.ucsb.nceas.utilities.UtilException;
39
import org.kepler.executionWS.KeplerWebServiceLocator;
40
import org.kepler.executionWS.KeplerWebServicePortType;
38 41

  
39 42
public class WorkflowJob implements InterruptableJob {
40 43
	
41 44
	private static Logger logMetacat = Logger.getLogger(WorkflowJob.class);
42 45
	
43
	public void execute(JobExecutionContext context) throws JobExecutionException {
46
	public void execute(JobExecutionContext executionContext) throws JobExecutionException {
44 47
		try {
45
			FileUtil.createFile("/tmp/worflowJob.txt");
46
			FileUtil.writeFile("/tmp/worflowJob.txt", Calendar.getInstance().getTime().toString());			
47
		} catch (UtilException ue) {
48
			String errorstr = "Util Exception writing to file" + ue.getMessage();
49
			logMetacat.error(errorstr);
50
			throw new JobExecutionException(errorstr);
48
			JobDetail jobDetail = executionContext.getJobDetail();
49
			if (jobDetail == null) {
50
				throw new JobExecutionException("WorkflowJob.execute - Could not get job detail from execution context"); 
51
			}
52
			
53
			JobDataMap jobDataMap = jobDetail.getJobDataMap();
54
			if (jobDataMap == null) {
55
				throw new JobExecutionException("WorkflowJob.execute - Could not get job data map from job detail"); 
56
			}
57
			
58
			String karLSID = jobDataMap.getString("karid");
59
			if (karLSID == null) {
60
				throw new JobExecutionException("WorkflowJob.execute - Could not get kar LSID from job data map");
61
			}
62
			
63
			logMetacat.debug("WorkflowJob.execute - Getting serviceLocator");
64
			KeplerWebServiceLocator serviceLocator = new KeplerWebServiceLocator();
65
			
66
			logMetacat.debug("WorkflowJob.execute - Getting service");
67
			KeplerWebServicePortType serviceEndpoint = serviceLocator.getKeplerWebServiceHttpSoap11Endpoint();
68
			
69
			logMetacat.debug("WorkflowJob.execute - Executing with kar lsid:" + karLSID);
70
			String status = serviceEndpoint.execute(karLSID);
71
			//String status = serviceEndpoint.getStatus(karLSID);		
72
			logMetacat.debug("WorkflowJob.execute - Status: " + status);
73
			
74
		} catch (RemoteException re) {
75
			String errorStr = "WorkflowJob.execute - Remote problem when trying to execute task: " + re.getMessage();
76
			logMetacat.error(errorStr);
77
			throw new JobExecutionException(errorStr); 
78
		} catch (ServiceException se) {
79
			String errorStr = "WorkflowJob.execute - Service problem when trying to execute task: " + se.getMessage();
80
			logMetacat.error(errorStr);
81
			throw new JobExecutionException(errorStr); 
82
		} catch (Exception e) {
83
			String errorStr = "WorkflowJob.execute - General problem when trying to execute task: " + e.getMessage();
84
			logMetacat.error(errorStr);
85
			throw new JobExecutionException(errorStr); 
51 86
		}
52
	
53 87
	}
54 88
	
55 89
	public void interrupt() {
src/edu/ucsb/nceas/metacat/workflow/WorkflowScheduler.java
26 26

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

  
29
import java.text.DateFormat;
29
import java.io.IOException;
30
import java.text.SimpleDateFormat;
30 31
import java.text.ParseException;
31 32
import java.util.Calendar;
32 33
import java.util.Date;
......
36 37

  
37 38
import javax.servlet.http.HttpServletRequest;
38 39
import javax.servlet.http.HttpServletResponse;
40
import javax.servlet.ServletException;
39 41

  
40 42
import org.apache.log4j.Logger;
41 43

  
44
import edu.ucsb.nceas.metacat.MetaCatServlet;
42 45
import edu.ucsb.nceas.metacat.scheduler.BaseScheduler;
46
import edu.ucsb.nceas.metacat.scheduler.ScheduledJobAccess;
47
import edu.ucsb.nceas.metacat.scheduler.ScheduledJobDAO;
48
import edu.ucsb.nceas.metacat.scheduler.ScheduledJobParamDAO;
43 49
import edu.ucsb.nceas.metacat.scheduler.SchedulerService;
44 50
import edu.ucsb.nceas.metacat.scheduler.MetacatSchedulerException;
45 51
import edu.ucsb.nceas.metacat.service.ServiceException;
52
import edu.ucsb.nceas.metacat.util.ErrorSendingErrorException;
53
import edu.ucsb.nceas.metacat.util.ResponseUtil;
54
import edu.ucsb.nceas.metacat.util.RequestUtil;
55
import edu.ucsb.nceas.shared.AccessException;
46 56

  
47 57
public class WorkflowScheduler extends BaseScheduler {
48 58
	
......
50 60
	
51 61
	private static Logger logMetacat = Logger.getLogger(WorkflowScheduler.class);
52 62
	
53
	private static String SCHEDULED_JOB_GROUP = "workflow";
54
	private static String SCHEDULED_JOB_CLASS = "edu.ucsb.nceas.metacat.workflow.WorkflowJob";
63
	private static String WORKFLOW_JOB_GROUP = "workflow";
64
	private static String WORKFLOW_JOB_CLASS = "edu.ucsb.nceas.metacat.workflow.WorkflowJob";
55 65

  
56 66
	/**
57 67
	 * private constructor since this is a singleton
......
70 80
		return workflowScheduler;
71 81
	}
72 82
	
73
	public String scheduleJob(Hashtable<String, String[]> params,
74
			HttpServletRequest request, HttpServletResponse response, String username,
83
	public void scheduleJob(HttpServletRequest request, HttpServletResponse response, 
84
			Hashtable<String, String[]> params, String username,
75 85
			String[] groups) throws MetacatSchedulerException {
76
		
86
		 		
77 87
		String delays[] = params.get("delay");
78 88
		String startTimes[] = params.get("starttime");
79 89
		HashMap<String, String> jobParams = new HashMap<String, String>();
......
85 95
			if (delays != null && delays.length > 0) {
86 96
				startCal = schedulerService.getStartDateFromDelay(delays[0]);
87 97
			} else if (startTimes != null && startTimes.length > 0) {
88
				Date startDate = DateFormat.getInstance().parse(startTimes[0]);
98
				SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
99
				Date startDate = dateFormat.parse(startTimes[0]);
89 100
				startCal = Calendar.getInstance();
90 101
				startCal.setTime(startDate);
91 102
			} else {
......
93 104
				startCal = Calendar.getInstance();
94 105
			}
95 106

  
96
			String intervals[] = params.get("interval");
97
			if (intervals == null || intervals.length == 0) {
98
				throw new MetacatSchedulerException(
99
						"SchedulerService.scheduleHandler - Interval field must be populated "
107
			String intervalValues[] = params.get("intervalvalue");
108
			if (intervalValues == null || intervalValues.length == 0) {
109
				throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - intervalvalue field must be populated "
100 110
								+ "in scheduler parameters when scheduling job.");
101 111
			}
102
			String interval = intervals[0];
112
			String intervalStrValue = intervalValues[0];
113
			int intervalValue = Integer.parseInt(intervalStrValue);
114
			
115
			String intervalUnits[] = params.get("intervalunit");
116
			if (intervalUnits == null || intervalUnits.length == 0) {
117
				throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - intervalunit field must be populated "
118
								+ "in scheduler parameters when scheduling job.");
119
			}
120
			String intervalUnit = intervalUnits[0];
103 121

  
104 122
			Enumeration<String> paramNames = params.keys();
105 123
			while (paramNames.hasMoreElements()) {
......
109 127
				}
110 128
			}
111 129

  
112
			String jobName = SCHEDULED_JOB_GROUP
130
			String jobName = WORKFLOW_JOB_GROUP
113 131
					+ Calendar.getInstance().getTimeInMillis();
114 132

  
115
			return schedulerService.scheduleJob(jobName, startCal, interval,
116
					SCHEDULED_JOB_CLASS, SCHEDULED_JOB_GROUP, jobParams);
133
			String xmlResult = schedulerService.scheduleJob(jobName, startCal, intervalValue, intervalUnit,
134
					WORKFLOW_JOB_CLASS, WORKFLOW_JOB_GROUP, jobParams, username, groups);
135

  
136
			String forwardtos[] = params.get("forwardto");
137
			String forwardto = null;
138
			if (forwardtos != null && forwardtos.length > 0) {
139
				forwardto = forwardtos[0];
140
			}
141
			
142
			if (forwardto != null) {
143
				String qformats[] = params.get("qformat");
144
				String qformat = null;
145
				if (qformats != null && qformats.length > 0) {
146
					qformat = qformats[0];
147
				}
148
				
149
				String destination = "/style/skins/" + qformat + "/" + forwardto
150
					+ "?workflowid=" + jobParams.get("workflowid");			
151
				RequestUtil.forwardRequest(request, response, destination.toString());
152
			} else {
153
				ResponseUtil.sendSuccessXML(response, xmlResult);
154
			}
155
			
117 156
		} catch (ParseException pe) {
118
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleHandler - Could not " + "schedule job  : " 
157
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - Could not " + "schedule job  : " 
119 158
					+ pe.getMessage());
120 159
		} catch (ServiceException se) {
121
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleHandler - Service issue scheduling job", se);
160
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - Service issue scheduling job", se);
161
		} catch (IOException ioe) {
162
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - I/O issue scheduling job: " + ioe.getMessage());
163
		} catch (ServletException se) {
164
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - Servlet issue scheduling job: " + se.getMessage());
165
		} catch (ErrorSendingErrorException esee) {
166
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - Issue sending erro when scheduling job: " + esee.getMessage());			
122 167
		}
123 168
	}
124 169
	
125
	public String unScheduleJob(Hashtable<String, String[]> params,
126
            HttpServletRequest request, HttpServletResponse response,
127
            String username, String[] groups) throws MetacatSchedulerException {
128
		return "";
170
	public void unScheduleJob(HttpServletRequest request, HttpServletResponse response,
171
			Hashtable<String, String[]> params, String username, String[] groups)
172
			throws MetacatSchedulerException {
173
		try {
174
			String jobNames[] = params.get("workflowjobid");
175
			if (jobNames == null || jobNames.length == 0) {
176
				throw new MetacatSchedulerException("SchedulerService.unScheduleJob - workflowjobid " 
177
						+ "field must be populated in scheduler parameters when unscheduling job.");
178
			}
179
			String jobName = jobNames[0];
180

  
181
			SchedulerService schedulerService = SchedulerService.getInstance();
182
			String xmlResult = schedulerService.unScheduleJob(jobName, username, groups);
183
			
184
			String forwardtos[] = params.get("forwardto");
185
			String forwardto = null;
186
			if (forwardtos != null && forwardtos.length > 0) {
187
				forwardto = forwardtos[0];
188
			}
189
			
190
			if (forwardto != null) {
191
				String qformats[] = params.get("qformat");
192
				String qformat = null;
193
				if (qformats != null && qformats.length > 0) {
194
					qformat = qformats[0];
195
				}
196
				
197
				ScheduledJobAccess jobAccess = new ScheduledJobAccess();
198
				ScheduledJobDAO jobDAO = jobAccess.getJobByName(jobName);
199
				
200
				String workflowId = null;
201
				ScheduledJobParamDAO jobParamDAO = jobDAO.getJobParam("workflowid");
202
				if (jobParamDAO != null) {
203
					workflowId = jobParamDAO.getValue();
204
				}				 
205
				
206
				String destination = "/style/skins/" + qformat + "/" + forwardto
207
					+ "?workflowid=" + workflowId;			
208
				RequestUtil.forwardRequest(request, response, destination.toString());
209
			} else {
210
				ResponseUtil.sendSuccessXML(response, xmlResult);
211
			}
212
			ResponseUtil.sendSuccessXML(response, xmlResult);
213
		} catch (ServiceException se) {
214
			throw new MetacatSchedulerException(
215
					"WorkflowScheduler.unScheduleJob - Service issue unscheduling job",
216
					se);
217
		} catch (Exception e) {
218
			throw new MetacatSchedulerException(
219
					"WorkflowScheduler.unScheduleJob - Generic issue unscheduling job: "
220
							+ e.getMessage());
221
		}
129 222
	}
130 223
	
131
	public String deleteJob(Hashtable<String, String[]> params,
132
            HttpServletRequest request, HttpServletResponse response,
133
            String username, String[] groups) throws MetacatSchedulerException {
134
		return "";
224
	public void reScheduleJob(HttpServletRequest request, HttpServletResponse response, 
225
			Hashtable<String, String[]> params, String username,
226
			String[] groups) throws MetacatSchedulerException {
227
		 		
228
		try {
229
			String jobNames[] = params.get("workflowjobid");
230
	
231
			if (jobNames == null || jobNames.length == 0) {
232
				throw new MetacatSchedulerException("WorkflowScheduler.reScheduleJob - workflowjobid field must be populated "
233
						+ "in scheduler parameters when rescheduling job.");
234
			}
235
			
236
			String jobName = jobNames[0];
237
	
238
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
239
			ScheduledJobDAO jobDAO = jobAccess.getJobByName(jobName);
240
			
241
			SchedulerService schedulerService = SchedulerService.getInstance();
242
			String result = schedulerService.rescheduleJob(jobDAO, username, groups);
243

  
244
			String forwardtos[] = params.get("forwardto");
245
			String forwardto = null;
246
			if (forwardtos != null && forwardtos.length > 0) {
247
				forwardto = forwardtos[0];
248
			}
249
			
250
			if (forwardto != null) {
251
				String qformats[] = params.get("qformat");
252
				String qformat = null;
253
				if (qformats != null && qformats.length > 0) {
254
					qformat = qformats[0];
255
				}
256
				
257
				String workflowId = null;
258
				ScheduledJobParamDAO jobParamDAO = jobDAO.getAllJobParams().get("workflowid");
259
				if (jobParamDAO != null) {
260
					workflowId = jobParamDAO.getValue();
261
				}
262
				
263
				String destination = "/style/skins/" + qformat + "/" + forwardto
264
					+ "?workflowid=" + workflowId;			
265
				RequestUtil.forwardRequest(request, response, destination.toString());
266
			} else {
267
				ResponseUtil.sendSuccessXML(response, result);
268
			}
269
			
270
		} catch (AccessException ae) {
271
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - DB access issue when scheduling job  : ", ae);
272
		} catch (ServiceException se) {
273
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - Service issue scheduling job", se);
274
		} catch (IOException ioe) {
275
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - I/O issue scheduling job: " + ioe.getMessage());
276
		} catch (ServletException se) {
277
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - Servlet issue scheduling job: " + se.getMessage());
278
		} catch (ErrorSendingErrorException esee) {
279
			throw new MetacatSchedulerException("WorkflowScheduler.scheduleJob - Issue sending erro when scheduling job: " + esee.getMessage());			
280
		}
135 281
	}
136 282
	
137
	public String getJobs(Hashtable<String, String[]> params,
138
            HttpServletRequest request, HttpServletResponse response,
139
            String username, String[] groups) throws MetacatSchedulerException {
283
	public void deleteJob(HttpServletRequest request, HttpServletResponse response, 
284
			Hashtable<String, String[]> params, String username, String[] groups) throws MetacatSchedulerException {
140 285
		
141
		String groupName = null;
142
		String groupNames[] = params.get("groupName");
143
		if (groupNames != null && groupNames.length != 0) {
144
			groupName = groupNames[0];
286
	}
287
	
288
	public void getJobs(HttpServletRequest request, HttpServletResponse response, 
289
			Hashtable<String, String[]> params, String username, String[] groups) throws MetacatSchedulerException {
290
		
291
		String workFlowId = null;
292
		String qformat = "";
293
		
294
		String workFlowIds[] = params.get("workflowid");
295
		if (workFlowIds != null && workFlowIds.length != 0) {
296
			workFlowId = workFlowIds[0];
145 297
		}
146 298
		
299
        if (params.containsKey("qformat")) {
300
            qformat = params.get("qformat")[0];
301
        }
302
		
147 303
		try {
148
			return SchedulerService.getInstance().getJobsInfoXML(groupName);
304
			String xmlResult = SchedulerService.getInstance().getJobsInfoXML(WORKFLOW_JOB_GROUP, "workflowid", workFlowId);
305
			logMetacat.debug("WorkflowScheduler.getJobs - xmlResult: " + xmlResult);
306
			
307
			if (qformat == null || qformat.equals(MetaCatServlet.XMLFORMAT)) {
308
				ResponseUtil.send(response, xmlResult);
309
			} else {				
310
				ResponseUtil.transformAndSendXML(response, xmlResult, "-//NCEAS//scheduledWorkflowResultset//EN", 
311
					"-//W3C//HTML//EN", qformat, params);
312
			}
149 313
		} catch (ServiceException se) {
150 314
			throw new MetacatSchedulerException("WorkflowScheduler.getJobs - Service issue getting jobs", se);
315
		} catch (Exception e) {
316
			throw new MetacatSchedulerException("WorkflowScheduler.getJobs - Generic issue getting jobs: " 
317
					+ e.getMessage());
151 318
		}		
152 319
	}	
153 320
}
src/edu/ucsb/nceas/metacat/util/ResponseUtil.java
32 32
import java.io.InputStream;
33 33
import java.io.OutputStream;
34 34
import java.io.PrintWriter;
35
import java.sql.SQLException;
35 36
import java.util.Hashtable;
36 37

  
37 38
import javax.servlet.http.HttpServletRequest;
......
39 40

  
40 41
import org.apache.log4j.Logger;
41 42

  
43
import edu.ucsb.nceas.metacat.DBTransform;
42 44
import edu.ucsb.nceas.shared.BaseException;
43 45
import edu.ucsb.nceas.utilities.FileUtil;
46
import edu.ucsb.nceas.utilities.PropertyNotFoundException;
44 47

  
45 48
public class ResponseUtil {
46 49
	
......
53 56
	public static Long NO_READ_PERMISSION = new Long(105001);
54 57
	// 130XXX - scheduler errors
55 58
	public static Long SCHEDULE_WORKFLOW_ERROR = new Long(130001);
59
	public static Long UNSCHEDULE_WORKFLOW_ERROR = new Long(130002);
60
	public static Long RESCHEDULE_WORKFLOW_ERROR = new Long(130003);
61
	public static Long GET_SCHEDULED_WORKFLOW_ERROR = new Long(130004);
56 62
	
63
	
57 64
	// errorCodes is a lookup table for generic messages for each code.  It
58 65
	// is better to use the sendError() versions that accept an explicit 
59 66
	// error message;
......
64 71
		errorCodes.put(PROPERTY_NOT_FOUND, "Property not found");
65 72
		errorCodes.put(NO_READ_PERMISSION, "Read permission denied for user");
66 73
		errorCodes.put(SCHEDULE_WORKFLOW_ERROR, "Schedule workflow error");
74
		errorCodes.put(UNSCHEDULE_WORKFLOW_ERROR, "Unschedule workflow error");
75
		errorCodes.put(RESCHEDULE_WORKFLOW_ERROR, "Reschedule workflow error");
76
		errorCodes.put(GET_SCHEDULED_WORKFLOW_ERROR, "Get scheduled workflow error");
67 77
	}
68 78
	
69 79
	private static Logger logMetacat = Logger.getLogger(ResponseUtil.class);
......
129 139
		}
130 140
	}
131 141
	
142
	public static void send(HttpServletResponse response, String content) throws ErrorSendingErrorException {
143

  
144
		PrintWriter out = null;
145
		try {
146
			out = response.getWriter();
147
			response.setContentType("text/xml");
148

  
149
			out.print(content);
150

  
151
		} catch (IOException ioe) {
152
			throw new ErrorSendingErrorException("I/O error when sending content: "
153
					+ content + " : " + ioe.getMessage());
154
		} finally {
155
			if (out != null) {
156
				out.close();
157
			}
158
		}
159
	}
160
	
132 161
	public static void sendErrorXML(HttpServletResponse response, Long errorCode,
133 162
			BaseException be) throws ErrorSendingErrorException {
134 163

  
......
204 233
			}
205 234
		}
206 235
	}
236
	
237
	public static boolean isSuccessXML(String message) {
238

  
239
		return message.indexOf("<success>") != -1;
240
	}
241
	
242
	public static void transformAndSendXML(HttpServletResponse response, String xmlDoc,
243
			String sourceType, String targetType, String qformat, 
244
			Hashtable<String, String[]> params) throws ErrorSendingErrorException {
245

  
246
		PrintWriter out = null;
247
		try {
248
			out = response.getWriter();
249
			DBTransform dbTransform = new DBTransform();
250

  
251
			dbTransform.transformXMLDocument(xmlDoc, sourceType, targetType, qformat, out, params);
252
		} catch (PropertyNotFoundException pnfe) {
253
			throw new ErrorSendingErrorException("Property error when transforming XML: "
254
					+ xmlDoc + " : " + pnfe.getMessage());
255
		} catch (ClassNotFoundException cnfe) {
256
			throw new ErrorSendingErrorException("Class error when transforming XML: "
257
					+ xmlDoc + " : " + cnfe.getMessage());
258
		} catch (SQLException sqle) {
259
			throw new ErrorSendingErrorException("SQL error when transforming XML: "
260
					+ xmlDoc + " : " + sqle.getMessage());
261
		} catch (IOException ioe) {
262
			throw new ErrorSendingErrorException("I/O error when transforming XML: "
263
					+ xmlDoc + " : " + ioe.getMessage());
264
		} finally {
265
			if (out != null) {
266
				out.close();
267
			}
268
		}
269
	}
207 270
}
src/edu/ucsb/nceas/metacat/DBEntityResolver.java
44 44
import java.io.InputStream;
45 45
import java.io.IOException;
46 46
import java.net.URL;
47
import java.net.URLConnection;
48 47
import java.net.MalformedURLException;
49 48

  
50 49
/**
......
179 178
        istream.close();
180 179
      } catch (IOException e) {
181 180
        throw new SAXException
182
        ("DBEntityResolver.resolveEntity(): " + e.getMessage());
181
        ("DBEntityResolver.resolveEntity - I/O issue when resolving entity: " + e.getMessage());
183 182
      }
184 183
      istream = checkURLConnection(dbSystemID);
185 184
      is.setByteStream(istream);
......
226 225
      stmt.close();
227 226
    } catch (SQLException e) {
228 227
      throw new SAXException
229
      ("DBEntityResolver.getDTDSystemID(): " + e.getMessage());
228
      ("DBEntityResolver.getDTDSystemID - SQL error when getting DTD system ID: " + e.getMessage());
230 229
    } catch (PropertyNotFoundException pnfe) {
231 230
        throw new SAXException
232
        ("DBEntityResolver.getDTDSystemID(): " + pnfe.getMessage());
231
        ("DBEntityResolver.getDTDSystemID - Property error when getting DTD system ID:  " + pnfe.getMessage());
233 232
      }
234 233
    finally
235 234
    {
......
239 238
      }//try
240 239
      catch (SQLException sqlE)
241 240
      {
242
        logMetacat.error("Error in DBEntityReolver.getDTDSystemId: "
241
        logMetacat.error("SQL error in DBEntityReolver.getDTDSystemId: "
243 242
                                  +sqlE.getMessage());
244 243
      }//catch
245 244
      finally
......
290 289
      pstmt.close();
291 290
    } catch (SQLException e) {
292 291
      throw new SAXException
293
      ("DBEntityResolver.registerDTD(): " + e.getMessage());
292
      ("DBEntityResolver.registerDTD - SQL issue when registering DTD: " + e.getMessage());
294 293
    }
295 294
    finally
296 295
    {
......
300 299
      }//try
301 300
      catch (SQLException sqlE)
302 301
      {
303
        logMetacat.error("Error in DBEntityReolver.registerDTD: "
302
        logMetacat.error("SQL error in DBEntityReolver.registerDTD: "
304 303
                                    +sqlE.getMessage());
305 304
      }//catch
306 305
      //DBConnectionPool.returnDBConnection(conn, serialNumber);
......
373 372
				fw.close();
374 373
			} // end of synchronized
375 374
		} catch (MalformedURLException e) {
376
			throw new SAXException("DBEntityResolver.uploadDTD(): " + e.getMessage());
375
			throw new SAXException("DBEntityResolver.uploadDTD() - Malformed URL when uploading DTD: " + e.getMessage());
377 376
		} catch (IOException e) {
378
			throw new SAXException("DBEntityResolver.uploadDTD(): " + e.getMessage());
377
			throw new SAXException("DBEntityResolver.uploadDTD - I/O issue when uploading DTD: " + e.getMessage());
379 378
		} catch (SecurityException e) {
380
			throw new SAXException("DBEntityResolver.uploadDTD(): " + e.getMessage());
379
			throw new SAXException("DBEntityResolver.uploadDTD() - Security issue when uploading DTD: " + e.getMessage());
381 380
		}
382 381

  
383 382
		// String dtdURL = "http://dev.nceas.ucsb.edu/bojilova/dtd/";
......
396 395
			dtdPath = SystemUtil.getContextDir() + "/dtd/";
397 396
			dtdURL = SystemUtil.getContextURL() + "/dtd/";
398 397
		} catch (PropertyNotFoundException pnfe) {
399
			throw new SAXException("DBEntityResolver.uploadDTDFromURL: "
398
			throw new SAXException("DBEntityResolver.uploadDTDFromURL - Property issue when uploading DTD from URL: "
400 399
					+ pnfe.getMessage());
401 400
		}
402 401

  
......
452 451
				fw.close();
453 452
			} // end of synchronized
454 453
		} catch (MalformedURLException e) {
455
			throw new SAXException("DBEntityResolver.uploadDTDFromURL(): "
454
			throw new SAXException("DBEntityResolver.uploadDTDFromURL - Malformed URL when uploading DTD from URL: "
456 455
					+ e.getMessage());
457 456
		} catch (IOException e) {
458
			throw new SAXException("DBEntityResolver.uploadDTDFromURL(): "
457
			throw new SAXException("DBEntityResolver.uploadDTDFromURL - I/O issue when uploading DTD from URL:  "
459 458
					+ e.getMessage());
460 459
		} catch (SecurityException e) {
461
			throw new SAXException("DBEntityResolver.uploadDTDFromURL(): "
460
			throw new SAXException("DBEntityResolver.uploadDTDFromURL - Security issue when uploading DTD from URL:  "
462 461
					+ e.getMessage());
463 462
		}
464 463

  
......
478 477
			return (new URL(systemId).openStream());
479 478

  
480 479
		} catch (MalformedURLException e) {
481
			throw new SAXException("DBEntityResolver.checkURLConnection(): "
480
			throw new SAXException("DBEntityResolver.checkURLConnection - Malformed URL when checking URL Connection: "
482 481
					+ e.getMessage());
483 482
		} catch (IOException e) {
484
			throw new SAXException("DBEntityResolver.checkURLConnection(): "
483
			throw new SAXException("DBEntityResolver.checkURLConnection - I/O issue when checking URL Connection: "
485 484
					+ e.getMessage());
486 485
		}
487 486
	}
src/edu/ucsb/nceas/metacat/scheduler/SchedulerService.java
26 26

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

  
29
import java.util.Arrays;
30 29
import java.util.Calendar;
31 30
import java.util.HashMap;
32 31
import java.util.Vector;
......
87 86
			SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
88 87
			
89 88
			sched = schedFact.getScheduler();
90
			// read jobs from db here.
91
			// then add jobs to sched.
92 89
			sched.start();
90
			
91
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
92
			HashMap<Long, ScheduledJobDAO> allJobsMap = jobAccess.getAllJobs(null);
93
			
94
			for (Long jobId : allJobsMap.keySet()) {
95
				ScheduledJobDAO jobDAO = allJobsMap.get(jobId);
96
				String[] groups = {"scheduler_group"};
97
				if (jobDAO.getStatus().equals(StatusUtil.SCHEDULED)) {
98
					rescheduleJob(jobDAO, "scheduler_user", groups, false);
99
				}
100
			}			
101
			
102
		} catch (AccessException ae) {
103
			throw new ServiceException("DB Access issue when starting scheduler: ", ae);
93 104
		} catch (SchedulerException se) {
94
			throw new ServiceException("Could not start scheduler: " + se.getMessage());
105
			throw new ServiceException("Scheduler engine issue when starting scheduler: " + se.getMessage());
95 106
		}		
96 107
	}
97 108
	
......
108 119
		return new Vector<String>();
109 120
	}
110 121
	
111
	public String scheduleJob(String jobName, Calendar startCal, String interval,
112
			String jobClassName, String jobGroup, HashMap<String, String> jobParams) throws ServiceException {
122
	public String scheduleJob(ScheduledJobDAO jobDAO, String username, String[] groups) throws ServiceException {
113 123
        
124
		Calendar startTimeCal = Calendar.getInstance();
125
        startTimeCal.setTime(jobDAO.getStartTime());
126
        
127
        HashMap<String, String> jobParams = new HashMap<String, String>();
128
        HashMap<String, ScheduledJobParamDAO> jobParamDAOs = jobDAO.getAllJobParams();
129
        for (String paramName : jobParamDAOs.keySet()) {
130
        	jobParams.put(paramName, jobParamDAOs.get(paramName).getValue());   	
131
        }
132
        
133
		return scheduleJob(jobDAO.getName(), startTimeCal, jobDAO.getIntervalValue(), jobDAO.getIntervalUnit(),
134
				jobDAO.getClassName(), jobDAO.getGroupName(), jobParams, username, groups);
135
	}
136
	
137
	public String scheduleJob(String jobName, Calendar startCal, int intervalValue, String intervalUnit,
138
			String jobClassName, String jobGroup, HashMap<String, String> jobParams, 
139
			String username, String[] groups) throws ServiceException {
140
        
114 141
        Class<Job> jobClass = null;
115 142
        try {        	
116 143
        	jobClass = (Class<Job>)Class.forName(jobClassName);     	
......
120 147
        } 
121 148
        
122 149
        logMetacat.info("Scheduling job -- name: " + jobName + ", class: " + jobClassName 
123
        		+ ", start time: " + startCal.toString() + ", interval: " + interval);  
124
        
125
		char intervalUnit = interval.trim().charAt(interval.length() - 1);
126
		String intervalStrValue = interval.trim().substring(0, interval.length() - 1);
127
		int intervalValue;
128
		try {
129
			intervalValue = Integer.parseInt(intervalStrValue);
130
		} catch (NumberFormatException nfe) {
131
			throw new ServiceException("SchedulerService.scheduleJob - Could not parse interval value " 
132
					+ "into an integer: " + intervalStrValue + " : " + nfe.getMessage());
133
		}
150
        		+ ", start time: " + startCal.toString() + ", interval value: " + intervalValue 
151
        		+ ", interval unit: " + intervalUnit);  
134 152
		
135 153
		startJob(jobName, startCal, intervalValue, intervalUnit, jobClass, jobGroup, jobParams);
136 154
		
137 155
		try {
138 156
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
139
			jobAccess.createJob(jobName, jobName, jobGroup, jobClass, startCal, intervalValue, Character.toString(intervalUnit), jobParams);
157
			jobAccess.createJob(jobName, jobName, jobGroup, jobClass, startCal, intervalValue, intervalUnit, jobParams);
140 158
		} catch (AccessException ae) {
141 159
			try {
142
				deleteJob(jobName);
160
				deleteJob(jobName, username, groups);
143 161
			} catch (Exception e) {
144 162
				// Not much we can do here but log this
145 163
				logMetacat.error("An access exception was thrown when writing job: " + jobName 
......
149 167
			throw new ServiceException("SchedulerService.scheduleJob - Error accessing db: ", ae);
150 168
		}
151 169
		
152
		return jobName;
170
		return "Scheduled: " + jobName;
153 171
	}
154 172
	
155
	public void unscheduleJob(String jobName) throws ServiceException {
173

  
174
	
175
	public String unScheduleJob(String jobName, String username,
176
			String[] groups) throws ServiceException {
156 177
		try {
157 178
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
158 179
			ScheduledJobDAO jobDAO = jobAccess.getJobByName(jobName);
180
			if (jobDAO == null) {
181
				throw new ServiceException("SchedulerService.unscheduleJob - Could " 
182
						+ "not find job with name: " + jobName);
183
			}
159 184

  
160
			sched.unscheduleJob(jobDAO.getName(), jobDAO.getGroupName());
185
			sched.deleteJob(jobDAO.getName(), jobDAO.getGroupName());
161 186

  
162
			jobDAO.setStatus(StatusUtil.UNSHCEDULED);
187
			jobDAO.setStatus(StatusUtil.UNSCHEDULED);
163 188
			jobAccess.updateJobStatus(jobDAO);
164 189
		} catch (SchedulerException se) {
165 190
			throw new ServiceException("SchedulerService.unscheduleJob - Could not create "
......
168 193
			throw new ServiceException("SchedulerService.unscheduleJob - Could not create "
169 194
							+ "scheduled job because of db access issue: ", ae);
170 195
		}
196
		
197
		return "Unscheduled: " + jobName;
171 198
	}
172 199
	
173
	public void deleteJob(String jobName) throws ServiceException {
200
	public String rescheduleJob(ScheduledJobDAO jobDAO, String username, String[] groups) throws ServiceException {
201
		return rescheduleJob(jobDAO, username, groups, true);
202
	}
203
	
204
	public String rescheduleJob(ScheduledJobDAO jobDAO, String username, String[] groups, boolean checkStatus) throws ServiceException {
205
		
206
		try {
207
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
208
        
209
			if (jobDAO == null) {
210
				throw new ServiceException("SchedulerService.reScheduleJob - Cannot reschedule nonexistant job.");
211
			}
212
        
213
			if (checkStatus && !jobDAO.getStatus().equals(StatusUtil.UNSCHEDULED)) {
214
				throw new ServiceException("SchedulerService.reScheduleJob - Cannot reschedule a job with status: " 
215
						+ jobDAO.getStatus() + ". Status must be 'unscheduled'.");
216
			}
217
        
218
			Calendar startCal = Calendar.getInstance();
219
	        startCal.setTime(jobDAO.getStartTime());
220
	        
221
	        HashMap<String, String> jobParams = new HashMap<String, String>();
222
	        HashMap<String, ScheduledJobParamDAO> jobParamDAOs = jobDAO.getAllJobParams();
223
	        for (String paramName : jobParamDAOs.keySet()) {
224
	        	jobParams.put(paramName, jobParamDAOs.get(paramName).getValue());   	
225
	        }
226
	        
227
	        Class<Job> jobClass = null;
228
	        String jobClassName = jobDAO.getClassName();
229
	        try {        	
230
	        	jobClass = (Class<Job>)Class.forName(jobClassName);     	
231
	        } catch (ClassNotFoundException cnfe) {
232
	        	throw new ServiceException("SchedulerService.scheduleJob - Could not find class with name: " 
233
	        			+ jobDAO.getClassName() + " : " + cnfe.getMessage());
234
	        } 
235
	        
236
	        logMetacat.info("SchedulerService.rescheduleJob - name: " + jobDAO.getName() + ", class: " + jobClassName 
237
	        		+ ", start time: " + startCal.toString() + ", interval value: " + jobDAO.getIntervalValue() 
238
	        		+ ", interval unit: " + jobDAO.getIntervalUnit());  
239
			
240
			startJob(jobDAO.getName(), startCal, jobDAO.getIntervalValue(), jobDAO.getIntervalUnit(), jobClass, jobDAO.getGroupName(), jobParams);
241
	        
242
			jobDAO.setStatus(StatusUtil.SCHEDULED);
243
			jobAccess.updateJobStatus(jobDAO);
244
			
245
		} catch (AccessException ae) {
246
			throw new ServiceException("SchedulerService.reScheduleJob - Could not reschedule "
247
					+ "job because of db access issue: ", ae);
248
		}
249
        		
250
		return "Resheduled: " + jobDAO.getName();
251
	}
252
	
253
	public String deleteJob(String jobName, String username,
254
			String[] groups) throws ServiceException {
255

  
174 256
		String groupName = "";
175

  
176 257
		try {
177 258
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
178 259
			ScheduledJobDAO jobDAO = jobAccess.getJobByName(jobName);
179 260
			groupName = jobDAO.getGroupName();
180 261

  
181 262
			sched.deleteJob(jobName, groupName);
263
			
264
			jobDAO.setStatus(StatusUtil.DELETED);
265
			jobAccess.updateJobStatus(jobDAO);
182 266
		} catch (SchedulerException se) {
183 267
			throw new ServiceException("SchedulerService.deleteJob - Could not delete job: " + jobName
184 268
							+ " for group: " + groupName + " : " + se.getMessage());
......
186 270
			throw new ServiceException("SchedulerService.deleteJob - Could not delete "
187 271
					+ "scheduled job because of db access issue: ", ae);
188 272
		}
189
	}
190
	
191
	public Vector<String> getJobInfo(String groupName) throws ServiceException {
192
		Vector<String> returnVector = new Vector<String>();
193 273
		
194
		try {
195
			if (groupName.equalsIgnoreCase("All")) {
196
				String[] groupNames = sched.getJobGroupNames();
197
				for (int i = 0; i < groupNames.length; i++) {
198
					returnVector.addAll(Arrays.asList(sched.getJobNames(groupNames[i])));
199
				}
200
			} else {
201
				returnVector.addAll(Arrays.asList(sched.getJobNames(groupName)));
202
			}
203
		} catch (SchedulerException se) {
204
			throw new ServiceException("SchedulerService.getJobNames - Could not get job names for group: " 
205
					+ groupName + " : " + se.getMessage());
206
		}
207

  
208
		return returnVector;
274
		return "Deleted: " + jobName;
209 275
	}
210 276
	
211 277
	public String getJobInfoXML(Long jobId) throws ServiceException {
......
226 292
		return jobInfoXML;
227 293
	}
228 294
	
229
	public String getJobsInfoXML(String groupName) throws ServiceException {
295
	public String getJobsInfoXML(String groupName, String paramName, String paramValue) throws ServiceException {
230 296
		String jobInfoXML = "";
231 297
		
232 298
		try {
233 299
			ScheduledJobAccess jobAccess = new ScheduledJobAccess();
234
			HashMap<Long, ScheduledJobDAO> JobDAOMap = jobAccess.getAllJobs(groupName);
300
			HashMap<Long, ScheduledJobDAO> JobDAOMap = jobAccess.getJobsWithParameter(groupName, paramName, paramValue);
235 301
			
236
			jobInfoXML += "<scheduledJobs>";
302
			jobInfoXML += "<scheduledWorkflowResultset>";
237 303
			for (Long jobDAOId : JobDAOMap.keySet()) {
238
				jobInfoXML +=  jobToXML(JobDAOMap.get(jobDAOId)); 
304
				ScheduledJobDAO jobDAO = JobDAOMap.get(jobDAOId); 
305
				if (paramValue != null && paramName != null) {
306
					ScheduledJobParamDAO jobParamDAO = jobDAO.getJobParam(paramName);
307
					if(jobParamDAO != null && jobParamDAO.getValue().equals(paramValue)) {
308
						jobInfoXML +=  jobToXML(JobDAOMap.get(jobDAOId)); 
309
					}
310
				}
239 311
			}				
240
			jobInfoXML += "</scheduledJobs>";
312
			jobInfoXML += "</scheduledWorkflowResultset>";
241 313
			
242 314
		} catch (AccessException ae) {
243 315
			throw new ServiceException("SchedulerService.getJobInfoXML - Could not get jobs info for group: " 
......
247 319
		return jobInfoXML;
248 320
	}
249 321
	
250
	private String jobToXML(ScheduledJobDAO scheduledJobDAO) {
322
	public String jobToXML(ScheduledJobDAO scheduledJobDAO) throws ServiceException {
251 323
		String jobXML = "";
252 324

  
253 325
		if (scheduledJobDAO != null) {
......
259 331
			jobXML += "<name>" + scheduledJobDAO.getName() + "</name>";
260 332
			jobXML += "<triggerName>" + scheduledJobDAO.getName() + "</triggerName>";
261 333
			jobXML += "<groupName>" + scheduledJobDAO.getGroupName() + "</groupName>";
262
			jobXML += "<className>" + scheduledJobDAO.getName() + "</className>";
334
			jobXML += "<className>" + scheduledJobDAO.getClassName() + "</className>";
263 335
			jobXML += "<startTime>" + scheduledJobDAO.getStartTime().toString()
264 336
					+ "</startTime>";
265 337
			jobXML += "<intervalValue>" + scheduledJobDAO.getIntervalValue()
......
270 342
			HashMap<String, ScheduledJobParamDAO> jobParams = scheduledJobDAO
271 343
					.getAllJobParams();
272 344
			for (String jobParamKey : jobParams.keySet()) {
273
				jobXML += "<jobParam>";
345
				jobXML += "<jobParam name='" + jobParams.get(jobParamKey).getKey() + "'>";
274 346
				jobXML += "<id>" + jobParams.get(jobParamKey).getId() + "</id>";
275 347
				jobXML += "<createTime>" + jobParams.get(jobParamKey).getCreateTime()
276 348
						+ "</createTime>";
......
290 362
	}
291 363
	
292 364
	
293
	private void startJob(String jobName, Calendar startCal, int intervalValue, char intervalUnit,
365
	private void startJob(String jobName, Calendar startCal, int intervalValue, String intervalUnit,
294 366
			Class<Job> jobClass, String jobGroup, HashMap<String, String> jobParams) throws ServiceException { 
295 367
		
296 368
		JobDetail jobDetail = new JobDetail(jobName, jobGroup, jobClass);
297 369
		jobDetail.setJobDataMap(new JobDataMap(jobParams));
298 370
		
299
		switch (intervalUnit) {
371
		char intervalChar = intervalUnit.charAt(0);
372
		
373
		switch (intervalChar) {
300 374
		case 's':
301 375
		case 'S':
302 376
			scheduleSecondlyJob(jobName, jobClass, startCal, intervalValue, jobGroup, jobDetail);
src/edu/ucsb/nceas/metacat/scheduler/BaseScheduler.java
33 33

  
34 34
public abstract class BaseScheduler {
35 35
	
36
	public abstract String scheduleJob(Hashtable<String, String[]> params,
37
            HttpServletRequest request, HttpServletResponse response,
38
            String username, String[] groups) throws MetacatSchedulerException;
36
	public abstract void scheduleJob(HttpServletRequest request, HttpServletResponse response, 
37
            Hashtable<String, String[]> params, String username, String[] groups) throws MetacatSchedulerException;
39 38
	
40
	public abstract String unScheduleJob(Hashtable<String, String[]> params,
41
            HttpServletRequest request, HttpServletResponse response,
42
            String username, String[] groups) throws MetacatSchedulerException;
39
	public abstract void unScheduleJob(HttpServletRequest request, HttpServletResponse response, 
40
			Hashtable<String, String[]> params, String username, String[] groups) throws MetacatSchedulerException;
43 41
	
44
	public abstract String deleteJob(Hashtable<String, String[]> params,
45
            HttpServletRequest request, HttpServletResponse response,
46
            String username, String[] groups) throws MetacatSchedulerException;
42
	public abstract void deleteJob(HttpServletRequest request, HttpServletResponse response, 
43
			Hashtable<String, String[]> params, String username, String[] groups) throws MetacatSchedulerException;
47 44
	
48
	public abstract String getJobs(Hashtable<String, String[]> params,
49
            HttpServletRequest request, HttpServletResponse response,
50
            String username, String[] groups) throws MetacatSchedulerException;
45
	public abstract void getJobs(HttpServletRequest request, HttpServletResponse response, 
46
			Hashtable<String, String[]> params, String username, String[] groups) throws MetacatSchedulerException;
51 47
}
src/edu/ucsb/nceas/metacat/scheduler/ScheduledJobAccess.java
101 101

  
102 102
		PreparedStatement pstmt = null;
103 103
		try {
104
			String sql = "SELECT * FROM scheduled_job WHERE name = ? status != 'deleted'"; 
104
			String sql = "SELECT * FROM scheduled_job WHERE name = ? AND status != 'deleted'"; 
105 105
			pstmt = conn.prepareStatement(sql);
106 106

  
107 107
			pstmt.setString(1, jobName);
......
141 141
		return jobDAO;		
142 142
	}
143 143
	
144
	public HashMap<Long, ScheduledJobDAO> getJobsWithParameter(String groupName, String paramName, String paramValue) throws AccessException {
145

  
146
		HashMap<Long, ScheduledJobDAO> allJobsMap = getAllJobs(groupName);
147
		HashMap<Long, ScheduledJobDAO> jobsWithParamMap = new HashMap<Long, ScheduledJobDAO>();
148
		
149
		for (Long jobDAOId : allJobsMap.keySet()) {
150
			ScheduledJobDAO jobDAO = allJobsMap.get(jobDAOId); 
151
			if (paramValue != null && paramName != null) {
152
				ScheduledJobParamDAO jobParamDAO = jobDAO.getJobParam(paramName);
153
				if(jobParamDAO != null && jobParamDAO.getValue().equals(paramValue)) {
154
					jobsWithParamMap.put(jobDAOId, jobDAO);
155
				}
156
			}
157
		}		
158
		
159
		return jobsWithParamMap;
160
	}
161
	
144 162
	public HashMap<Long, ScheduledJobDAO> getAllJobs(String groupName) throws AccessException {
145 163
		ScheduledJobDAO jobDAO = null;
146 164
		
......
275 293
				scheduledJobParamsAccess.createJobParams(updatedJobDAO.getId(), jobParams);
276 294
			} catch (AccessException ae) {
277 295
				if (updatedJobDAO != null) {
278
					deleteJob(updatedJobDAO);
296
					updatedJobDAO.setStatus(StatusUtil.DELETED);
297
					updateJobStatus(updatedJobDAO);
279 298
					scheduledJobParamsAccess.deleteJobParams(updatedJobDAO.getId());
280 299
				} else {
281 300
					logMetacat.warn("ScheduledJobAccess.createJob - Tried to delete non-existant scheduled job: " 
......
285 304
		}
286 305
	}
287 306
	
288
	public void deleteJob(ScheduledJobDAO jobDAO) throws AccessException {	
289
		ScheduledJobParamAccess scheduledJobParamsAccess = new ScheduledJobParamAccess();
290
		
291
		if (jobDAO == null) {
292
			throw new AccessException("ScheduledJobAccess.deleteJob - job DAO cannot be null.");
293
		}
294
		scheduledJobParamsAccess.deleteJobParams(jobDAO.getId());
295
		
296
		PreparedStatement pstmt = null;
297
		
298
		try {
299
			String sql = "UPDATE scheduled_job SET status = ? WHERE id = ?";	
300
			pstmt.setString(1, StatusUtil.DELETED);
301
			pstmt.setLong(2, jobDAO.getId());
302
			
303
			logMetacat.info("ScheduledJobAccess.deleteJob - " + sql);
304
			
305
			logMetacat.info("SQL params:  [" + StatusUtil.DELETED + ","
306
					+ jobDAO.getId() + "]");
307

  
308
			pstmt.execute();
309
		} catch (SQLException sqle) {
310
			throw new AccessException("ScheduledJobAccess.deleteJob - SQL error when " 
311
					+ "deleting scheduled job " + jobDAO.getName()  + " : "  + sqle.getMessage());
312
		} finally {
313
			try {
314
				if (pstmt != null) {
315
					pstmt.close();
316
				}
317
			} catch (SQLException sqle) {
318
				logMetacat.error("ScheduledJobAccess.deleteJob - An error occurred " 
319
						+ "closing prepared statement: " + sqle.getMessage());
320
			} finally {
321
				DBConnectionPool.returnDBConnection(conn, serialNumber);
322
			}
323
		}				
324
	}
325
	
326 307
	public void updateJobStatus(ScheduledJobDAO jobDAO) throws AccessException {	
327 308
		
328 309
		if (jobDAO == null) {
......
333 314
		
334 315
		try {
335 316
			String sql = "UPDATE scheduled_job SET status = ? WHERE id = ?";	
317
			
318
			pstmt = conn.prepareStatement(sql);
336 319
			pstmt.setString(1, jobDAO.getStatus());
337 320
			pstmt.setLong(2, jobDAO.getId());
338 321
			
src/edu/ucsb/nceas/metacat/scheduler/ScheduledJobParamAccess.java
132 132
		PreparedStatement pstmt = null;
133 133
		ScheduledJobParamDAO jobParamDAO = null;
134 134
		try {
135
			String sql = "SELECT * FROM scheduled_job_params WHERE job_id = ? status != 'deleted'"; 
135
			String sql = "SELECT * FROM scheduled_job_params WHERE job_id = ? AND status != 'deleted'"; 
136 136
			pstmt = conn.prepareStatement(sql);
137 137

  
138 138
			pstmt.setLong(1, jobId);
......
152 152
			return jobParamList;
153 153
			
154 154
		} catch (SQLException sqle) {
155
			throw new AccessException("ScheduledJobAccess.getJobByName - SQL error when getting " 
155
			throw new AccessException("ScheduledJobAccess.getJobParamsForJobId - SQL error when getting " 
156 156
					+ "scheduled job parameter for job id: " + jobId  + " : "  + sqle.getMessage());
157 157
		} finally {
158 158
			try {
......
160 160
					pstmt.close();
161 161
				}
162 162
			} catch (SQLException sqle) {
163
				logMetacat.error("ScheduledJobAccess.getJobByName - An error occurred " 
163
				logMetacat.error("ScheduledJobParamAccess.getJobParamsForJobId - An error occurred " 
164 164
						+ "closing prepared statement: " + sqle.getMessage());
165 165
			} finally {
166 166
				DBConnectionPool.returnDBConnection(conn, serialNumber);
......
193 193
			return jobParamList;
194 194
			
195 195
		} catch (SQLException sqle) {
196
			throw new AccessException("ScheduledJobAccess.getJobByName - SQL error when getting " 
196
			throw new AccessException("ScheduledJobParamAccess.getAllJobParams - SQL error when getting " 
197 197
					+ "scheduled job parameters : "  + sqle.getMessage());
198 198
		} finally {
199 199
			try {
......
201 201
					pstmt.close();
202 202
				}
203 203
			} catch (SQLException sqle) {
204
				logMetacat.error("ScheduledJobAccess.getJobByName - An error occurred " 
204
				logMetacat.error("ScheduledJobParamsAccess.getAllJobParams - An error occurred " 
205 205
						+ "closing prepared statement: " + sqle.getMessage());
206 206
			} finally {
207 207
				DBConnectionPool.returnDBConnection(conn, serialNumber);

Also available in: Unified diff