public static void main(String args[]) throws Exception {
    // cache the initial set of loggers before this test begins
    // to add any loggers
    Enumeration<String> e = logMgr.getLoggerNames();
    List<String> defaultLoggers = getDefaultLoggerNames();
    while (e.hasMoreElements()) {
      String logger = e.nextElement();
      if (!defaultLoggers.contains(logger)) {
        initialLoggerNames.add(logger);
      }
    }
    ;

    String tstSrc = System.getProperty(TST_SRC_PROP);
    File fname = new File(tstSrc, LM_PROP_FNAME);
    String prop = fname.getCanonicalPath();
    System.setProperty(CFG_FILE_PROP, prop);
    logMgr.readConfiguration();

    System.out.println();
    if (checkLoggers() == PASSED) {
      System.out.println(MSG_PASSED);
    } else {
      System.out.println(MSG_FAILED);
      throw new Exception(MSG_FAILED);
    }
  }
  /**
   * Commit the contained item to the main archive. The item is associated with the relevant
   * collection, added to the search index, and any other tasks such as assigning dates are
   * performed.
   *
   * @return the fully archived item.
   */
  @Override
  public Item archive(Context context, BasicWorkflowItem workflowItem)
      throws SQLException, IOException, AuthorizeException {
    // FIXME: Check auth
    Item item = workflowItem.getItem();
    Collection collection = workflowItem.getCollection();

    log.info(
        LogManager.getHeader(
            context,
            "archive_item",
            "workflow_item_id="
                + workflowItem.getID()
                + "item_id="
                + item.getID()
                + "collection_id="
                + collection.getID()));

    installItemService.installItem(context, workflowItem);

    // Log the event
    log.info(
        LogManager.getHeader(
            context,
            "install_item",
            "workflow_id=" + workflowItem.getID() + ", item_id=" + item.getID() + "handle=FIXME"));

    return item;
  }
  protected void notifyOfReject(
      Context context, BasicWorkflowItem workflowItem, EPerson e, String reason) {
    try {
      // Get the item title
      String title = getItemTitle(workflowItem);

      // Get the collection
      Collection coll = workflowItem.getCollection();

      // Get rejector's name
      String rejector = getEPersonName(e);
      Locale supportedLocale = I18nUtil.getEPersonLocale(e);
      Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_reject"));

      email.addRecipient(workflowItem.getSubmitter().getEmail());
      email.addArgument(title);
      email.addArgument(coll.getName());
      email.addArgument(rejector);
      email.addArgument(reason);
      email.addArgument(getMyDSpaceLink());

      email.send();
    } catch (RuntimeException re) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              context,
              "notify_of_reject",
              "cannot email user eperson_id="
                  + e.getID()
                  + " eperson_email="
                  + e.getEmail()
                  + " workflow_item_id="
                  + workflowItem.getID()
                  + ":  "
                  + re.getMessage()));

      throw re;
    } catch (Exception ex) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              context,
              "notify_of_reject",
              "cannot email user eperson_id="
                  + e.getID()
                  + " eperson_email="
                  + e.getEmail()
                  + " workflow_item_id="
                  + workflowItem.getID()
                  + ":  "
                  + ex.getMessage()));
    }
  }
Ejemplo n.º 4
0
  static void checkDataset() {
    Attribute[] outputs = Attributes.getOutputAttributes();

    if (outputs.length != 1) {
      LogManager.printErr("Only datasets with one output are supported");
      System.exit(1);
    }
    if (outputs[0].getType() != Attribute.NOMINAL) {
      LogManager.printErr("Output attribute should be nominal");
      System.exit(1);
    }
    Parameters.numClasses = outputs[0].getNumNominalValues();
    Parameters.numAttributes = Attributes.getInputAttributes().length;
  }
