package org.ngbw.web.actions;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.ngbw.sdk.UsageLimitException;
import org.ngbw.sdk.Workbench;
import org.ngbw.sdk.WorkbenchSession;
import org.ngbw.sdk.api.tool.ParameterValidator;
import org.ngbw.sdk.api.tool.ToolConfig;
import org.ngbw.sdk.common.util.CipresTaskThread;
import org.ngbw.sdk.common.util.StringUtils;
import org.ngbw.sdk.core.shared.TaskRunStage;
import org.ngbw.sdk.core.types.DataFormat;
import org.ngbw.sdk.database.Folder;
import org.ngbw.sdk.database.ResourceConversionService;
import org.ngbw.sdk.database.RunStatus;
import org.ngbw.sdk.database.SourceDocument;
import org.ngbw.sdk.database.Statistics;
import org.ngbw.sdk.database.Task;
import org.ngbw.sdk.database.TaskInputSourceDocument;
import org.ngbw.sdk.database.TaskRun;
import org.ngbw.sdk.database.User;
import org.ngbw.sdk.database.UserDataItem;
import org.ngbw.sdk.database.XsedeAttributeReportingScheduler;
import org.ngbw.sdk.database.util.UserDataItemSortableField;
import org.ngbw.sdk.jobs.UsageLimit;
import org.ngbw.sdk.parser.task.DataFormatInspectorTask;
import org.ngbw.sdk.tool.DisabledResourceException;
import org.ngbw.sdk.tool.Tool;
import org.ngbw.sdk.tool.ReusedJobIDException;
/**
* Struts action class to handle creation (create/edit) of tasks in the NGBW web
* application.
*
* @author Jeremy Carver
* @author Tony Chen
*/
@SuppressWarnings("serial")
public class CreateTask extends ManageTasks
{
private static final Logger logger = Logger.getLogger(CreateTask.class);
/**
* User must open Tool GUI and save parameters, so JavaScript preconds and ctrls are eval'd and
* defaults are added. GUI must be opened for new jobs and and if the tool is changed. For cloned
* jobs GUI doesn't need to be opened (unless the tool is changed).
*
*
* We communicate between the Tool GUI (ToolParameters) and the CreateTask GUI by putting
* TOOL_GUI_OPENED in task.toolParameters:
*
*
* 1) ToolParameters.execute inserts TOOL_GUI_OPENED when the parameters are saved, as does
* CreateTask.clone. 2) Changing the tool, clears all parameters, including TOOL_GUI_OPENED. 3)
* Remove TOOL_GUI_OPENED right before saving the task and we don't want to save this parameter.
*/
protected static final String TOOL_GUI_OPENED = "gui_opened__";
// result constants
public static final String SET_INPUT = "setInput";
public static final String PARAMETERS = "parameters";
public static final String TOOLS = "tools";
// parameter attribute key constants
public static final String SELECTED_TOOL = "selectedTool";
public static final String TASK = "task";
// session attribute key constants
public static final String INPUT_DATA = "inputData";
// task action constants
public static final String SET_DESCRIPTION = "Set Description";
public static final String SAVE_TASK = "Save Task";
public static final String SAVE_AND_RUN_TASK = "Save and Run Task";
public static final String DISCARD_TASK = "Discard Task";
public static final String BEAST_TOOLID = "BEAST_TG";
public static final String BEAST2_TOOLID = "BEAST2_XSEDE";
// task form tab label constants
public static final String TASK_SUMMARY_TAB_LBL = "Task Summary";
public static final String SELECT_DATA_TAB_LBL = "Select Data";
public static final String SELECT_TOOL_TAB_LBL = "Select Tool";
public static final String SET_PARAMETERS_TAB_LBL = "Set Parameters";
// result constants
public static final String CREATE_FOLDER = "createFolder";
public static final String INVALID_TASKID = "invalidTaskID";
// error message constants
public static final String CANNOT_SUBMIT_COREHOURS =
"Sorry, job submission from your account has been temporarily suspended "
+ "because you have reached the maximum number of core hours for the "
+ "current allocation year. For information on reactivating your "
+ "account, or if you think you received this message in error, please "
+ "contact cipresadmin@sdsc.edu";
public static final String CANNOT_SUBMIT_STORAGELIMIT =
"Sorry, job submission from your account has been temporarily suspended "
+ "because you have exceeded the maximum amount of data storage "
+ "permitted. You can reactivate your account by deleting some of your "
+ "data. If you have questions, or think you received this message in "
+ "error, please contact cipresadmin@sdsc.edu";
public static final String JAVASCRIPT_DISABLED = "Javascript is disabled on your browser and you have CIPRES open on multiple tabs. This might have caused problems. Please close all other tabs that have CIPRES open and start over again.";
// task form properties
private String tab;
// task summary form properties
private String label;
// task data selection form properties
private List inputData;
private List mappedInput;
private Integer unmappedInputCount = null;
@SkipValidation
@Override
public String create ()
{
//logger.debug("BEGIN: create()::String");
setTab(TASK_SUMMARY_TAB_LBL);
setInput(null);
setCurrentTask(null);
//logger.debug("END: create()::String");
return INPUT;
}
@Override
public String clone ()
{
Task task = getRequestTask(TASK);
if (task == null)
{
reportUserError("You must select a task to make a clone of it.");
return LIST;
}
else if (!getTools().contains(task.getToolId()))
{
reportUserError("The tool, " + task.getToolId() + ", is no longer available.");
return LIST_ERROR;
}
Task clone = cloneTask(task);
if (clone == null)
{
reportUserError("There was an error cloning " + "the selected task.");
return LIST_ERROR;
}
logger.debug(getUsernameString() + "CLONE taskId = " + task.getTaskId() + ", new taskId is " + clone.getTaskId());
setCurrentTask(clone);
setTab(TASK_SUMMARY_TAB_LBL);
return INPUT;
}
public String restart ()
{
String[] taskId = (String[]) getParameters().get(ID);
if (taskId == null || taskId.length == 0)
{
reportUserError("You must select a task to restart it.");
return LIST;
}
Task task = getSelectedTask(Long.parseLong(taskId[0]));
if (!getTools().contains(task.getToolId()))
{
reportUserError("The tool, " + task.getToolId() + ", is no longer available.");
return LIST_ERROR;
}
try
{
TaskRun newRun = task.runs().last().createClone();
newRun.setRestart(true);
newRun.setStage(TaskRunStage.READY);
task.runs().add(newRun);
//task.save();
logger.debug("RESTART taskId = " + task.getTaskId() + ", new run is number " + newRun.getRunNumber());
Tool tool = Workbench.getInstance().getTool(task.getToolId());
ToolConfig config = tool.getToolConfig();
if (config.isRestartInterface())
{
logger.info("RESTART this tool: " + task.getToolId() + " requires showing interaface when being restarted");
setCurrentTask(task);
String toolAction = getToolAction();
if (toolAction == null || toolAction.length() <= 0)
{
logger.info("RESTART toolAction is null");
}
else
logger.info("RESTART toolAction = " + toolAction);
setTab(TASK_SUMMARY_TAB_LBL);
//setTab(SET_PARAMETERS_TAB_LBL);
return INPUT;
//return PARAMETERS;
}
else
task.save();
}
catch ( Throwable error )
{
logger.error("Error adding new task run to task " + task.getTaskId() + ":", error);
}
return run(task);
}
public String noAutoResubmission ()
{
Task task = getRequestTask(TASK);
if (task == null)
{
reportUserError("You must select a task to disable auto resubmission of it.");
return LIST;
}
try
{
TaskRun lastRun = task.runs().last();
lastRun.setStatus(RunStatus.NO_RESUBMIT);
lastRun.save();
logger.debug("noAutoResubmission taskId = " + task.getTaskId() + ", last run is number " + lastRun.getRunNumber() + " Setting status to NO_RESUBMIT");
}
catch ( Throwable error )
{
logger.error("Error setting status to NO_RESUBMIT: taskId = " + task.getTaskId());
}
refresh ();
return LIST_ERROR;
}
@SkipValidation
@Override
public String edit ()
{
setTab(TASK_SUMMARY_TAB_LBL);
return INPUT;
}
private String button;
public void setButton(String b) {
button = b;
}
public String getButton() {
return button;
}
@SkipValidation
@Override
public String execute ()
{
// make sure label gets saved if user has entered one
if (getLabel() != null && !getLabel().isEmpty())
{
getCurrentTask().setLabel(label);
}
String[] buttons = (String[]) getParameters().get("method:execute");
String button = (buttons == null || buttons.length == 0)?
"" : buttons[0];
logger.debug("Enter");
logger.debug(button);
logger.debug("Label: " + label);
if (button.equals(SET_DESCRIPTION))
{
String label = getLabel();
if (label == null || label.trim().isEmpty()) {
addFieldError("label", "Description is required.");
}
else {
getCurrentTask().setLabel(label);
addActionMessage("Description \"" + label + "\" successfully set to current task.");
}
}
else if (button.equals(SELECT_DATA_TAB_LBL))
{
try
{
Long[] selectedIds = getSelectedIds();
if (selectedIds == null || selectedIds.length <= 0) {
setTab(SELECT_DATA_TAB_LBL);
addActionError("You must select one or more data items to set them as input to the current task.");
}
else {
String retVal = setSelectedInputData();
return retVal;
}
}
catch ( Throwable t )
{
logger.error(t);
super.reportUserError(t.getMessage());
return ERROR;
}
}
else if (button.equals(SAVE_TASK)) // if "Save Task" button is pressed ...
{
try
{
if (isTaskValid())
{
if (saveTask() != null) {
reportUserMessage("Task \"" + getLabel() + "\" successfully saved.");
return LIST;
}
else {
reportUserError("Error saving task \"" + getLabel() + "\"");
return INPUT;
}
}
else {
this.printTaskSessionContent();
logger.debug("Task validation failed.");
}
return INPUT;
}
catch ( ReusedJobIDException | MySQLIntegrityConstraintViolationException e )
{
logger.error(e.getMessage());
logger.error(JAVASCRIPT_DISABLED);
addActionError(JAVASCRIPT_DISABLED);
return INVALID_TASKID;
}
catch ( Exception error )
{
reportUserError(error, "Error saving task \"" + getLabel() + "\"");
return ERROR;
}
}
else if (button.equals(SAVE_AND_RUN_TASK)) // if "Save and Run Task" button is pressed ...
{
boolean isValid = false;
try
{
if (isTaskValid())
{
logger.debug("Task validated.");
String disabledMessage = disabledMessage(null);
if (disabledMessage != null)
{
logger.debug("DisabledMessage: " + disabledMessage);
saveTask();
addActionError("Your task has been saved but can't be run at this time. " + disabledMessage);
return LIST_ERROR;
}
logger.debug("SaveAndRunTask() ...");
if (saveAndRunTask() != null)
{
reportUserMessage("Task \"" + getLabel() + "\" successfully saved and submitted.");
isValid = true;
return LIST;
}
else
{
logger.debug("SaveAndRunTask() ... errors!");
reportUserError(String.format("Error saving task '%s'", getLabel())); // "Error saving task \"" + getLabel() + "\"");
return INPUT;
}
}
else
{
this.printTaskSessionContent();
logger.debug("Task validation failed.");
}
return INPUT;
}
catch ( UsageLimitException ule )
{
logger.error(ule.getMessage());
reportUserError(ule.getMessage());
return INPUT;
}
catch ( DisabledResourceException e )
{
logger.error(e.getMessage());
addActionError("Your task has been saved but can't be run at this time. " + e.getMessage());
return INPUT;
}
catch ( ReusedJobIDException | MySQLIntegrityConstraintViolationException e )
{
logger.error(e.getMessage());
logger.error(JAVASCRIPT_DISABLED);
addActionError(JAVASCRIPT_DISABLED);
return INVALID_TASKID;
}
catch ( Exception error )
{
logger.error(error.getMessage(), error);
reportUserError(error, "Error saving and submitting task \"" + getLabel() + "\"");
return INPUT;
}
finally
{
if (isValid) {
setCurrentTask(null);
refreshFolderTaskTabs();
}
}
}
return INPUT;
}
public String updateLabel() {
if (getLabel() != null && !getLabel().isEmpty())
{
getCurrentTask().setLabel(label);
}
return SUCCESS;
}
private String disabledMessage ( Task task )
{
if (task == null)
{
task = getCurrentTask();
}
String toolid = task.getToolId();
try
{
Tool tool = Workbench.getInstance().getTool(toolid);
return tool.disabled();
}
catch ( NullPointerException ne )
{
return toolid + " is not in the list of available tools.";
}
}
/**
* This is run from taskList.jsp when there's a RUN button next to a saved
* task. Can't use tokenSession to prevent double submit because RUN is a
* link not a button on that form.
*
* @return
*/
@SkipValidation
public String run ()
{
// get selected task ID from request param, if present
String[] taskId = (String[]) getParameters().get(ID);
try
{
if (taskId != null && taskId.length > 0)
{
Task task = getSelectedTask(Long.parseLong(taskId[0]));
return run(task);
}
else
{
addActionError("You must select a task to run it.");
return LIST;
}
}
catch (UsageLimitException ule)
{
addActionError(ule.getMessage());
return LIST_ERROR;
}
}
private String run ( Task task )
{
super.setCurrentTask(task);
String disabledMessage = disabledMessage(task);
if (disabledMessage != null)
{
addActionError(disabledMessage);
return LIST_ERROR;
}
logger.debug(
getUsernameString() +
String.format("RUN TaskID=[%d], task.getToolId() is [%s]",
task.getTaskId(), task.getToolId()));
String msg = whyToolNotAllowed(task.getToolId());
if (msg != null)
{
addActionError(msg);
return LIST_ERROR;
}
try
{
if (!task.getUser().getCanSubmit())
{
addActionError(CANNOT_SUBMIT_COREHOURS);
logger.debug(CANNOT_SUBMIT_COREHOURS);
return LIST_ERROR;
}
else if (!task.getUser().canSubmit())
{
addActionError(CANNOT_SUBMIT_STORAGELIMIT);
logger.debug(CANNOT_SUBMIT_STORAGELIMIT);
return LIST_ERROR;
}
// Compute the predicted su to only enforce user's usage limit.
computePredictedSuAndEnforceUserLimits(task);
try
{
logger.debug(getUsernameString() + "Calling submitTask for taskId " + task.getTaskId());
getWorkbench().submitTask(task, loggedInViaIPlant());
// Populate XSEDE Job Attribute reporting record.
populateXsedeAttributeReportingRecord(task);
}
catch ( DisabledResourceException e )
{
addActionError(e.getMessage());
return LIST_ERROR;
}
catch ( ReusedJobIDException | MySQLIntegrityConstraintViolationException e )
{
logger.error(e.getMessage());
addActionError("Javascript is disabled on your browser and you have CIPRES open on multiple tabs. This may cause problems. Please close all other tabs that have CIPRES open.");
return INVALID_TASKID;
}
reportUserMessage("Submitting task \"" + task.getLabel() + "\"");
refreshFolderTaskTabs();
}
catch (UsageLimitException ule)
{
logger.debug("UsageLimitException caught: " + ule.getMessage());
throw ule;
}
catch ( Throwable error )
{
reportUserError(error, "Error submitting task \"" + getLabel() + "\"");
}
return LIST;
}
@SkipValidation
@Override
public String cancel ()
{
clearErrorsAndMessages();
String[] button = (String[]) getParameters().get("method:cancel");
if (button != null && button.length > 0)
{
if (button[0].equals(DISCARD_TASK))
{
setInput(null);
setCurrentTask(null);
addActionMessage("Task not saved.");
return LIST;
}
else
{
addActionMessage("Task input not saved.");
}
}
setTab(TASK_SUMMARY_TAB_LBL);
return INPUT;
}
@SkipValidation
public String changeTab () throws Throwable
{
logger.trace("BEGIN: changeTab()::String");
String retVal = INPUT;
//Get changed description from request param, if present
String[] desc = (String[]) getParameters().get("description");
if (desc != null && desc.length > 0 && desc[0].length() > 0) {
logger.debug(String.format("Changed Label to [%s]", desc[0]));
getCurrentTask().setLabel(desc[0]);
}
// Get selected tab from request param, if present.
String[] tabs = (String[]) getParameters().get(TAB);
// TRACE - 1
if (tabs != null && tabs.length > 0)
{
logger.debug(String.format(super.getUsernameString() + "Selected Tab is [%s]", tabs[0]));
setSessionAttribute(START_NEW_TASK, "false");
setTab(tabs[0]);
String selectedTab = getTab();
logger.debug(String.format("The tab=[%s]", selectedTab));
// If the target tab is 'Set Parameters,' check to see if a tool and data item have
// been selected. Display a message if not.
if (selectedTab != null && selectedTab.trim().equals(SET_PARAMETERS_TAB_LBL))
{
// Data item is not selected, display dat items list.
if (!hasInput())
{
setTab(nextTab());
addActionError("You must select a data item to proceed with task creation.");
}
// Tool is not selected, display tools list.
else if (!hasTool())
{
setTab(nextTab());
addActionError("You must select a task category to proceed with task creation.");
}
// Both data item(s) and tool are selected; Parse the UserDataItem(s) and
// pre-populate parameters values.
else
{
// Parse the input data file.
parseBeastInputDataFile();
if (!inputDataFileAndToolCompatible())
{
retVal = INPUT;
setTab(SELECT_TOOL_TAB_LBL);
}
else if (getToolAction() != null)
{
retVal = PARAMETERS;
logger.debug(String.format("ToolAction=[%s]", getToolAction()));
}
}
}
else
{
//addActionError("You must select a task category and data item to proceed with task creation.");
}
}
else
{
//addActionError("You must select a task category to proceed with task creation.");
}
logger.debug(String.format("RetVal=[%s]", retVal));
logger.trace("END: changeTab()::String");
return retVal;
}
@SkipValidation
public String changeDataTab () throws Exception
{
// get selected tab from request param, if present
String[] tab = (String[]) getParameters().get(TAB);
if (tab != null && tab.length > 0)
{
getFolderDataTabs().setCurrentTab(tab[0]);
}
setTab(SELECT_DATA_TAB_LBL);
return INPUT;
}
@SkipValidation
@Override
public String changeToolTab ()
{
super.changeToolTab();
setTab(SELECT_TOOL_TAB_LBL);
return INPUT;
}
@SkipValidation
public String selectTool () throws Throwable
{
logger.debug("BEGIN: selectTool()::String");
String nextTab = SELECT_DATA_TAB_LBL;
String retVal = INPUT;
Folder folder = getCurrentFolder();
if (folder == null)
{
retVal = CREATE_FOLDER;
addActionError("You must create a folder first before you can select a tool to create a task");
}
// if no folder is currently selected, return to the tool list page
else if (getCurrentFolder() == null)
{
retVal = TOOLS;
addActionError("You must select a folder from the left panel to start a new task.");
}
else
{
// This attribute is set to true or false each time NgbwSupport.changeToolTab() is called.
// It's set to false in CreateTask.changeTab().
/*
* When user chooses the Toolkit tab, NgbwSupport.changeToolTab is
* called w/o a tab parameter and we set START_NEW_TASK = true.
*
* If it's called with a parameter (though I'm not sure that ever
* happens) we set START_NEW_TASK = false.
*
* When user is creating a task and presses Select Tool button or
* Tab we call CreateTask.changeTab() and in their I set
* START_NEW_TASK = false. This is all to make sure we don't end up
* working on an existing task when the user goes to the Toolkit
* tab to create a new one.
*
* Users were viewing output of one task, going to Toolkit tab, and
* they'd end up editting the task they just viewed, and trying to
* run it again!
*/
String startNewTask = (String) getSessionAttribute(START_NEW_TASK);
if (startNewTask != null && startNewTask.equals("true"))
{
create();
}
// get selected tool from request param, if present
String[] tool = (String[]) getParameters().get(SELECTED_TOOL);
if (tool != null && tool.length > 0)
{
setTool(getSelectedTool(tool[0]));
if (getToolId() == null)
{
addActionError("Error selecting tool \"" + tool[0] + "\": tool not found.");
}
else
{
String msg = whyToolNotAllowed(getToolId());
if (msg != null)
{
setTool(null);
addActionMessage(msg);
}
else if (!inputDataFileAndToolCompatible())
{
nextTab = SELECT_TOOL_TAB_LBL;
}
else
{
//nextTab = nextTab();
nextTab = TASK_SUMMARY_TAB_LBL;
addActionMessage("Tool \"" + tool[0] + "\" successfully set to current task.");
}
}
}
else
{
addActionError("You must select a tool to set it to the current task.");
}
retVal = INPUT;
}
setTab(nextTab);
logger.debug(String.format("Next Tab=[%s]", nextTab));
// If next destination tab is 'Set Parmameters,'
// the returned value must be 'PARAMETERS'.
if (nextTab.trim().equals(SET_PARAMETERS_TAB_LBL) && hasParameters())
{
retVal = PARAMETERS;
}
logger.debug(String.format("RetVal=[%s]", retVal));
logger.debug("END: selectTool()::String");
return retVal;
}
public String getTab ()
{
return tab;
}
public void setTab ( String tab )
{
if (isValidTab(tab))
{
this.tab = tab;
}
else
{
throw new RuntimeException("CreateTask.setTab() was called "
+ "with an invalid argument.");
}
}
@Override
public Task getCurrentTask ()
{
Task task = super.getCurrentTask();
if (task == null)
{
// This creates a new Task() object
try
{
task = getWorkbenchSession().getTaskInstance(getCurrentFolder());
}
catch ( IOException | SQLException error )
{
logger.error("Error creating a new task");
}
setTaskFolder(getCurrentFolder());
setCurrentTask(task);
}
return task;
}
@Override
public void setCurrentTask ( Task task )
{
super.setCurrentTask(null);
if (task != null)
{
// get input of task and store it properly
Map> inputMap = null;
try
{
//inputMap = new HashMap>( task.input());
inputMap = new HashMap>();
for (Map.Entry> entry : task.runs().last().input().entrySet())
{
List newList = new ArrayList();
for (TaskInputSourceDocument doc : entry.getValue())
{
newList.add(new TaskInputSourceDocument(doc));
}
inputMap.put(entry.getKey(), newList);
}
}
catch ( IOException | SQLException error )
{
logger.error("Error retrieving new task's input map");
}
finally
{
if (inputMap != null && inputMap.size() > 0)
{
// store entire input map in the session
setInputMap(inputMap);
// store "main" input separately in the session
String tool = task.getToolId();
if (tool != null)
{
String inputParam = getMainInputParameter(tool);
if (inputParam != null)
{
List input
= inputMap.get(inputParam);
if (input != null && input.size() > 0)
{
setSessionAttribute(INPUT_DATA, input);
}
}
}
}
}
setTaskFolder(getCurrentFolder());
super.setCurrentTask(task);
}
}
public void addTaskInput ( String parameter, List input )
{
try
{
Map> inputMap = getInputMap();
if (parameter == null)
{
throw new NullPointerException("Parameter key is null.");
}
else if (input != null)
{
if (inputMap == null)
{
inputMap = new HashMap>();
}
inputMap.put(parameter, input);
setInputMap(inputMap);
}
else if (inputMap != null)
{
inputMap.remove(parameter);
if (inputMap.size() > 0)
{
setInputMap(inputMap);
}
else
{
setInputMap(null);
}
}
}
catch ( Throwable error )
{
logger.error("Error adding input for task");
}
}
@Override
public String getLabel ()
{
return label;
}
@Override
public void setLabel ( String label )
{
this.label = label;
}
@SuppressWarnings("unchecked")
public List getInput ()
{
return (List) getSessionAttribute(INPUT_DATA);
}
/**
* Simultaneously stores the given input both in the HTTP session, and in
* the actual task input
* map (if a tool has already been selected for this task). This parallel
* storage is required to
* keep track of the selected input even in the case of changing tool
* selection, since each tool
* stores its main input under its own input parameter.
*/
public void setInput ( List input )
{
setSessionAttribute(INPUT_DATA, input);
String tool = getToolId();
if (tool != null)
{
String inputParam = getMainInputParameter(tool);
if (inputParam != null)
{
addTaskInput(inputParam, input);
}
}
}
public boolean hasInput ()
{
return (getInput() != null);
}
public int getInputCount ()
{
List input = getInput();
if (input == null)
{
return 0;
}
else
{
return input.size();
}
}
private boolean setTool ( String tool )
{
// If the tool changes, the parameters must be cleared, but the main
// input must be preserved.
boolean status = true;
Task task = getCurrentTask();
String currentTool = getToolId();
if (currentTool == null ||
(tool != null && !currentTool.equals(tool)))
{
try
{
task.setToolId(tool);
ToolParameters parameterAction =
(ToolParameters) Class.forName(
"org.ngbw.web.actions.tool."
+ tool.toLowerCase()).newInstance();
parameterAction.setSession(getSession());
parameterAction.reset();
// set default parameters into task.
setParameters(task, parameterAction.getUIParameters());
setInputMap(parameterAction.getInputDataItems());
// the main input must be preserved
List input = getInput();
if (input != null)
{
setInput(input);
}
if (hasMappedInput() && hasTool())
{
status = inputDataFileAndToolCompatible();
}
}
catch ( Throwable error )
{
status = false;
clearParameters(task);
setInputMap(null);
logger.error("Error pre-populating default parameter values " + "for tool \"" + tool.toString() + "\"");
}
}
return status;
}
public boolean isRestart()
{
boolean isRestart = false;
Task task = getCurrentTask ();
if (task != null)
{
try
{
TaskRun newRun = task.runs().last();
if (newRun != null)
return newRun.isRestart();
}
catch (Exception e)
{
logger.error("Exception thrown when trying to decide whether current run is a restart or not");
logger.error(e);
}
}
return isRestart;
}
public boolean hasTool ()
{
return getToolId() != null;
}
@Override
public boolean hasParameters ()
{
Task task = getCurrentTask();
if (task == null)
{
return false;
}
else
{
Map parameters = null;
try
{
parameters = task.toolParameters();
}
catch ( Throwable error )
{
logger.error("Error determining whether or not task "
+ task.getTaskId() + " has parameters");
return false;
}
if (parameters == null || parameters.size() < 1)
{
Map> input = getInputMap();
if (input == null || input.size() < 1)
{
return false;
}
else if (input.size() == 1)
{
String inputParam = getMainInputParameter(task.getToolId());
if (inputParam != null && input.containsKey(inputParam))
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
else
{
return true;
}
}
}
@Override
public Map> getParameterInput ()
{
Map> input = getInputMap();
if (input == null)
{
return null;
}
else
{
String inputParam = getMainInputParameter(getTool());
if (inputParam != null && input.containsKey(inputParam))
{
input = new HashMap>(input);
input.remove(inputParam);
}
return input;
}
}
@Override
public int getParameterCount ()
{
Task task = getCurrentTask();
if (task == null)
{
return 0;
}
else
{
int parameterCount = 0;
Map parameters = null;
try
{
parameters = task.toolParameters();
}
catch ( Throwable error )
{
logger.error("Error retrieving parameter count for task "
+ task.getTaskId());
}
if (parameters != null)
{
parameterCount += parameters.size();
}
Map> parameterInput = getParameterInput();
if (parameterInput != null)
{
parameterCount += parameterInput.size();
}
return parameterCount;
}
}
/**
* Do not validate parameters, and do not report user error till validation of all fields are
* done.
*
* @return
* @throws Exception
*/
private boolean isTaskValid () throws Exception
{
StringBuilder errors = new StringBuilder();
StringBuilder warns = new StringBuilder();
Task task = getCurrentTask();
if (task == null)
{
return false;
}
if (!isRestart())
if (getLabel() == null || getLabel().trim().isEmpty() || task.getLabel() == null || task.getLabel().trim().isEmpty())
{
errors.append("Please enter a description for your task. ");
}
String tool = task.getToolId();
if (tool == null)
{
errors.append("Please choose a tool for your analysis. ");
}
String inputParam = getMainInputParameter(tool);
Map> inputMap = getInputMap();
if (inputParam == null || inputMap == null || !inputMap.containsKey(inputParam))
{
errors.append("Please choose one or more data items for the task. ");
}
if (!task.toolParameters().keySet().contains(TOOL_GUI_OPENED))
{
if (!isRestart())
errors.append("Please review the 'Input Parameters'. ");
else
warns.append("Please review the 'Input Parameters' before proceeding. ");
}
// If there are errors, report errors to user.
if (errors.length() > 0)
{
reportUserError(errors.toString());
return false;
}
if (warns.length() > 0)
{
reportUserMessage(warns.toString());
return false;
}
return true;
}
/* ================================================================
* Task input data selection
* page property accessor methods
* ================================================================ */
//TODO: filter available input data by tool selection, this will require
//a more complex treatment of tool mode
public List
getInputData_tbd ()
{
// get the input data list stored in the action
if (inputData != null)
{
return inputData;
}
// if not found, construct the proper input data list
else
{
try
{
String tool = getToolId();
if (tool != null)
{
String input = getMainInputParameter(tool);
if (input == null)
{
inputData = getCurrentFolder().findDataItems();
}
else
{
inputData = getCurrentFolder().findDataItems();
}
}
else
{
inputData = getCurrentFolder().findDataItems();
}
return inputData;
}
catch ( Throwable error )
{
logger.error("Error retrieving data for current folder");
return null;
}
}
}
public List
getInputData ()
{
logger.trace("BEGIN: getInputData()::List");
if (null == inputData || inputData.isEmpty())
{
try
{
inputData = getCurrentFolder().findDataItems();
}
catch ( Throwable error )
{
logger.error("Error retrieving data for current folder");
}
}
if (null != inputData)
{
Collections.sort(inputData, UserDataItem.SORT_BY_CREATED_TIME_DESC);
logger.debug("MappedInput list of UserDataItem is sorted.");
}
logger.trace("END: getInputData()::List");
return inputData;
}
public boolean hasInputData ()
{
List inputData = getInputData();
return (inputData != null && inputData.size() > 0);
}
//TODO: add the proper interface and get rid of this method!
public List getMappedInput_tbd ()
{
// get the mapped input list stored in the action
if (mappedInput != null)
{
return mappedInput;
}
// if not found, construct the proper mapped input list
else
{
List input = getInput();
unmappedInputCount = 0;
if (input == null)
{
mappedInput = null;
}
else
{
WorkbenchSession session = getWorkbenchSession();
mappedInput = new ArrayList(input.size());
for (TaskInputSourceDocument inputDocument : input)
{
try
{
Long id = Long.parseLong(inputDocument.getName());
UserDataItem dataItem = session.findUserDataItem(id);
if (dataItem != null)
{
mappedInput.add(dataItem);
}
else
{
unmappedInputCount++;
}
}
catch ( Throwable error )
{
unmappedInputCount++;
continue;
}
}
if (mappedInput.size() < 1)
{
mappedInput = null;
}
else
{
getWorkbenchSession().sortUserDataItems(mappedInput,
UserDataItemSortableField.ID, false);
}
}
return mappedInput;
}
}
public List
getMappedInput ()
{
logger.trace("BEGIN: getMappedInput()::List");
if (null == mappedInput || mappedInput.isEmpty())
{
List input = getInput();
unmappedInputCount = 0;
if (null != input)
{
WorkbenchSession session = getWorkbenchSession();
mappedInput = new ArrayList<>(input.size());
for (TaskInputSourceDocument inputDocument : input)
{
try
{
Long id = Long.parseLong(inputDocument.getName());
UserDataItem dataItem = session.findUserDataItem(id);
if (null != dataItem)
{
mappedInput.add(dataItem);
}
else
{
unmappedInputCount++;
}
}
catch ( Throwable error )
{
unmappedInputCount++;
}
}
}
}
if (null != mappedInput && !mappedInput.isEmpty())
{
getWorkbenchSession()
.sortUserDataItems(
mappedInput,
UserDataItemSortableField.ID,
false);
Collections.sort(mappedInput, UserDataItem.SORT_BY_CREATED_TIME_DESC);
logger.debug("MappedInput list of UserDataItem is sorted.");
}
else {
mappedInput = null;
}
logger.trace("END: getMappedInput()::List");
return mappedInput;
}
public boolean hasMappedInput ()
{
return (getMappedInput() != null);
}
//TODO: add the proper interface and get rid of this method!
public int getUnmappedInputCount ()
{
// get the unmapped input count stored in the action
if (unmappedInputCount != null)
{
return unmappedInputCount;
}
// if not found, construct the proper unmapped input count
else
{
List input = getInput();
unmappedInputCount = 0;
if (input == null)
{
mappedInput = null;
}
else
{
WorkbenchSession session = getWorkbenchSession();
mappedInput = new ArrayList(input.size());
for (TaskInputSourceDocument inputDocument : input)
{
try
{
Long id = Long.parseLong(inputDocument.getName());
UserDataItem dataItem = session.findUserDataItem(id);
if (dataItem != null)
{
mappedInput.add(dataItem);
}
else
{
unmappedInputCount++;
}
}
catch ( Throwable error )
{
unmappedInputCount++;
continue;
}
}
if (mappedInput.size() < 1)
{
mappedInput = null;
}
else
{
getWorkbenchSession().sortUserDataItems(mappedInput,
UserDataItemSortableField.ID, false);
}
}
return unmappedInputCount;
}
}
public boolean hasUnmappedInput ()
{
return (getUnmappedInputCount() > 0);
}
public boolean isCurrentTool ( String tool )
{
String currentTool = getTool();
if (tool == null || currentTool == null)
{
return false;
}
else
{
return tool.equals(currentTool);
}
}
protected Task getRequestTask ( String parameter )
{
String taskId = getRequestParameter(parameter);
if (taskId == null)
{
return null;
}
else
{
try
{
return getSelectedTask(Long.parseLong(taskId));
}
catch ( NumberFormatException error )
{
return null;
}
}
}
protected Task cloneTask ( Task task )
{
if (task == null)
{
return null;
}
try
{
WorkbenchSession session = getWorkbenchSession();
if (session == null)
{
throw new NullPointerException("No session is present.");
}
else
{
Task newtask = session.cloneTask(task);
if (newtask != null)
{
// Say that tool gui was opened, since in a clone the parameters went thru the gui's javascript once already.
// If user changes the tool, the tool parameters will all be cleared.
logger.debug("Adding TOOL_GUI_OPENED");
newtask.toolParameters().put(TOOL_GUI_OPENED, "1");
}
return newtask;
}
}
catch ( Throwable error )
{
logger.error("Error cloning selected task");
return null;
}
}
protected void setParameters ( Task task, Map parameters ) throws Exception
{
if (task == null)
{
return;
}
clearParameters(task);
if (parameters != null && parameters.size() > 0)
{
try
{
task.toolParameters().putAll(parameters);
}
catch ( Throwable error )
{
logger.debug("Error setting parameter map of size " + parameters.size() + " to task " + task.getTaskId());
logger.error("", error);
throw error;
}
}
}
protected void clearParameters ( Task task )
{
if (task == null)
{
return;
}
try
{
task.toolParameters().clear();
}
catch ( Throwable error )
{
logger.debug("Error clearing parameter map for task " + task.getTaskId());
}
}
protected void setInput ( Task task,
Map> input )
{
if (task == null)
{
return;
}
else
{
clearInput(task);
if (input != null && input.size() > 0)
{
try
{
task.runs().last().input().putAll(input);
}
catch ( Throwable error )
{
logger.debug("Error setting input map of size " + input.size()
+ " to task " + task.getTaskId());
}
}
}
}
protected void clearInput ( Task task )
{
if (task == null)
{
return;
}
else
{
try
{
task.runs().last().input().clear();
}
catch ( Throwable error )
{
logger.debug("Error clearing input map for task " + task.getTaskId());
}
}
}
protected ParameterValidator getParameterValidator ( String tool )
{
try
{
if (tool == null)
{
throw new NullPointerException("Selected tool is null.");
}
else
{
return (ParameterValidator) Class.forName("org.ngbw.web.model.impl.tool."
+ tool.toLowerCase() + "Validator").newInstance();
}
}
catch ( Throwable error )
{
logger.error("Error instantiating validator class for tool");
return null;
}
}
/**
* protected boolean validateParameters() { //TODO: update
* ParameterValidator to accommodate a
* global view of parameter validation try { Task task = getCurrentTask(); ;
* if (task == null)
* throw new NullPointerException("No task is currently selected."); else {
* String tool =
* task.getToolId(); if (tool == null) return false; ParameterValidator
* validator =
* getParameterValidator(tool); Map errors =
* validator.validateParameters(task.toolParameters()); if (errors != null
* && errors.size() > 0)
* return false; errors = validator.validateInput(getInputMap()); if (errors
* != null &&
* errors.size() > 0) return false; return true; } } catch (Throwable error)
* {
* logger.error("Error validating current task's parameters"); return false;
* } }
*/
private Task saveTask () throws ReusedJobIDException
{
try
{
WorkbenchSession session = getWorkbenchSession();
Folder folder = getCurrentFolder();
Task task = getCurrentTask();
if (session == null)
{
throw new NullPointerException("No session is present.");
}
else if (folder == null)
{
throw new NullPointerException("No folder is currently selected.");
}
else if (task == null)
{
throw new NullPointerException("No task is currently selected.");
}
setInput(task, getInputMap());
if (isUneditable(task))
{
throw new ReusedJobIDException("Trying to save to an uneditable task");
}
task.runs().last().setStage(TaskRunStage.READY);
// Here's where task actually gets saved.
if (task.toolParameters().keySet().contains(TOOL_GUI_OPENED))
{
logger.debug("removing TOOL_GUI_OPENED");
task.toolParameters().remove(TOOL_GUI_OPENED);
}
task = session.saveTask(task, folder);
logger.debug(getUsernameString() + "SAVE TASK taskId = " + task.getTaskId() + ", task.getToolId() is " + task.getToolId());
setCurrentTask(null);
refreshFolderTaskTabs();
return task;
}
catch ( IOException | NullPointerException | SQLException error )
{
logger.error("Error saving current task");
return null;
}
}
private Task
saveAndRunTask () throws DisabledResourceException,
UsageLimitException, ReusedJobIDException, MySQLIntegrityConstraintViolationException
{
logger.debug("BEGIN: saveAndRunTask()::Task");
try
{
Workbench workbench = getWorkbench();
Folder folder = getCurrentFolder();
final Task task = getCurrentTask();
final User user = getWorkbenchSession().getUser();
if (workbench == null)
{
throw new NullPointerException("No workbench is present.");
}
else if (folder == null)
{
throw new NullPointerException("No folder is currently selected.");
}
else if (task == null)
{
throw new NullPointerException("No task is currently selected.");
}
//setInput(task, getInputMap());
String msg = whyToolNotAllowed(task.getToolId());
if (msg != null)
{
addActionError(msg);
return null;
}
if (!task.getUser().getCanSubmit())
{
addActionError(CANNOT_SUBMIT_COREHOURS);
logger.error(
String.format(
"User [%d - %s] cannot submit Task [%s] because the user has reached max core hours.",
user.getUserId(),
user.getUsername(),
task.getJobHandle()));
return null;
}
else if (!task.getUser().canSubmit())
{
addActionError(CANNOT_SUBMIT_STORAGELIMIT);
logger.error(
String.format(
"User [%d - %s] cannot submit Task [%s] because the user has reached max data storage.",
user.getUserId(),
user.getUsername(),
task.getJobHandle()));
return null;
}
task.runs().last().setStage(TaskRunStage.READY);
// Here's where it actually gets saved.
if (task.toolParameters().keySet().contains(TOOL_GUI_OPENED))
{
logger.debug(
String.format(
"User [%d - %s], Task [%s] - removing TOOL_GUI_OPENED ...",
user.getUserId(),
user.getUsername(),
task.getJobHandle()));
task.toolParameters().remove(TOOL_GUI_OPENED);
}
// Compute the predicted su to only enforce user's usage limit.
Task taskForSuPredict = new Task(task, folder);
setInput(taskForSuPredict, getInputMap());
computePredictedSuAndEnforceUserLimits(taskForSuPredict);
//computePredictedSuAndEnforceUserLimits(task);
setInput(task, getInputMap());
// ***** User has not reached the limit, continue with the process. //
workbench.saveAndSubmitTask(task, folder, loggedInViaIPlant());
logger.debug(
String.format(
"%s SAVE AND RUN taskId = %d, task.getToolId() is %s.",
getUsernameString(),
task.getTaskId(),
task.getToolId()));
setCurrentTask(null);
refreshFolderTaskTabs();
logger.debug("END: saveAndRunTask()::Task");
return task;
}
catch ( UsageLimitException | DisabledResourceException | ReusedJobIDException | MySQLIntegrityConstraintViolationException e )
{
throw e;
}
catch ( Exception error )
{
logger.error(error.toString());
logger.error("Error saving and running current task");
return null;
}
}
protected boolean isValidTab ( String tab )
{
return
tab != null &&
(tab.equals(TASK_SUMMARY_TAB_LBL)
|| tab.equals(SELECT_DATA_TAB_LBL)
|| tab.equals(SELECT_TOOL_TAB_LBL)
|| tab.equals(SET_PARAMETERS_TAB_LBL));
}
protected String getSelectedTool ( String tool )
{
Collection tools = getTools();
if (tool == null || tools == null || tools.size() < 1)
{
return null;
}
else
{
for (String currentTool : tools)
{
if (currentTool.equalsIgnoreCase(tool))
{
return currentTool;
}
}
}
return null;
}
protected String setSelectedInputData () throws Throwable
{
logger.debug("BEGIN: setSelectedInputData()::String");
String retVal = INPUT;
Long[] selectedIds = getSelectedIds();
if (selectedIds != null && selectedIds.length > 0)
{
boolean hasError = Boolean.FALSE;
List taskInputSrcDocs = new ArrayList<>(selectedIds.length);
for (int i = 0; i < selectedIds.length; i++)
{
UserDataItem dataItem = getSelectedData(selectedIds[i]);
if (dataItem == null)
{
String message = String.format("Error selecting UserDataItem with ID %d: item not found in current folder.", selectedIds[i]);
logger.error(reportUserError(message));
setTab(SELECT_DATA_TAB_LBL);
hasError = Boolean.TRUE;
break;
}
else
{
// This is not used; Unnecessary.
SourceDocument srcDoc = getWorkbenchSession().getSourceDocument(dataItem);
try
{
logger.debug(String.format("UserDataItem [%d] found.", dataItem.getUserDataId()));
TaskInputSourceDocument inputSrcDoc = new TaskInputSourceDocument(dataItem);
inputSrcDoc.setName(Long.toString(dataItem.getUserDataId()));
taskInputSrcDocs.add(inputSrcDoc);
}
catch ( Throwable error )
{
addActionError("There was an error adding your selected input data to your task.");
logger.error(constructMessage(error, "Error creating new TaskInputSourceDocument."));
hasError = Boolean.TRUE;
break;
}
}
}
String nextTab = SELECT_DATA_TAB_LBL;
if (!hasError)
{
setInput(taskInputSrcDocs);
String message = selectedIds.length + " data item";
message += (selectedIds.length > 1)? " data items" : " data item";
message += " successfully set as input to current task.";
// Parse the data file (if necessary).
parseBeastInputDataFile();
// If there is no error(s), validate input and tool.
if (inputDataFileAndToolCompatible())
{
addActionMessage(message);
logger.debug(constructMessage(message));
nextTab = nextTab();
}
}
setTab(nextTab);
logger.debug(String.format("Next Tab=[%s]", nextTab));
// If next destination tab is 'Set Parmameters,'
// the returned value must be 'PARAMETERS'.
if (nextTab.trim().equals(SET_PARAMETERS_TAB_LBL) && hasParameters())
{
retVal = PARAMETERS;
}
}
logger.debug("END: setSelectedInputData()::String");
return retVal;
}
protected void dumpToolParameters ( Task task )
{
if (task == null)
{
return;
}
int i = 1;
// primitive parameters
logger.debug("Examining parameters for task \"" + task.getLabel()
+ "\", running tool \"" + task.getToolId() + "\":");
Map parameters = null;
try
{
parameters = task.toolParameters();
}
catch ( Throwable error )
{
logger.error("Error retrieving parameters for task "
+ task.getTaskId());
}
if (parameters == null || parameters.keySet().size() < 1)
{
logger.debug(" No basic parameters.");
}
else
{
logger.debug(" Basic parameters:");
for (String param : parameters.keySet())
{
if (parameters.get(param) == null)
{
logger.debug(" Parameter " + i + " = \"" + param
+ "\" : exists, but has a null value.");
}
else
{
logger.debug(" Parameter " + i + " = \"" + param
+ "\" : \"" + parameters.get(param) + "\"");
}
i++;
}
}
// file-typed parameters
Map> inputDataItems = null;
try
{
inputDataItems = task.runs().last().input();
}
catch ( Throwable error )
{
logger.error("Error retrieving input for task "
+ task.getTaskId());
}
if (inputDataItems == null || inputDataItems.keySet().size() < 1)
{
logger.debug(" No input data items.");
}
else
{
logger.debug(" Input data items:");
for (String param : inputDataItems.keySet())
{
if (inputDataItems.get(param) == null)
{
logger.debug(" Parameter " + i + " = \"" + param + "\" : exists, but has a null value.");
}
else
{
List input = inputDataItems.get(param);
logger.debug(" Parameter " + i + " = \"" + param + "\" : " + input.size() + " items.");
for (int j = 0; j < input.size(); j++)
{
TaskInputSourceDocument inputDocument = input.get(j);
String message = " Input document " + j;
if (inputDocument == null)
{
logger.debug(message + " exists, but has a null value.");
}
else
{
message += " = TaskInputSourceDocument with name \""
+ inputDocument.getName() + "\", type \""
+ inputDocument.getType() + "\"";
try
{
//message += " and with data of size " + inputDocument.getData().length + " bytes.";
message += " and with data of size " + inputDocument.getDataLength() + " bytes.";
}
catch ( Throwable error )
{
logger.error("Error retrieving source data for " + "input document " + j);
message += " and data of unknown size.";
}
logger.debug(message);
}
}
}
i++;
}
}
}
protected void dumpToolParameters ()
{
dumpToolParameters(getCurrentTask());
}
private String nextTab () throws Throwable
{
logger.debug("BEGIN: nextTab()::String");
String nextTab = TASK_SUMMARY_TAB_LBL;
// Data item is not selected, display dat items list.
if (!hasMappedInput())
{
nextTab = SELECT_DATA_TAB_LBL;
}
// Tool is not selected, display tools list.
else if (!hasTool())
{
nextTab = SELECT_TOOL_TAB_LBL;
}
else if (hasParameters())
{
// Task task = super.getCurrentTask();
// if (task.toolParameters() != null &&
// task.toolParameters().keySet().contains(TOOL_GUI_OPENED))
// {
nextTab = SET_PARAMETERS_TAB_LBL;
// }
}
logger.debug(String.format("*** The Next Tab = [%s]", nextTab));
logger.debug("END: nextTab()::String");
return nextTab;
}
private void
computePredictedSuAndEnforceUserLimits ( final Task task ) throws Exception
{
logger.info("BEGIN: computePredictedSuAndEnforceUserLimits(Task)::void");
String toolId = getToolId();
User user = getWorkbenchSession().getUser();
// Verify active jobs count.
UsageLimit.getInstance().verifyActiveJobCount(user, null);
Tool tool = new Tool(toolId, Workbench.getInstance().getServiceFactory().getToolRegistry());
// Tony:
// When we calculate predicted SU to enforce user's usage limit,
// we have to include the ConversionRatio in the calculation.
Long predictedSUs = Workbench.getInstance().predictSus(tool, task, true);
logger.info(
String.format(
"Task [%s], Predicted SU reported to the user = [%d]",
task.getJobHandle(),
predictedSUs));
// Verify SU usages.
UsageLimit.getInstance().verifySuLimit(user, null, toolId, predictedSUs, loggedInViaIPlant());
logger.info("END: computePredictedSuAndEnforceUserLimits(Task)::void");
}
private void
parseBeastInputDataFile () throws Throwable
{
logger.debug("BEGIN: parseBeastInputDataFile()::void");
// Get all UserDataItems need to be checked and parsed (if necessary).
List userDataItems = getMappedInput();
// Parse the file IF AND ONLY IF the Tool is 'BEAST'
// If not, quite silently.
boolean beastTool = (super.getToolId() != null &&
super.getToolId().trim().equals(BEAST_TOOLID));
if (userDataItems == null || userDataItems.isEmpty())
{
logger.debug("Dataset/data file not selected. NOT parsing.");
}
// Parse the data file only if the tool is BEAST.
else if (beastTool)
{
logger.debug(String.format("Dataset selected; ToolID [%s] selected.", super.getToolId()));
for (UserDataItem userDataItem : userDataItems)
{
if (userDataItem.isParseSucceeded())
{
logger.debug(String.format(
"UserDataItemID=[%d] Label=[%s] is already parsed;\n%s",
userDataItem.getUserDataId(),
userDataItem.getLabel(),
StringUtils.map2String(userDataItem.metaData())));
}
else
{
logger.debug(
String.format(
"Parsing UserDataItemID=[%d] Label=[%s] ...",
userDataItem.getUserDataId(),
userDataItem.getLabel()));
DataFormatInspectorTask dataFormatInspectorTask =
new DataFormatInspectorTask(userDataItem);
CipresTaskThread taskThread = new CipresTaskThread(dataFormatInspectorTask);
taskThread.start();
taskThread.join();
logger.debug(
String.format(
"Parsed UserDataItemID=[%d] Label=[%s] values:\n%s",
userDataItem.getUserDataId(),
userDataItem.getLabel(),
StringUtils.map2String(dataFormatInspectorTask.getMetaData().parameters())));
}
}
}
else
{
logger.debug(String.format("Selected ToolID is [%s]. NOT parsing.", super.getToolId()));
}
Task task = getCurrentTask();
if (userDataItems != null && !userDataItems.isEmpty() && task != null)
{
for (UserDataItem userDataItem : userDataItems)
{
UserDataItem temp = new UserDataItem(userDataItem.getUserDataId());
if (temp != null)
{
task.toolParameters().putAll(temp.metaData());
}
}
}
logger.debug("END: parseBeastInputDataFile()::void");
}
private boolean
inputDataFileAndToolCompatible () throws Throwable
{
logger.debug("BEGIN: inputDataFileAndToolCompatible()::boolean");
// Get all UserDataItems need to be checked and parsed (if necessary).
List userDataItems = getMappedInput();
final String toolId = (super.getToolId() == null)?
"" : super.getToolId().trim();
if (userDataItems == null || userDataItems.isEmpty())
{
logger.debug("Dataset/data file not selected; NOT checking.");
}
else if (toolId.isEmpty())
{
logger.debug("Tool not selected; NOT checking.");
}
// Check the input file's DataFormat and selected tool.
else
{
final String MSG_TEMPLATE =
"You have chosen a %s file, which cannot be run with the tool you have selected (%s).";
for (UserDataItem userDataItem : userDataItems)
{
DataFormat dataFormat = (userDataItem.getDataFormat() == null)?
DataFormat.UNKNOWN : userDataItem.getDataFormat();
logger.debug(
String.format(
"Selected ToolID=[%s] data file DataFormat=[%s]",
toolId, dataFormat.toString()));
if (!dataFormat.equals(DataFormat.UNKNOWN))
{
boolean incompatible =
((toolId.equals(BEAST_TOOLID) &&
dataFormat.equals(DataFormat.BEAST2)))
||
((toolId.equals(BEAST2_TOOLID) &&
dataFormat.equals(DataFormat.BEAST)));
if (incompatible)
{
addActionError(
String.format(MSG_TEMPLATE,
dataFormat.toString(),
toolId));
return !incompatible;
}
}
}
}
logger.debug("END: inputDataFileAndToolCompatible()::boolean");
// Default to 'true'
return Boolean.TRUE;
}
private void
populateXsedeAttributeReportingRecord ( Task task ) throws IOException, SQLException
{
if (task == null)
{
throw new RuntimeException("Task cannot be null.");
}
User user = super.getWorkbenchSession().getUser();
List list = Statistics.findStatistics(
task.getTaskId(),
task.runs().last().getRunNumber());
if (list != null && !list.isEmpty())
{
for (Statistics stats : list)
{
if (ResourceConversionService.isXsedeResource(stats.getResource()))
{
XsedeAttributeReportingScheduler
.getInstance()
.schedule(user, task);
}
}
}
}
private void
printTaskSessionContent ()
{
logger.debug("==============================");
logger.debug(String.format("Has Input? [%s]", hasInput()));
logger.debug(String.format("Has InputData? [%s]", hasInputData()));
logger.debug(String.format("Has MappedInput? [%s]", hasMappedInput()));
logger.debug(String.format("Has UnmappedInput? [%s]", hasUnmappedInput()));
logger.debug(String.format("Has Tool? [%s]", hasTool()));
logger.debug(String.format("Tool [%s - %s]", getToolId(), getToolLabel()));
logger.debug(String.format("Has Parameters? [%s]", hasParameters()));
logger.debug(String.format("Params Count: [%d]", getParameterCount()));
logger.debug("==============================");
}
}