Exemple #1
0
 @Override
 public ActionResult process(Map<String, String> context) {
   ActionResult result = new ActionResult();
   switchEngine.reload();
   result.setSuccess(true);
   return result;
 }
    public ActionResult execute(User user, String[] args) {
      ActionResult res = new ActionResult();
      if (!user.isAdmin()) {
        res.setMess(new String[] {prefix + ErrorMessages.E101.Mess(null, null)});
        return res;
      }

      if (args[0].equals("")) {
        res.setMess(new String[] {prefix + ErrorMessages.E103.Mess(null, null)});
        return res;
      }

      String theUser = match(user.getMisc(), args[0]);

      if (!DCoProperties.getDS().AccountExists(AccountType.BANK, theUser)) {
        res.setMess(new String[] {prefix + ErrorMessages.E104.Mess(theUser, "Bank")});
        return res;
      }

      DCoProperties.getDS().setBalance(AccountType.BANK, theUser, 0);

      res.setMess(new String[] {prefix + AdminMessages.A301.Mess(theUser, "Account", 0)});
      log(LoggingMessages.L622.Mess(user.getName(), theUser, 0, null));
      return res;
    }
  public void testDeleteCopiesForUnknownIsbnDoesNothing() throws Exception {
    int mediaCount = mockInMemoryMediaGateway.copyCount();
    request.setParameter("delete_100", "on");
    assertEquals(mediaCount, mockInMemoryMediaGateway.copyCount());
    ActionResult result = booksController.handle(request);

    assertEquals("", result.getInfoMessage());
    assertEquals("", result.getWarningMessage());
    assertEquals("", result.getErrorMessage());
  }
 protected final void onPostExecute(ActionResult<Result> result) {
   if (mCancelled) {
     Log.i(tag, "Action has been cancelled: " + mServiceId);
     return;
   }
   if (mUICallback != null) {
     if (result.hasError()) {
       mUICallback.onFailure(result.getError());
     } else {
       mUICallback.onSuccess(result.getObject());
     }
   }
 }
    public ActionResult execute(User user, String[] args) {
      ActionResult res = new ActionResult();

      if (!user.canRank()) {
        res.setMess(new String[] {prefix + ErrorMessages.E101.Mess(null, null)});
        return res;
      }

      int rank = 1, amount = 20;

      Map<String, Double> sorted = DCoProperties.getDS().getRankMap(AccountType.BANK);

      if (sorted.size() < 1) {
        res.setMess(new String[] {AccountMessages.A223.Mess(null, "Bank", 0, 0)});
        return res;
      }

      if (!args[0].equals("")) {
        try {
          amount = Integer.parseInt(args[0]);
        } catch (NumberFormatException nfe) {
          amount = 20;
        }
      }

      if (amount > sorted.size()) {
        amount = sorted.size();
      }

      String[] ranking = new String[amount + 1];
      ranking[0] = AccountMessages.A223.Mess(null, "Bank", 0, amount);

      for (String name : sorted.keySet()) {
        double balance = sorted.get(name);

        if (rank <= amount) {
          ranking[rank] = AccountMessages.A224.Mess(null, name, balance, rank);
        } else {
          break;
        }
        rank++;
      }

      log(LoggingMessages.L614.Mess(user.getName(), null, amount, null));

      res.setMess(ranking);
      return res;
    }
    public ActionResult execute(User user, String[] args) {
      int rank = -1;
      ActionResult res = new ActionResult();
      if (!user.canRank()) {
        res.setMess(new String[] {prefix + ErrorMessages.E101.Mess(null, null)});
        return res;
      }

      boolean self = true;

      String theUser = match(user.getMisc(), args[0]);
      if (!args[0].equals("")) {
        if (!DCoProperties.getDS().AccountExists(AccountType.BANK, theUser)) {
          res.setMess(new String[] {prefix + ErrorMessages.E104.Mess(theUser, "Bank")});
          return res;
        }
        self = false;
      }

      String ranked = null;
      Map<String, Double> sorted = DCoProperties.getDS().getRankMap(AccountType.BANK);
      if (sorted != null) {
        for (String name : sorted.keySet()) {
          if (self) {
            if (name.equalsIgnoreCase(user.getName())) {
              ranked = AccountMessages.A222.Mess(null, null, 0, rank);
              log(LoggingMessages.L639.Mess(user.getName(), null, 0, null));
              break;
            }
          } else {
            if (name.equalsIgnoreCase(theUser)) {
              ranked = AccountMessages.A221.Mess(theUser, null, 0, rank);
              log(LoggingMessages.L638.Mess(user.getName(), theUser, 0, null));
              break;
            }
          }
          rank++;
        }
      }

      res.setMess(
          new String[] {ranked != null ? prefix + ranked : prefix + "Unable to retrieve rank..."});
      return res;
    }
  public void testDeleteThreeCopiesForValidIsbn() throws Exception {
    assertISBNKnownWithEntries("3", 3);
    assertEquals(6, mockInMemoryMediaGateway.copyCount());
    List copies = mockInMemoryMediaGateway.findAllCopies("3");
    for (Iterator iter = copies.iterator(); iter.hasNext(); ) {
      MediaCopy copy = (MediaCopy) iter.next();
      String id = copy.getId();
      request.setParameter("delete_" + id, "on");
    }

    ActionResult result = booksController.handle(request);
    assertTrue(mockInMemoryMediaGateway.contains("3"));
    assertISBNKnownWithEntries("3", 0);
    assertEquals(3, mockInMemoryMediaGateway.copyCount());

    assertTrue(result.getInfoMessage().length() > 0);
    assertEquals("", result.getWarningMessage());
    assertEquals("", result.getErrorMessage());
  }
 public ActionResult execute(User user, String[] args) {
   ActionResult res = new ActionResult();
   res.setMess(
       new String[] {
         HelpMessages.H402.Mess(),
         HelpMessages.H404.Mess(),
         HelpMessages.H405.Mess(),
         HelpMessages.H410.Mess(),
         HelpMessages.H417.Mess(),
         HelpMessages.H418.Mess(),
         (user.canRank() ? HelpMessages.H412.Mess() : null),
         (user.canRank() ? HelpMessages.H413.Mess() : null),
         (user.isAdmin() ? HelpMessages.H431.Mess() : null),
         (user.isAdmin() ? HelpMessages.H432.Mess() : null),
         (user.isAdmin() ? HelpMessages.H433.Mess() : null),
         (user.isAdmin() ? HelpMessages.H434.Mess() : null),
         (user.useMoney() ? HelpMessages.H406.Mess() : null),
         (user.useJoint() ? HelpMessages.H408.Mess() : null)
       });
   return res;
 }
    public ActionResult execute(User user, String[] args) {
      ActionResult res = new ActionResult();
      if (!args[0].equals("") && !DCoProperties.getAOC()) {
        String theUser = match(user.getMisc(), args[0]);

        if (theUser != null) {
          if (!DCoProperties.getDS().AccountExists(AccountType.BANK, theUser)) {
            res.setMess(new String[] {prefix + ErrorMessages.E104.Mess(theUser, "Bank")});
            return res;
          }
        }

        res.setMess(
            new String[] {
              prefix
                  + AccountMessages.A203.Mess(
                      theUser,
                      "Bank",
                      DCoProperties.getDS().getBalance(AccountType.BANK, theUser),
                      -1)
            });
        return res;
      } else {
        if (!DCoProperties.getDS().AccountExists(AccountType.BANK, user.getName())) {
          DCoProperties.getDS().setInitialBalance(AccountType.BANK, user.getName());
        }
        res.setMess(
            new String[] {
              prefix
                  + AccountMessages.A201.Mess(
                      null,
                      "Bank",
                      DCoProperties.getDS().getBalance(AccountType.BANK, user.getName()),
                      -1)
            });
        return res;
      }
    }
  protected WorkflowActionConfig processNextStep(
      Context c,
      EPerson user,
      Workflow workflow,
      ActionResult currentOutcome,
      XmlWorkflowItem wfi,
      Step nextStep)
      throws SQLException, IOException, AuthorizeException, WorkflowException,
          WorkflowConfigurationException {
    WorkflowActionConfig nextActionConfig;
    if (nextStep != null) {
      nextActionConfig = nextStep.getUserSelectionMethod();
      nextActionConfig.getProcessingAction().activate(c, wfi);
      //                nextActionConfig.getProcessingAction().generateTasks();

      if (nextActionConfig.requiresUI()) {
        // Since a new step has been started, stop executing actions once one with a user interface
        // is present.
        c.restoreAuthSystemState();
        return nextActionConfig;
      } else {
        ActionResult newOutcome =
            nextActionConfig.getProcessingAction().execute(c, wfi, nextStep, null);
        c.restoreAuthSystemState();
        return processOutcome(c, user, workflow, nextStep, nextActionConfig, newOutcome, wfi, true);
      }
    } else {
      if (currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE) {
        c.restoreAuthSystemState();
        throw new WorkflowException(
            "No alternate step was found for outcome: " + currentOutcome.getResult());
      }
      archive(c, wfi);
      c.restoreAuthSystemState();
      return null;
    }
  }
  public static void processAction(
      HttpServletRequest request, HttpServletResponse response, Portlet portlet)
      throws PortletContainerException {

    PortletContainer portletContainer = getPortletContainer();

    ActionResult actionResult = portletContainer.processAction(request, response, portlet);

    List<Event> events = actionResult.getEvents();

    if (!events.isEmpty()) {
      _processEvents(request, response, events);
    }

    String location = actionResult.getLocation();

    if (Validator.isNotNull(location)) {
      try {
        response.sendRedirect(location);
      } catch (IOException ioe) {
        throw new PortletContainerException(ioe);
      }
    }
  }
    public ActionResult execute(User user, String[] args) {
      ActionResult res = new ActionResult();
      if (!user.isAdmin()) {
        res.setMess(new String[] {prefix + ErrorMessages.E101.Mess(null, null)});
        return res;
      }

      if (!argcheck(2, args)) {
        res.setMess(new String[] {prefix + ErrorMessages.E103.Mess(null, null)});
        return res;
      }

      String theUser = match(user.getMisc(), args[0]);

      if (!DCoProperties.getDS().AccountExists(AccountType.BANK, theUser)) {
        res.setMess(new String[] {prefix + ErrorMessages.E104.Mess(theUser, "Bank")});
        return res;
      }

      double deduct = 0;

      try {
        deduct = Double.parseDouble(args[1]);
      } catch (NumberFormatException nfe) {
        res.setMess(new String[] {prefix + ErrorMessages.E102.Mess(null, null)});
        return res;
      }

      if (deduct < 0.01) {
        res.setMess(new String[] {prefix + ErrorMessages.E102.Mess(null, null)});
        return res;
      }

      double newbal = DCoProperties.getDS().getBalance(AccountType.BANK, theUser) - deduct;

      if (newbal < 0) {
        res.setMess(new String[] {prefix + ErrorMessages.E102.Mess(null, null)});
        return res;
      }

      DCoProperties.getDS().setBalance(AccountType.BANK, theUser, newbal);

      res.setMess(new String[] {prefix + AdminMessages.A303.Mess(theUser, "Bank", newbal)});
      log(LoggingMessages.L623.Mess(user.getName(), theUser, newbal, null));
      return res;
    }
    public ActionResult execute(User user, String[] args) {
      ActionResult res = new ActionResult();
      if (user.getName().equals("SERVER")) {
        res.setMess(new String[] {"You cannot use that command from the console!"});
        return res;
      }

      if (args[0].equals("")) {
        res.setMess(new String[] {prefix + ErrorMessages.E103.Mess(null, null)});
        return res;
      }
      double withdraw = 0;

      try {
        withdraw = Double.parseDouble(args[0]);
      } catch (NumberFormatException nfe) {
        res.setMess(new String[] {prefix + ErrorMessages.E102.Mess(null, null)});
        return res;
      }

      if (withdraw < 0.01) {
        res.setMess(new String[] {prefix + ErrorMessages.E102.Mess(null, null)});
        return res;
      }

      double newBank =
          DCoProperties.getDS().getBalance(AccountType.BANK, user.getName()) - withdraw;

      if (newBank < 0) {
        res.setMess(new String[] {prefix + ErrorMessages.E116.Mess(null, null)});
        return res;
      }

      double newAcc =
          DCoProperties.getDS().getBalance(AccountType.ACCOUNT, user.getName()) + withdraw;
      DCoProperties.getDS().setBalance(AccountType.BANK, user.getName(), newBank);
      DCoProperties.getDS().setBalance(AccountType.ACCOUNT, user.getName(), newAcc);

      res.setMess(
          new String[] {
            prefix + AccountMessages.A205.Mess(null, null, withdraw, -1),
            prefix + AccountMessages.A202.Mess(null, "Account", newAcc, -1),
            prefix + AccountMessages.A202.Mess(null, "Bank", newBank, -1)
          });
      log(LoggingMessages.L603.Mess(user.getName(), null, withdraw, null));
      return res;
    }
    public ActionResult<Result> doInBackground() {
      String response = null;
      try {
        JsonObject jsonReq = createJSONRequest();
        Log.d(tag, "Sending JSON request to " + getUrl() + "\n" + gson.toJson(jsonReq));
        //                if("URL_REGISTER".equals(mServiceId)){
        //                    return mResult;
        //                }
        SyncHttpClient httpClient = new SyncHttpClient();
        final HttpEntity entity =
            new StringEntity(jsonReq.toString(), AsyncHttpResponseHandler.DEFAULT_CHARSET);
        httpClient.post(
            mAppContext,
            getUrl(),
            entity,
            RequestParams.APPLICATION_JSON,
            new JsonHttpResponseHandler() {
              @Override
              public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                  Header[] header = getRequestHeaders();
                  if (header != null)
                    for (int i = 0; i < header.length; i++) {
                      Log.d(tag, header[i].getName() + ": " + header[i].getValue());
                    }
                  mOriginalResponse = response;
                  Log.d(tag, "Received JSON response : " + response.toString(4));
                  super.onSuccess(statusCode, headers, response);
                  mResult = parseJSONResponse(response);
                } catch (Exception e) {
                  Log.e(tag, "Failed to process response message.", e);
                  mResult =
                      new ActionResult<>(
                          new ActionError(ErrorCode.INVALID_RESPONSE, e.getMessage()));
                }
              }

              public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                mOriginalResponse = response;
                super.onSuccess(statusCode, headers, response);
              }

              public void onSuccess(int statusCode, Header[] headers, String response) {
                mOriginalResponse = response;
                super.onSuccess(statusCode, headers, response);
              }

              public void onFailure(
                  int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                mOriginalResponse = errorResponse;
                mOriginalError = throwable;
                onFailure(
                    statusCode,
                    headers,
                    errorResponse == null ? "" : errorResponse.toString(),
                    throwable);
              }

              public void onFailure(
                  int statusCode, Header[] headers, Throwable throwable, JSONArray errorResponse) {
                mOriginalResponse = errorResponse;
                mOriginalError = throwable;
                onFailure(
                    statusCode,
                    headers,
                    errorResponse == null ? "" : errorResponse.toString(),
                    throwable);
              }

              @Override
              public void onFailure(
                  int statusCode, Header[] headers, String responseString, Throwable throwable) {
                mOriginalResponse = responseString;
                mOriginalError = throwable;
                super.onFailure(statusCode, headers, responseString, throwable);
                Log.e(
                    tag,
                    "Received Error response : StatusCode: "
                        + statusCode
                        + ", Received response : "
                        + responseString,
                    throwable);
                try {
                  if (statusCode >= HttpStatus.SC_BAD_REQUEST
                      && statusCode < HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                    mResult =
                        new ActionResult<>(
                            new ActionError(ErrorCode.INVALID_REQUEST, responseString));
                  } else if (statusCode >= HttpStatus.SC_INTERNAL_SERVER_ERROR) {
                    mResult =
                        new ActionResult<>(new ActionError(ErrorCode.SERVER_ERROR, responseString));
                  } else {
                    mResult =
                        new ActionResult<>(
                            new ActionError(
                                ErrorCode.NETWORK_ERROR,
                                mAppContext.getString(R.string.network_error)));
                  }
                } catch (Exception e) {
                  Log.e(tag, "Failed to process response message.", e);
                  mResult =
                      new ActionResult<>(
                          new ActionError(
                              ErrorCode.INVALID_RESPONSE,
                              mAppContext.getString(R.string.unknown_error)));
                }
              }

              protected Object parseResponse(byte[] responseBody) throws JSONException {
                if (null == responseBody) return null;
                Object result = null;
                // trim the string to prevent start with blank, and test if the string is valid
                // JSON, because the parser don't do this :(. If JSON is not valid this will return
                // null
                String jsonString = getResponseString(responseBody, getCharset());
                if (jsonString != null) {
                  Log.d(tag, "Original jsonString: " + jsonString);
                  jsonString = jsonString.trim();
                  while (jsonString.length() > 1 && !jsonString.startsWith("{")) {
                    jsonString = jsonString.substring(1);
                  }
                  if (jsonString.startsWith("{") || jsonString.startsWith("[")) {
                    result = new JSONTokener(jsonString).nextValue();
                    mGsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
                  }
                }
                if (result == null) {
                  result = jsonString;
                }
                return result;
              }
            });
      } catch (Exception e) {
        Log.e(tag, "Failed to process action : " + mServiceId + "\n" + response, e);
        mOriginalError = e;
        mResult =
            new ActionResult<Result>(
                new ActionError(
                    ErrorCode.NETWORK_ERROR, mAppContext.getString(R.string.network_error)));
      }
      if (mBackgroundCallBack != null) {
        if (mResult.hasError()) {
          mBackgroundCallBack.onFailure(mResult.getError());
        } else {
          mBackgroundCallBack.onSuccess(mResult.getObject());
        }
      }
      return mResult;
    }
  @Override
  public WorkflowActionConfig processOutcome(
      Context c,
      EPerson user,
      Workflow workflow,
      Step currentStep,
      WorkflowActionConfig currentActionConfig,
      ActionResult currentOutcome,
      XmlWorkflowItem wfi,
      boolean enteredNewStep)
      throws IOException, AuthorizeException, SQLException, WorkflowException {
    if (currentOutcome.getType() == ActionResult.TYPE.TYPE_PAGE
        || currentOutcome.getType() == ActionResult.TYPE.TYPE_ERROR) {
      // Our outcome is a page or an error, so return our current action
      c.restoreAuthSystemState();
      return currentActionConfig;
    } else if (currentOutcome.getType() == ActionResult.TYPE.TYPE_CANCEL
        || currentOutcome.getType() == ActionResult.TYPE.TYPE_SUBMISSION_PAGE) {
      // We either pressed the cancel button or got an order to return to the submission page, so
      // don't return an action
      // By not returning an action we ensure ourselfs that we go back to the submission page
      c.restoreAuthSystemState();
      return null;
    } else if (currentOutcome.getType() == ActionResult.TYPE.TYPE_OUTCOME) {
      Step nextStep = null;
      WorkflowActionConfig nextActionConfig = null;
      try {
        // We have completed our action search & retrieve the next action
        if (currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE) {
          nextActionConfig = currentStep.getNextAction(currentActionConfig);
        }

        if (nextActionConfig != null) {
          // We remain in the current step since an action is found
          nextStep = currentStep;
          nextActionConfig.getProcessingAction().activate(c, wfi);
          if (nextActionConfig.requiresUI() && !enteredNewStep) {
            createOwnedTask(c, wfi, currentStep, nextActionConfig, user);
            return nextActionConfig;
          } else if (nextActionConfig.requiresUI() && enteredNewStep) {
            // We have entered a new step and have encountered a UI, return null since the current
            // user doesn't have anything to do with this
            c.restoreAuthSystemState();
            return null;
          } else {
            ActionResult newOutcome =
                nextActionConfig.getProcessingAction().execute(c, wfi, currentStep, null);
            return processOutcome(
                c, user, workflow, currentStep, nextActionConfig, newOutcome, wfi, enteredNewStep);
          }
        } else if (enteredNewStep) {
          // If the user finished his/her step, we keep processing until there is a UI step action
          // or no step at all
          nextStep = workflow.getNextStep(c, wfi, currentStep, currentOutcome.getResult());
          c.turnOffAuthorisationSystem();
          nextActionConfig = processNextStep(c, user, workflow, currentOutcome, wfi, nextStep);
          // If we require a user interface return null so that the user is redirected to the
          // "submissions page"
          if (nextActionConfig == null || nextActionConfig.requiresUI()) {
            return null;
          } else {
            return nextActionConfig;
          }
        } else {
          ClaimedTask task = claimedTaskService.findByWorkflowIdAndEPerson(c, wfi, user);

          // Check if we have a task for this action (might not be the case with automatic steps)
          // First add it to our list of finished users, since no more actions remain
          workflowRequirementsService.addFinishedUser(c, wfi, user);
          c.turnOffAuthorisationSystem();
          // Check if our requirements have been met
          if ((currentStep.isFinished(c, wfi)
                  && currentOutcome.getResult() == ActionResult.OUTCOME_COMPLETE)
              || currentOutcome.getResult() != ActionResult.OUTCOME_COMPLETE) {
            // Delete all the table rows containing the users who performed this task
            workflowRequirementsService.clearInProgressUsers(c, wfi);
            // Remove all the tasks
            deleteAllTasks(c, wfi);

            nextStep = workflow.getNextStep(c, wfi, currentStep, currentOutcome.getResult());

            nextActionConfig = processNextStep(c, user, workflow, currentOutcome, wfi, nextStep);
            // If we require a user interface return null so that the user is redirected to the
            // "submissions page"
            if (nextActionConfig == null || nextActionConfig.requiresUI()) {
              return null;
            } else {
              return nextActionConfig;
            }
          } else {
            // We are done with our actions so go to the submissions page but remove action
            // ClaimedAction first
            deleteClaimedTask(c, wfi, task);
            c.restoreAuthSystemState();
            nextStep = currentStep;
            nextActionConfig = currentActionConfig;
            return null;
          }
        }
      } catch (Exception e) {
        log.error("error while processing workflow outcome", e);
        e.printStackTrace();
      } finally {
        if ((nextStep != null && currentStep != null && nextActionConfig != null)
            || (wfi.getItem().isArchived() && currentStep != null)) {
          logWorkflowEvent(
              c,
              currentStep.getWorkflow().getID(),
              currentStep.getId(),
              currentActionConfig.getId(),
              wfi,
              user,
              nextStep,
              nextActionConfig);
        }
      }
    }

    log.error(LogManager.getHeader(c, "Invalid step outcome", "Workflow item id: " + wfi.getID()));
    throw new WorkflowException("Invalid step outcome");
  }