Ejemplo n.º 5
0
 public static void logInit(boolean force) throws IOException {
   if (!IsLogInitialized || force) {
     LogManager.getLogManager()
         .readConfiguration(
             LibRt.class.getClassLoader().getResourceAsStream("cfg.logging.properties"));
     String logFile = System.getProperty("CfgLog");
     if (logFile != null) {
       LogManager.getLogManager().readConfiguration(new FileInputStream(logFile));
     }
     try {
       LogLvlMax = Integer.parseInt(System.getProperty("LogLvlMax", LogLvlMax + ""));
     } catch (Exception ex) {
     }
     ; // XXX: mostrar mensaje?
   }
 }
  /* Check: getLoggerNames() must return correct names
   *        for registered loggers and their parents.
   * Returns boolean values: PASSED or FAILED
   */
  public static boolean checkLoggers() {
    String failMsg = "# checkLoggers: getLoggerNames() returned unexpected loggers";
    Vector<String> expectedLoggerNames = new Vector<String>(getDefaultLoggerNames());

    // Create the logger LOGGER_NAME_1
    Logger.getLogger(LOGGER_NAME_1);
    expectedLoggerNames.addElement(PARENT_NAME_1);
    expectedLoggerNames.addElement(LOGGER_NAME_1);

    // Create the logger LOGGER_NAME_2
    Logger.getLogger(LOGGER_NAME_2);
    expectedLoggerNames.addElement(PARENT_NAME_2);
    expectedLoggerNames.addElement(LOGGER_NAME_2);

    Enumeration<String> returnedLoggersEnum = logMgr.getLoggerNames();
    Vector<String> returnedLoggerNames = new Vector<String>(0);
    while (returnedLoggersEnum.hasMoreElements()) {
      String logger = returnedLoggersEnum.nextElement();
      if (!initialLoggerNames.contains(logger)) {
        // filter out the loggers that have been added before this test runs
        returnedLoggerNames.addElement(logger);
      }
    }
    ;

    return checkNames(expectedLoggerNames, returnedLoggerNames, failMsg);
  }
  /**
   * Return the workflow item to the workspace of the submitter. The workflow item is removed, and a
   * workspace item created.
   *
   * @param c Context
   * @param wfi WorkflowItem to be 'dismantled'
   * @return the workspace item
   */
  protected WorkspaceItem returnToWorkspace(Context c, BasicWorkflowItem wfi)
      throws SQLException, IOException, AuthorizeException {
    // FIXME: How should this interact with the workflow system?
    // FIXME: Remove license
    // FIXME: Provenance statement?
    // Create the new workspace item row
    WorkspaceItem workspaceItem = workspaceItemService.create(c, wfi);

    workspaceItem.setMultipleFiles(wfi.hasMultipleFiles());
    workspaceItem.setMultipleTitles(wfi.hasMultipleTitles());
    workspaceItem.setPublishedBefore(wfi.isPublishedBefore());
    workspaceItemService.update(c, workspaceItem);

    // myitem.update();
    log.info(
        LogManager.getHeader(
            c,
            "return_to_workspace",
            "workflow_item_id=" + wfi.getID() + "workspace_item_id=" + workspaceItem.getID()));

    // Now remove the workflow object manually from the database
    workflowItemService.deleteWrapper(c, wfi);

    return workspaceItem;
  }
Ejemplo n.º 8
0
  @Override
  public WorkspaceItem abort(Context c, XmlWorkflowItem wi, EPerson e)
      throws AuthorizeException, SQLException, IOException {
    if (!authorizeService.isAdmin(c)) {
      throw new AuthorizeException("You must be an admin to abort a workflow");
    }

    c.turnOffAuthorisationSystem();
    // Restore permissions for the submitter
    // convert into personal workspace
    WorkspaceItem wsi = returnToWorkspace(c, wi);

    log.info(
        LogManager.getHeader(
            c,
            "abort_workflow",
            "workflow_item_id="
                + wi.getID()
                + "item_id="
                + wsi.getItem().getID()
                + "collection_id="
                + wi.getCollection().getID()
                + "eperson_id="
                + e.getID()));

    c.restoreAuthSystemState();
    return wsi;
  }
  @Override
  public WorkspaceItem abort(Context context, BasicWorkflowItem workflowItem, EPerson e)
      throws SQLException, AuthorizeException, IOException {
    // authorize a DSpaceActions.ABORT
    if (!authorizeService.isAdmin(context)) {
      throw new AuthorizeException("You must be an admin to abort a workflow");
    }

    // stop workflow regardless of its state
    taskListItemService.deleteByWorkflowItem(context, workflowItem);

    log.info(
        LogManager.getHeader(
            context,
            "abort_workflow",
            "workflow_item_id="
                + workflowItem.getID()
                + "item_id="
                + workflowItem.getItem().getID()
                + "collection_id="
                + workflowItem.getCollection().getID()
                + "eperson_id="
                + e.getID()));

    // convert into personal workspace
    return returnToWorkspace(context, workflowItem);
  }
/**
 * Gets the score for a given position from a sgr file
 *
 * @author elee
 */
public class SgrScoreCalculator extends StoredScoreCalculator {

  // class variables
  protected static final Logger logger = LogManager.getLogger(SgrScoreCalculator.class);

  /**
   * Builds a SgrScoreCalculator object
   *
   * @param data - name of file containing sgr data
   * @param winSize - size of display window
   * @throws IOException - if the file cannot be accessed
   */
  public SgrScoreCalculator(String data, int winSize, CurationSet curation) throws IOException {
    super(winSize);
    BufferedReader br = new BufferedReader(new FileReader(data));
    String line;
    double minAbsScore = Double.POSITIVE_INFINITY;
    Set<String> unmatchedIds = new HashSet<String>();
    while ((line = br.readLine()) != null) {
      String[] tokens = line.split("\t");
      String refId = curation.getRefSequence().getName();
      if (!tokens[0].equals(refId)) {
        if (!unmatchedIds.contains(tokens[0])) {
          logger.warn(
              "Score id "
                  + tokens[0]
                  + " does not match main sequence id "
                  + refId
                  + ". Skipping score.");
          unmatchedIds.add(tokens[0]);
        }
        continue;
      }
      Double score = new Double(Double.parseDouble(tokens[2]));
      // chuck out scores outside of the given range
      int pos = Integer.parseInt(tokens[1]);
      if (pos >= curation.getLow() && pos <= curation.getHigh()) {
        scoreMap.put(pos, score);
      }

      if (Math.abs(score) < minAbsScore) {
        minAbsScore = Math.abs(score);
      }
      if (score.doubleValue() < minScore) {
        minScore = score;
      }
      if (score.doubleValue() > maxScore) {
        maxScore = score;
      }
    }
    while (minAbsScore * factor < 1) {
      factor *= 10;
    }
  }
}
Ejemplo n.º 11
0
  /** @param args the command line arguments */
  public static void main(String[] args) {
    ParserParameters.doParse(args[0]);
    LogManager.initLogManager();

    InstanceSet is = new InstanceSet();
    try {
      is.readSet(Parameters.trainInputFile, true);
    } catch (Exception e) {
      LogManager.printErr(e.toString());
      System.exit(1);
    }
    checkDataset();

    Discretizer dis;
    String name = Parameters.algorithmName;
    dis = new FayyadDiscretizer();
    dis.buildCutPoints(is);
    dis.applyDiscretization(Parameters.trainInputFile, Parameters.trainOutputFile);
    dis.applyDiscretization(Parameters.testInputFile, Parameters.testOutputFile);
    LogManager.closeLog();
  }
Ejemplo n.º 12
0
  /**
   * Commit the contained item to the main archive. The item is associated with the relevant
   * collection, added to the search index, and any other tasks such as assigning dates are
   * performed.
   *
   * @param context The relevant DSpace Context.
   * @param wfi workflow item
   * @return the fully archived item.
   * @throws IOException A general class of exceptions produced by failed or interrupted I/O
   *     operations.
   * @throws SQLException An exception that provides information on a database access error or other
   *     errors.
   * @throws AuthorizeException Exception indicating the current user of the context does not have
   *     permission to perform a particular action.
   */
  @Override
  public Item archive(Context context, XmlWorkflowItem wfi)
      throws SQLException, IOException, AuthorizeException {
    // FIXME: Check auth
    Item item = wfi.getItem();
    Collection collection = wfi.getCollection();

    // Remove (if any) the workflowItemroles for this item
    workflowItemRoleService.deleteForWorkflowItem(context, wfi);

    log.info(
        LogManager.getHeader(
            context,
            "archive_item",
            "workflow_item_id="
                + wfi.getID()
                + "item_id="
                + item.getID()
                + "collection_id="
                + collection.getID()));

    installItemService.installItem(context, wfi);

    // Notify
    notifyOfArchive(context, item, collection);

    // Clear any remaining workflow metadata
    itemService.clearMetadata(
        context, item, WorkflowRequirementsService.WORKFLOW_SCHEMA, Item.ANY, Item.ANY, Item.ANY);
    itemService.update(context, item);

    // Log the event
    log.info(
        LogManager.getHeader(
            context,
            "install_item",
            "workflow_item_id=" + wfi.getID() + ", item_id=" + item.getID() + "handle=FIXME"));

    return item;
  }
  @Override
  public void claim(Context context, BasicWorkflowItem workflowItem, EPerson e)
      throws SQLException, IOException, AuthorizeException {
    int taskstate = workflowItem.getState();

    switch (taskstate) {
      case WFSTATE_STEP1POOL:

        // authorize DSpaceActions.SUBMIT_REVIEW
        doState(context, workflowItem, WFSTATE_STEP1, e);

        break;

      case WFSTATE_STEP2POOL:

        // authorize DSpaceActions.SUBMIT_STEP2
        doState(context, workflowItem, WFSTATE_STEP2, e);

        break;

      case WFSTATE_STEP3POOL:

        // authorize DSpaceActions.SUBMIT_STEP3
        doState(context, workflowItem, WFSTATE_STEP3, e);

        break;

        // if we got here, we weren't pooled... error?
        // FIXME - log the error?
    }

    log.info(
        LogManager.getHeader(
            context,
            "claim_task",
            "workflow_item_id="
                + workflowItem.getID()
                + "item_id="
                + workflowItem.getItem().getID()
                + "collection_id="
                + workflowItem.getCollection().getID()
                + "newowner_id="
                + workflowItem.getOwner().getID()
                + "old_state="
                + taskstate
                + "new_state="
                + workflowItem.getState()));
  }
  @Override
  public void unclaim(Context context, BasicWorkflowItem workflowItem, EPerson e)
      throws SQLException, IOException, AuthorizeException {
    int taskstate = workflowItem.getState();

    switch (taskstate) {
      case WFSTATE_STEP1:

        // authorize DSpaceActions.STEP1
        doState(context, workflowItem, WFSTATE_STEP1POOL, e);

        break;

      case WFSTATE_STEP2:

        // authorize DSpaceActions.APPROVE
        doState(context, workflowItem, WFSTATE_STEP2POOL, e);

        break;

      case WFSTATE_STEP3:

        // authorize DSpaceActions.STEP3
        doState(context, workflowItem, WFSTATE_STEP3POOL, e);

        break;

        // error handling? shouldn't get here
        // FIXME - what to do with error - log it?
    }

    log.info(
        LogManager.getHeader(
            context,
            "unclaim_workflow",
            "workflow_item_id="
                + workflowItem.getID()
                + ",item_id="
                + workflowItem.getItem().getID()
                + ",collection_id="
                + workflowItem.getCollection().getID()
                + ",old_state="
                + taskstate
                + ",new_state="
                + workflowItem.getState()));
  }
  // send notices of curation activity
  @Override
  public void notifyOfCuration(
      Context c,
      BasicWorkflowItem wi,
      List<EPerson> ePeople,
      String taskName,
      String action,
      String message)
      throws SQLException, IOException {
    try {
      // Get the item title
      String title = getItemTitle(wi);

      // Get the submitter's name
      String submitter = getSubmitterName(wi);

      // Get the collection
      Collection coll = wi.getCollection();

      for (EPerson epa : ePeople) {
        Locale supportedLocale = I18nUtil.getEPersonLocale(epa);
        Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "flowtask_notify"));
        email.addArgument(title);
        email.addArgument(coll.getName());
        email.addArgument(submitter);
        email.addArgument(taskName);
        email.addArgument(message);
        email.addArgument(action);
        email.addRecipient(epa.getEmail());
        email.send();
      }
    } catch (MessagingException e) {
      log.warn(
          LogManager.getHeader(
              c,
              "notifyOfCuration",
              "cannot email users of workflow_item_id " + wi.getID() + ":  " + e.getMessage()));
    }
  }
Ejemplo n.º 16
0
  protected void activateFirstStep(
      Context context, Workflow wf, Step firstStep, XmlWorkflowItem wfi)
      throws AuthorizeException, IOException, SQLException, WorkflowException,
          WorkflowConfigurationException {
    WorkflowActionConfig firstActionConfig = firstStep.getUserSelectionMethod();
    firstActionConfig.getProcessingAction().activate(context, wfi);
    log.info(
        LogManager.getHeader(
            context,
            "start_workflow",
            firstActionConfig.getProcessingAction()
                + " workflow_item_id="
                + wfi.getID()
                + "item_id="
                + wfi.getItem().getID()
                + "collection_id="
                + wfi.getCollection().getID()));

    // record the start of the workflow w/provenance message
    recordStart(context, wfi.getItem(), firstActionConfig.getProcessingAction());

    // Fire an event !
    logWorkflowEvent(
        context,
        firstStep.getWorkflow().getID(),
        null,
        null,
        wfi,
        null,
        firstStep,
        firstActionConfig);

    // If we don't have a UI activate it
    if (!firstActionConfig.requiresUI()) {
      ActionResult outcome =
          firstActionConfig.getProcessingAction().execute(context, wfi, firstStep, null);
      processOutcome(context, null, wf, firstStep, firstActionConfig, outcome, wfi, true);
    }
  }
Ejemplo n.º 17
0
  private void initLogger() {
    ConsoleHandler consoleHandler = null;

    Logger rootLogger = LogManager.getLogManager().getLogger("");
    Handler[] handlers = rootLogger.getHandlers();
    for (Handler handler : handlers) {
      if (handler instanceof ConsoleHandler) {
        consoleHandler = (ConsoleHandler) handler;
        rootLogger.removeHandler(handler);
      }
    }

    logger = Logger.getLogger(contextId);
    logger.setLevel(logLevel);
    if (!logLevel.equals(Level.OFF)) {
      LogFormatter formatter = new LogFormatter();
      if (consoleLog) {
        if (consoleHandler == null) {
          consoleHandler = new ConsoleHandler();
        }
        consoleHandler.setFormatter(formatter);
        consoleHandler.setLevel(logLevel);
        logger.addHandler(consoleHandler);
      }
      String userHomePath = getProperty("user.home", ".");
      File logDir = new File(userHomePath, '.' + contextId + "/log");
      logDir.mkdirs();
      String logFilePattern = new File(logDir, contextId + "-%g.log").getPath();
      try {
        FileHandler fileHandler = new FileHandler(logFilePattern);
        fileHandler.setFormatter(formatter);
        fileHandler.setLevel(logLevel);
        logger.addHandler(fileHandler);
      } catch (IOException e) {
        System.err.println("Error: Failed to create log file: " + logFilePattern);
      }
    }
  }
Ejemplo n.º 18
0
  /**
   * Return the workflow item to the workspace of the submitter. The workflow item is removed, and a
   * workspace item created.
   *
   * @param c Context
   * @param wfi WorkflowItem to be 'dismantled'
   * @return the workspace item
   * @throws java.io.IOException ...
   * @throws java.sql.SQLException ...
   * @throws org.dspace.authorize.AuthorizeException ...
   */
  protected WorkspaceItem returnToWorkspace(Context c, XmlWorkflowItem wfi)
      throws SQLException, IOException, AuthorizeException {
    // authorize a DSpaceActions.REJECT
    // stop workflow
    deleteAllTasks(c, wfi);

    c.turnOffAuthorisationSystem();
    // Also clear all info for this step
    workflowRequirementsService.clearInProgressUsers(c, wfi);

    // Remove (if any) the workflowItemroles for this item
    workflowItemRoleService.deleteForWorkflowItem(c, wfi);

    Item myitem = wfi.getItem();
    // Restore permissions for the submitter
    grantUserAllItemPolicies(c, myitem, myitem.getSubmitter());

    // FIXME: How should this interact with the workflow system?
    // FIXME: Remove license
    // FIXME: Provenance statement?
    // Create the new workspace item row
    WorkspaceItem workspaceItem = workspaceItemService.create(c, wfi);
    workspaceItem.setMultipleFiles(wfi.hasMultipleFiles());
    workspaceItem.setMultipleTitles(wfi.hasMultipleTitles());
    workspaceItem.setPublishedBefore(wfi.isPublishedBefore());
    workspaceItemService.update(c, workspaceItem);

    // myitem.update();
    log.info(
        LogManager.getHeader(
            c,
            "return_to_workspace",
            "workflow_item_id=" + wfi.getID() + "workspace_item_id=" + workspaceItem.getID()));

    // Now remove the workflow object manually from the database
    xmlWorkflowItemService.deleteWrapper(c, wfi);
    return workspaceItem;
  }
  @Override
  public BasicWorkflowItem start(Context context, WorkspaceItem wsi)
      throws SQLException, AuthorizeException, IOException {
    // FIXME Check auth
    Item myitem = wsi.getItem();
    Collection collection = wsi.getCollection();

    log.info(
        LogManager.getHeader(
            context,
            "start_workflow",
            "workspace_item_id="
                + wsi.getID()
                + "item_id="
                + myitem.getID()
                + "collection_id="
                + collection.getID()));

    // record the start of the workflow w/provenance message
    recordStart(context, myitem);

    // create the WorkflowItem
    BasicWorkflowItem wfi = workflowItemService.create(context, myitem, collection);
    wfi.setMultipleFiles(wsi.hasMultipleFiles());
    wfi.setMultipleTitles(wsi.hasMultipleTitles());
    wfi.setPublishedBefore(wsi.isPublishedBefore());

    // remove the WorkspaceItem
    workspaceItemService.deleteWrapper(context, wsi);

    // now get the workflow started
    wfi.setState(WFSTATE_SUBMIT);
    advance(context, wfi, null);

    // Return the workflow item
    return wfi;
  }
Ejemplo n.º 20
0
  /**
   * notify the submitter that the item is archived
   *
   * @param context The relevant DSpace Context.
   * @param item which item was archived
   * @param coll collection name to display in template
   * @throws SQLException An exception that provides information on a database access error or other
   *     errors.
   * @throws IOException A general class of exceptions produced by failed or interrupted I/O
   *     operations.
   */
  protected void notifyOfArchive(Context context, Item item, Collection coll)
      throws SQLException, IOException {
    try {
      // Get submitter
      EPerson ep = item.getSubmitter();
      // Get the Locale
      Locale supportedLocale = I18nUtil.getEPersonLocale(ep);
      Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive"));

      // Get the item handle to email to user
      String handle = handleService.findHandle(context, item);

      // Get title
      List<MetadataValue> titles =
          itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "title", null, Item.ANY);
      String title = "";
      try {
        title = I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled");
      } catch (MissingResourceException e) {
        title = "Untitled";
      }
      if (titles.size() > 0) {
        title = titles.iterator().next().getValue();
      }

      email.addRecipient(ep.getEmail());
      email.addArgument(title);
      email.addArgument(coll.getName());
      email.addArgument(handleService.getCanonicalForm(handle));

      email.send();
    } catch (MessagingException e) {
      log.warn(
          LogManager.getHeader(
              context, "notifyOfArchive", "cannot email user" + " item_id=" + item.getID()));
    }
  }
  /** notify the submitter that the item is archived */
  protected void notifyOfArchive(Context context, Item item, Collection coll)
      throws SQLException, IOException {
    try {
      // Get submitter
      EPerson ep = item.getSubmitter();
      // Get the Locale
      Locale supportedLocale = I18nUtil.getEPersonLocale(ep);
      Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive"));

      // Get the item handle to email to user
      String handle = handleService.findHandle(context, item);

      // Get title
      String title = item.getName();
      if (StringUtils.isBlank(title)) {
        try {
          title = I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled");
        } catch (MissingResourceException e) {
          title = "Untitled";
        }
      }

      email.addRecipient(ep.getEmail());
      email.addArgument(title);
      email.addArgument(coll.getName());
      email.addArgument(handleService.getCanonicalForm(handle));

      email.send();
    } catch (MessagingException e) {
      log.warn(
          LogManager.getHeader(
              context,
              "notifyOfArchive",
              "cannot email user; item_id=" + item.getID() + ":  " + e.getMessage()));
    }
  }
Ejemplo n.º 22
0
 /*
  * Executes an action and returns the next.
  */
 @Override
 public WorkflowActionConfig doState(
     Context c,
     EPerson user,
     HttpServletRequest request,
     int workflowItemId,
     Workflow workflow,
     WorkflowActionConfig currentActionConfig)
     throws SQLException, AuthorizeException, IOException, MessagingException, WorkflowException {
   try {
     XmlWorkflowItem wi = xmlWorkflowItemService.find(c, workflowItemId);
     Step currentStep = currentActionConfig.getStep();
     if (currentActionConfig.getProcessingAction().isAuthorized(c, request, wi)) {
       ActionResult outcome =
           currentActionConfig.getProcessingAction().execute(c, wi, currentStep, request);
       return processOutcome(
           c, user, workflow, currentStep, currentActionConfig, outcome, wi, false);
     } else {
       throw new AuthorizeException("You are not allowed to to perform this task.");
     }
   } catch (WorkflowConfigurationException e) {
     log.error(
         LogManager.getHeader(
             c,
             "error while executing state",
             "workflow:  "
                 + workflow.getID()
                 + " action: "
                 + currentActionConfig.getId()
                 + " workflowItemId: "
                 + workflowItemId),
         e);
     WorkflowUtils.sendAlert(request, e);
     throw new WorkflowException(e);
   }
 }
Ejemplo n.º 23
0
  protected void notifyOfReject(Context c, XmlWorkflowItem wi, EPerson e, String reason) {
    try {
      // Get the item title
      String title = wi.getItem().getName();

      // Get the collection
      Collection coll = wi.getCollection();

      // Get rejector's name
      String rejector = getEPersonName(e);
      Locale supportedLocale = I18nUtil.getEPersonLocale(e);
      Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_reject"));

      email.addRecipient(wi.getSubmitter().getEmail());
      email.addArgument(title);
      email.addArgument(coll.getName());
      email.addArgument(rejector);
      email.addArgument(reason);
      email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/mydspace");

      email.send();
    } catch (Exception ex) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              c,
              "notify_of_reject",
              "cannot email user"
                  + " eperson_id"
                  + e.getID()
                  + " eperson_email"
                  + e.getEmail()
                  + " workflow_item_id"
                  + wi.getID()));
    }
  }
/**
 * FXML Controller class
 *
 * @author Mostafa
 */
public class LocalDeleteObjectInstanceServiceController implements Initializable {

  // Logger
  private static final Logger logger = LogManager.getLogger();

  @FXML private TextField ObjectInstanceDesignator;
  @FXML private Button OkButton;

  /** Initializes the controller class. */
  @Override
  public void initialize(URL url, ResourceBundle rb) {
    logger.entry();
    OkButton.disableProperty().bind(ObjectInstanceDesignator.textProperty().isEmpty());
    logger.exit();
  }

  @FXML
  private void Cancel_click(ActionEvent event) {
    logger.entry();
    ((Stage) OkButton.getScene().getWindow()).close();
    logger.exit();
  }

  @FXML
  private void Ok_click(ActionEvent event) {
    logger.entry();
    LogEntry log = new LogEntry("6.16", "Local Delete Object Instance service");
    try {
      ObjectInstanceHandle instanceHandle =
          rtiAmb
              .getObjectInstanceHandleFactory()
              .decode(
                  ByteBuffer.allocate(4)
                      .putInt(Integer.parseInt(ObjectInstanceDesignator.getText()))
                      .array(),
                  0);
      log.getSuppliedArguments()
          .add(
              new ClassValuePair(
                  "Object instance designator",
                  ObjectInstanceHandle.class,
                  instanceHandle.toString()));
      rtiAmb.localDeleteObjectInstance(instanceHandle);
      log.setDescription("Local Object instance deleted successfully");
      log.setLogType(LogEntryType.REQUEST);
    } catch (FederateNotExecutionMember
        | NotConnected
        | NumberFormatException
        | CouldNotDecode
        | RTIinternalError
        | OwnershipAcquisitionPending
        | FederateOwnsAttributes
        | ObjectInstanceNotKnown
        | SaveInProgress
        | RestoreInProgress ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.ERROR);
      logger.log(Level.ERROR, ex.getMessage(), ex);
    } catch (Exception ex) {
      log.setException(ex);
      log.setLogType(LogEntryType.FATAL);
      logger.log(Level.FATAL, ex.getMessage(), ex);
    }
    logEntries.add(log);
    ((Stage) OkButton.getScene().getWindow()).close();
    logger.exit();
  }
}
Ejemplo n.º 25
0
 /**
  * The instance is stored in a place directly accessible through the Java SE API, so that it can
  * be recovered from any class loader.
  */
 protected MockingBridge(Class<? extends MockingBridge> subclass) {
   super("mockit." + subclass.hashCode(), null);
   LogManager.getLogManager().addLogger(this);
 }
  protected void notifyGroupOfTask(
      Context c, BasicWorkflowItem wi, Group mygroup, List<EPerson> epa)
      throws SQLException, IOException {
    // check to see if notification is turned off
    // and only do it once - delete key after notification has
    // been suppressed for the first time
    UUID myID = wi.getItem().getID();

    if (noEMail.containsKey(myID)) {
      // suppress email, and delete key
      noEMail.remove(myID);
    } else {
      try {
        // Get the item title
        String title = getItemTitle(wi);

        // Get the submitter's name
        String submitter = getSubmitterName(wi);

        // Get the collection
        Collection coll = wi.getCollection();

        String message = "";

        for (EPerson anEpa : epa) {
          Locale supportedLocale = I18nUtil.getEPersonLocale(anEpa);
          Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_task"));
          email.addArgument(title);
          email.addArgument(coll.getName());
          email.addArgument(submitter);

          ResourceBundle messages = ResourceBundle.getBundle("Messages", supportedLocale);
          switch (wi.getState()) {
            case WFSTATE_STEP1POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step1");

              break;

            case WFSTATE_STEP2POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step2");

              break;

            case WFSTATE_STEP3POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step3");

              break;
          }
          email.addArgument(message);
          email.addArgument(getMyDSpaceLink());
          email.addRecipient(anEpa.getEmail());
          email.send();
        }
      } catch (MessagingException e) {
        String gid = (mygroup != null) ? String.valueOf(mygroup.getID()) : "none";
        log.warn(
            LogManager.getHeader(
                c,
                "notifyGroupofTask",
                "cannot email user group_id="
                    + gid
                    + " workflow_item_id="
                    + wi.getID()
                    + ":  "
                    + e.getMessage()));
      }
    }
  }
  @Override
  public WorkspaceItem sendWorkflowItemBackSubmission(
      Context context,
      BasicWorkflowItem workflowItem,
      EPerson ePerson,
      String provenancePrefix,
      String rejection_message)
      throws SQLException, AuthorizeException, IOException {

    int oldState = workflowItem.getState();
    // authorize a DSpaceActions.REJECT
    // stop workflow
    taskListItemService.deleteByWorkflowItem(context, workflowItem);

    // rejection provenance
    Item myitem = workflowItem.getItem();

    // Get current date
    String now = DCDate.getCurrent().toString();

    // Get user's name + email address
    String usersName = getEPersonName(ePerson);

    // Here's what happened
    String provDescription =
        "Rejected by " + usersName + ", reason: " + rejection_message + " on " + now + " (GMT) ";

    // Add to item as a DC field
    itemService.addMetadata(
        context,
        myitem,
        MetadataSchema.DC_SCHEMA,
        "description",
        "provenance",
        "en",
        provDescription);
    itemService.update(context, myitem);

    // convert into personal workspace
    WorkspaceItem wsi = returnToWorkspace(context, workflowItem);

    // notify that it's been rejected
    notifyOfReject(context, workflowItem, ePerson, rejection_message);

    log.info(
        LogManager.getHeader(
            context,
            "reject_workflow",
            "workflow_item_id="
                + workflowItem.getID()
                + "item_id="
                + workflowItem.getItem().getID()
                + "collection_id="
                + workflowItem.getCollection().getID()
                + "eperson_id="
                + ePerson.getID()));

    logWorkflowEvent(
        context,
        wsi.getItem(),
        workflowItem,
        ePerson,
        WFSTATE_SUBMIT,
        null,
        wsi.getCollection(),
        oldState,
        null);

    return wsi;
  }
  @Override
  public boolean advance(
      Context context, BasicWorkflowItem workflowItem, EPerson e, boolean curate, boolean record)
      throws SQLException, IOException, AuthorizeException {
    int taskstate = workflowItem.getState();
    boolean archived = false;

    // perform curation tasks if needed
    if (curate && workflowCuratorService.needsCuration(workflowItem)) {
      if (!workflowCuratorService.doCuration(context, workflowItem)) {
        // don't proceed - either curation tasks queued, or item rejected
        log.info(
            LogManager.getHeader(
                context,
                "advance_workflow",
                "workflow_item_id="
                    + workflowItem.getID()
                    + ",item_id="
                    + workflowItem.getItem().getID()
                    + ",collection_id="
                    + workflowItem.getCollection().getID()
                    + ",old_state="
                    + taskstate
                    + ",doCuration=false"));
        return false;
      }
    }

    switch (taskstate) {
      case WFSTATE_SUBMIT:
        archived = doState(context, workflowItem, WFSTATE_STEP1POOL, e);

        break;

      case WFSTATE_STEP1:

        // authorize DSpaceActions.SUBMIT_REVIEW
        // Record provenance
        if (record) {
          recordApproval(context, workflowItem, e);
        }
        archived = doState(context, workflowItem, WFSTATE_STEP2POOL, e);

        break;

      case WFSTATE_STEP2:

        // authorize DSpaceActions.SUBMIT_STEP2
        // Record provenance
        if (record) {
          recordApproval(context, workflowItem, e);
        }
        archived = doState(context, workflowItem, WFSTATE_STEP3POOL, e);

        break;

      case WFSTATE_STEP3:

        // authorize DSpaceActions.SUBMIT_STEP3
        // We don't record approval for editors, since they can't reject,
        // and thus didn't actually make a decision
        archived = doState(context, workflowItem, WFSTATE_ARCHIVE, e);

        break;

        // error handling? shouldn't get here
    }

    log.info(
        LogManager.getHeader(
            context,
            "advance_workflow",
            "workflow_item_id="
                + workflowItem.getID()
                + ",item_id="
                + workflowItem.getItem().getID()
                + ",collection_id="
                + workflowItem.getCollection().getID()
                + ",old_state="
                + taskstate
                + ",new_state="
                + workflowItem.getState()));
    return archived;
  }
Ejemplo n.º 29
0
    /**
     * Return the global LogManager object.
     */
    public static LogManager getLogManager() {
        if (manager != null) {
            manager.readPrimordialConfiguration();
        }
	return manager;
    }
/**
 * FXML Controller class
 *
 * @author Mostafa Ali <*****@*****.**>
 */
public class InteractionsListController extends VBox {

  // Logger
  private static final Logger logger = LogManager.getLogger();

  @FXML private TableView<InteractionState> InteractionTableView;
  @FXML private TableColumn<InteractionState, String> InteractionTableColumn;
  @FXML private TableColumn CheckTableColumn;

  CheckBox cb = new CheckBox();
  ObservableList<InteractionState> interactions = FXCollections.observableArrayList();

  public InteractionsListController() {
    logger.entry();
    FXMLLoader fxmlLoader =
        new FXMLLoader(getClass().getResource("/fxml/customcontrol/InteractionsList.fxml"));
    fxmlLoader.setController(this);
    fxmlLoader.setRoot(this);
    try {
      fxmlLoader.load();

    } catch (IOException ex) {
      logger.log(Level.FATAL, ex.getMessage(), ex);
    }
    logger.exit();
  }

  public void setFddObjectModel(FddObjectModel fddObjectModel) {
    logger.entry();
    if (fddObjectModel != null) {
      fddObjectModel
          .getInteractionClasses()
          .values()
          .stream()
          .forEach(
              (value) -> {
                interactions.add(new InteractionState(value));
              });
      InteractionTableView.setItems(interactions);
      interactions.forEach(
          (interaction) -> {
            interaction
                .onProperty()
                .addListener(
                    (observable, oldValue, newValue) -> {
                      if (!newValue) {
                        cb.setSelected(false);
                      } else if (interactions.stream().allMatch(a -> a.isOn())) {
                        cb.setSelected(true);
                      }
                    });
          });
      InteractionTableColumn.setCellValueFactory(new PropertyValueFactory<>("interactionName"));
      CheckTableColumn.setCellValueFactory(
          new Callback<
              TableColumn.CellDataFeatures<InteractionState, Boolean>, ObservableValue<Boolean>>() {
            @Override
            public ObservableValue<Boolean> call(
                TableColumn.CellDataFeatures<InteractionState, Boolean> param) {
              return param.getValue().onProperty();
            }
          });

      CheckTableColumn.setCellFactory(CheckBoxTableCell.forTableColumn(CheckTableColumn));
      cb.setUserData(CheckTableColumn);
      cb.setOnAction(
          (ActionEvent event) -> {
            CheckBox cb1 = (CheckBox) event.getSource();
            TableColumn tc = (TableColumn) cb1.getUserData();
            InteractionTableView.getItems()
                .stream()
                .forEach(
                    (item) -> {
                      item.setOn(cb1.isSelected());
                    });
          });
      CheckTableColumn.setGraphic(cb);
    }
    logger.exit();
  }

  public List<InteractionClassFDD> getInteractions() {
    return interactions
        .stream()
        .filter(a -> a.isOn())
        .map(a -> a.interaction)
        .collect(Collectors.toList());
  }

  public static class InteractionState {

    private final ReadOnlyStringWrapper interactionName = new ReadOnlyStringWrapper();
    private final BooleanProperty on = new SimpleBooleanProperty();
    private final InteractionClassFDD interaction;

    public InteractionState(InteractionClassFDD interaction) {
      this.interaction = interaction;
      interactionName.set(interaction.getFullName());
    }

    public String getInteractionName() {
      return interactionName.get();
    }

    public ReadOnlyStringProperty interactionNameProperty() {
      return interactionName.getReadOnlyProperty();
    }

    public boolean isOn() {
      return on.get();
    }

    public void setOn(boolean value) {
      on.set(value);
    }

    public BooleanProperty onProperty() {
      return on;
    }

    @Override
    public String toString() {
      return interaction.getFullName();
    }
  }
}