예제 #1
0
  /**
   * Dispatch to the specified method.
   *
   * @since Struts 1.1
   */
  protected ActionForward dispatchMethod(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response,
      String name)
      throws Exception {

    // Make sure we have a valid method name to call.
    // This may be null if the user hacks the query string.
    if (name == null) {
      return this.unspecified(mapping, form, request, response);
    }

    // Identify the method object to be dispatched to
    Method method = null;
    try {
      method = getMethod(name);
    } catch (NoSuchMethodException e) {
      String message = messages.getMessage("dispatch.method", mapping.getPath(), name);
      log.error(message, e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
      return (null);
    }

    ActionForward forward = null;
    try {
      Object args[] = {mapping, form, request, response};
      forward = (ActionForward) method.invoke(this, args);
    } catch (ClassCastException e) {
      String message = messages.getMessage("dispatch.return", mapping.getPath(), name);
      log.error(message, e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
      return (null);
    } catch (IllegalAccessException e) {
      String message = messages.getMessage("dispatch.error", mapping.getPath(), name);
      log.error(message, e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
      return (null);
    } catch (InvocationTargetException e) {
      // Rethrow the target exception if possible so that the
      // exception handling machinery can deal with it
      Throwable t = e.getTargetException();
      if (t instanceof Exception) {
        throw ((Exception) t);
      } else {
        String message = messages.getMessage("dispatch.error", mapping.getPath(), name);
        log.error(message, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
        return (null);
      }
    }

    // Return the returned ActionForward instance
    return (forward);
  }
예제 #2
0
 /**
  * Return a URL path that will return control to the current action. This path is generated by
  * adding the specified parameter to the path of the forward specified as the "input" forward for
  * the given mapping.
  *
  * @param mapping the ActionMapping describing the current action's forwards
  * @param param the name of the path parameter to add
  * @param value the value of the parameter to add
  * @exception ServletException if encoding the path parameter fails or input has not been set
  */
 public static String findReturnPath(ActionMapping mapping, Map params) throws Exception {
   ActionForward inputForward = mapping.getInputForward();
   if (inputForward.getPath() == null)
     throw new ServletException(
         "input cannot be null for returnPath on url: " + mapping.getPath());
   ActionForward returnForward = ActionUtils.changeForwardPath(inputForward, params);
   return returnForward.getPath();
 }
예제 #3
0
  /**
   * Method which is dispatched to when there is no value for specified request parameter included
   * in the request. Subclasses of <code>DispatchAction</code> should override this method if they
   * wish to provide default behavior different than producing an HTTP "Bad Request" error.
   */
  protected ActionForward unspecified(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    String message =
        messages.getMessage("dispatch.parameter", mapping.getPath(), mapping.getParameter());
    log.error(message);
    response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
    return (null);
  }
예제 #4
0
  /**
   * Gets the <code>Action</code> specified by the mapping type from a PicoContainer. The action
   * will be instantiated if necessary, and its dependencies will be injected. The action will be
   * instantiated via a special PicoContainer that just contains actions. If this container already
   * exists in the request attribute, this method will use it. If no such container exists, this
   * method will create a new Pico container and place it in the request. The parent container will
   * either be the request container, or if that container can not be found the session container,
   * or if that container can not be found, the application container. If no parent container can be
   * found, a <code>PicoInitializationException</code> will be thrown. The action path specified in
   * the mapping is used as the component key for the action.
   *
   * @param request the Http servlet request.
   * @param mapping the Struts mapping object, whose type property tells us what Action class is
   *     required.
   * @param servlet the Struts <code>ActionServlet</code>.
   * @return the <code>Action</code> instance.
   * @throws PicoIntrospectionException if the mapping type does not specify a valid action.
   * @throws PicoInitializationException if no request, session, or application scoped Pico
   *     container can be found.
   */
  public Action processAction(
      HttpServletRequest request, ActionMapping mapping, ActionServlet servlet)
      throws PicoIntrospectionException, PicoInitializationException {
    Object actionKey = mapping.getPath();
    Class actionType = getActionClass(mapping.getType());

    Action action = (Action) sf.getService(actionKey);
    if (action == null) {
      sf.registerService(actionKey, actionType);
      action = (Action) sf.getService(actionKey);
    }

    action.setServlet(servlet);
    return action;
  }
  public ActionForward executeAction(
      ActionMapping actionMapping,
      ActionForm actionForm,
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse) {
    ActionForward retorno = actionMapping.findForward("login");
    this.messages = new ActionErrors();
    RelatorioUsuarioPerfilForm form = null;
    String acao = "";
    try {
      form =
          actionForm != null
              ? (RelatorioUsuarioPerfilForm) actionForm
              : new RelatorioUsuarioPerfilForm();

      if (form.getAcao().equalsIgnoreCase("")) {
        if (actionMapping.getPath().equalsIgnoreCase("/relUsuarioPerfil")) {
          form.setAcao("init");
        }
      }

      this.relEvents = new RelatorioUsuarioPerfilCore();
    } catch (Exception ex) {
      try {
        throw new SGOActionException(ex);
      } catch (SGOActionException e) {
        e.printStackTrace();
      }
    }

    acao = form.getAcao() != "" ? form.getAcao() : "Fail";

    if (acao.equals("init")) {
      retorno = init(actionMapping, actionForm, httpServletRequest, httpServletResponse);
    }
    if (acao.equals("excel")) {
      retorno = toExcel(actionMapping, actionForm, httpServletRequest, httpServletResponse);
    }
    if (acao.equals("imprimir")) {
      retorno = toPrint(actionMapping, actionForm, httpServletRequest, httpServletResponse);
    }

    this.relEvents = null;
    return retorno;
  }
  /**
   * Dispatches to the target class' <code>unspecified</code> method, if present, otherwise throws a
   * ServletException. Classes utilizing <code>EventActionDispatcher</code> should provide an <code>
   * unspecified</code> method if they wish to provide behavior different than throwing a
   * ServletException.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The non-HTTP request we are processing
   * @param response The non-HTTP response we are creating
   * @return The forward to which control should be transferred, or <code>null</code> if the
   *     response has been completed.
   * @throws Exception if the application business logic throws an exception.
   */
  protected ActionForward unspecified(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    // Identify if there is an "unspecified" method to be dispatched to
    String name = "unspecified";
    Method method = null;

    try {
      method = getMethod(name);
    } catch (NoSuchMethodException e) {
      String message = messages.getMessage("event.parameter", mapping.getPath());

      LOG.error(message + " " + mapping.getParameter());

      throw new ServletException(message);
    }

    return dispatchMethod(mapping, form, request, response, name, method);
  }
예제 #7
0
  /**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if an exception occurs
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Identify the request parameter containing the method name
    String parameter = mapping.getParameter();
    if (parameter == null) {
      String message = messages.getMessage("dispatch.handler", mapping.getPath());
      log.error(message);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
      return (null);
    }

    // Identify the method name to be dispatched to.
    // dispatchMethod() will call unspecified() if name is null
    String name = request.getParameter(parameter);

    // Invoke the named method, and return the result
    return dispatchMethod(mapping, form, request, response, name);
  }
예제 #8
0
  private void mappingContextAppend(HttpServletRequest request, final StringBuilder exceptionInfo) {
    String query = request.getQueryString();
    setRequestURI(request.getRequestURI());
    setRequestURL(request.getRequestURL().toString());
    setRequestFullUrl(getRequestFullUrl(request));
    setQueryString(query);
    setRequestMethod(request.getMethod());
    setRequestParameters(getRequestParameters(request));
    exceptionInfo.append("[RequestURI] ").append(request.getRequestURI()).append("\n");
    exceptionInfo.append("[RequestURL] ").append(request.getRequestURL()).append("\n");
    exceptionInfo.append("[QueryString] ").append(request.getQueryString()).append("\n");
    exceptionInfo.append("[Method] ").append(request.getMethod()).append('\n');

    if (request.getAttribute(PresentationConstants.ORIGINAL_MAPPING_KEY) != null) {
      ActionMapping mapping =
          (ActionMapping) request.getAttribute(PresentationConstants.ORIGINAL_MAPPING_KEY);
      setActionMapping(mapping);
      exceptionInfo.append("[Path] ").append(mapping.getPath()).append("\n");
      exceptionInfo.append("[Name] ").append(mapping.getName()).append("\n");
    } else {
      exceptionInfo.append(
          "[Path|Name] impossible to get (exception through UncaughtExceptionFilter)\n");
    }
  }
  /**
   * This method handles preparing all of the accounting line data so that it can be pushed up to
   * the balance inquiries for populating the search criteria of each.
   *
   * @param mapping
   * @param form
   * @param request
   * @param line
   * @return ActionForward
   */
  protected ActionForward performBalanceInquiryForAccountingLine(
      ActionMapping mapping, ActionForm form, HttpServletRequest request, AccountingLine line) {
    // build out base path for return location
    String basePath =
        request.getScheme()
            + "://"
            + request.getServerName()
            + ":"
            + request.getServerPort()
            + request.getContextPath();

    // build out the actual form key that will be used to retrieve the form on refresh
    String callerDocFormKey = GlobalVariables.getUserSession().addObjectWithGeneratedKey(form);

    // now add required parameters
    Properties parameters = new Properties();
    parameters.put(KFSConstants.DISPATCH_REQUEST_PARAMETER, KFSConstants.START_METHOD);
    // need this next param b/c the lookup's return back will overwrite
    // the original doc form key
    parameters.put(KFSConstants.BALANCE_INQUIRY_REPORT_MENU_CALLER_DOC_FORM_KEY, callerDocFormKey);
    parameters.put(KFSConstants.DOC_FORM_KEY, callerDocFormKey);
    parameters.put(KFSConstants.BACK_LOCATION, basePath + mapping.getPath() + ".do");

    if (line.getPostingYear() != null) {
      parameters.put(KFSPropertyConstants.UNIVERSITY_FISCAL_YEAR, line.getPostingYear().toString());
    }
    if (StringUtils.isNotBlank(line.getReferenceOriginCode())) {
      parameters.put("referenceOriginCode", line.getReferenceOriginCode());
    }
    if (StringUtils.isNotBlank(line.getReferenceNumber())) {
      parameters.put("referenceNumber", line.getReferenceNumber());
    }
    if (StringUtils.isNotBlank(line.getReferenceTypeCode())) {
      parameters.put("referenceTypeCode", line.getReferenceTypeCode());
    }
    if (StringUtils.isNotBlank(line.getDebitCreditCode())) {
      parameters.put("debitCreditCode", line.getDebitCreditCode());
    }
    if (StringUtils.isNotBlank(line.getChartOfAccountsCode())) {
      parameters.put("chartOfAccountsCode", line.getChartOfAccountsCode());
    }
    if (StringUtils.isNotBlank(line.getAccountNumber())) {
      parameters.put("accountNumber", line.getAccountNumber());
    }
    if (StringUtils.isNotBlank(line.getFinancialObjectCode())) {
      parameters.put("financialObjectCode", line.getFinancialObjectCode());
    }
    if (StringUtils.isNotBlank(line.getSubAccountNumber())) {
      parameters.put("subAccountNumber", line.getSubAccountNumber());
    }
    if (StringUtils.isNotBlank(line.getFinancialSubObjectCode())) {
      parameters.put("financialSubObjectCode", line.getFinancialSubObjectCode());
    }
    if (StringUtils.isNotBlank(line.getProjectCode())) {
      parameters.put("projectCode", line.getProjectCode());
    }
    if (StringUtils.isNotBlank(getObjectTypeCodeFromLine(line))) {
      if (!StringUtils.isBlank(line.getObjectTypeCode())) {
        parameters.put("objectTypeCode", line.getObjectTypeCode());
      } else {
        line.refreshReferenceObject("objectCode");
        parameters.put("objectTypeCode", line.getObjectCode().getFinancialObjectTypeCode());
      }
    }

    String lookupUrl =
        UrlFactory.parameterizeUrl(
            basePath + "/" + KFSConstants.BALANCE_INQUIRY_REPORT_MENU_ACTION, parameters);

    // register that we're going to come back w/ to this form w/ a refresh methodToCall
    ((KualiAccountingDocumentFormBase) form)
        .registerEditableProperty(KRADConstants.DISPATCH_REQUEST_PARAMETER);

    return new ActionForward(lookupUrl, true);
  }
예제 #10
0
 protected String getActionPath(ActionMapping mapping, HttpServletRequest request) {
   return mapping.getPath() + ".do";
 }
예제 #11
0
  /**
   * Checks for return from a lookup or question, and restores the action form stored under the
   * request parameter docFormKey.
   */
  @Override
  protected ActionForm processActionForm(
      HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) {

    String documentNumber = getDocumentNumber(request);
    if (documentNumber != null) {
      MDC.put(MDC_DOC_ID, documentNumber);
    }

    UserSession userSession =
        (UserSession) request.getSession().getAttribute(KRADConstants.USER_SESSION_KEY);

    String docFormKey = request.getParameter(KRADConstants.DOC_FORM_KEY);
    String methodToCall = request.getParameter(KRADConstants.DISPATCH_REQUEST_PARAMETER);
    String refreshCaller = request.getParameter(KRADConstants.REFRESH_CALLER);
    //		String searchListRequestKey = request.getParameter(KRADConstants.SEARCH_LIST_REQUEST_KEY);
    String documentWebScope = request.getParameter(KRADConstants.DOCUMENT_WEB_SCOPE);

    if (mapping.getPath().startsWith(KRADConstants.REFRESH_MAPPING_PREFIX)
        || KRADConstants.RETURN_METHOD_TO_CALL.equalsIgnoreCase(methodToCall)
        || KRADConstants.QUESTION_REFRESH.equalsIgnoreCase(refreshCaller)
        || KRADConstants.TEXT_AREA_REFRESH.equalsIgnoreCase(refreshCaller)
        || KRADConstants.SESSION_SCOPE.equalsIgnoreCase(documentWebScope)) {
      ActionForm form = null;
      // check for search result storage and clear
      GlobalVariables.getUserSession().removeObjectsByPrefix(KRADConstants.SEARCH_LIST_KEY_PREFIX);

      // We put different type of forms such as document form, lookup form
      // in session but we only store document form in
      // database.
      if (userSession.retrieveObject(docFormKey) != null) {
        LOG.debug("getDecomentForm KualiDocumentFormBase from session");
        form = (ActionForm) userSession.retrieveObject(docFormKey);
      } else if (StringUtils.isNotBlank(documentNumber)) {
        form =
            getSessionDocumentService()
                .getDocumentForm(documentNumber, docFormKey, userSession, request.getRemoteAddr());
      }
      request.setAttribute(mapping.getAttribute(), form);
      if (!KRADConstants.SESSION_SCOPE.equalsIgnoreCase(documentWebScope)) {
        userSession.removeObject(docFormKey);
      }
      // we should check whether this is a multipart request because we
      // could have had a combination of query parameters and a multipart
      // request
      String contentType = request.getContentType();
      String method = request.getMethod();
      if (("POST".equalsIgnoreCase(method)
          && contentType != null
          && contentType.startsWith("multipart/form-data"))) {
        // this method parses the multipart request and adds new
        // non-file parameters into the request
        WebUtils.getMultipartParameters(request, null, form, mapping);
      }
      // The form can be null if the document is not a session document
      if (form != null) {
        return form;
      }
    }

    // Rice has the ability to limit file upload sizes on a per-form basis,
    // so the max upload sizes may be accessed by calling methods on
    // PojoFormBase.
    // This requires that we are able know the file upload size limit (i.e.
    // retrieve a form instance) before we parse a mulitpart request.
    ActionForm form = super.processActionForm(request, response, mapping);

    // for sessiondocument with multipart request
    String contentType = request.getContentType();
    String method = request.getMethod();

    if ("GET".equalsIgnoreCase(method)
        && StringUtils.isNotBlank(methodToCall)
        && form instanceof PojoForm
        && ((PojoForm) form)
            .getMethodToCallsToBypassSessionRetrievalForGETRequests()
            .contains(methodToCall)) {
      return createNewActionForm(mapping, request);
    }

    // if we have a multipart request, parse it and return the stored form
    // from session if the doc form key is not blank. If it is blank, then
    // we just return the form
    // generated from the superclass processActionForm method. Either way,
    // we need to parse the mulitpart request now so that we may determine
    // what the value of the doc form key is.
    // This is generally against the contract of processActionForm, because
    // processPopulate should be responsible for parsing the mulitpart
    // request, but we need to parse it now
    // to determine the doc form key value.
    if (("POST".equalsIgnoreCase(method)
        && contentType != null
        && contentType.startsWith("multipart/form-data"))) {
      WebUtils.getMultipartParameters(request, null, form, mapping);
      docFormKey = request.getParameter(KRADConstants.DOC_FORM_KEY);
      documentWebScope = request.getParameter(KRADConstants.DOCUMENT_WEB_SCOPE);

      documentNumber = getDocumentNumber(request);

      if (KRADConstants.SESSION_SCOPE.equalsIgnoreCase(documentWebScope)
          || (form instanceof KualiDocumentFormBase
              && WebUtils.isDocumentSession(
                  ((KualiDocumentFormBase) form).getDocument(), (KualiDocumentFormBase) form))) {

        Object userSessionObject = userSession.retrieveObject(docFormKey);
        if (userSessionObject != null && userSessionObject instanceof ActionForm) {
          LOG.debug("getDocumentForm KualiDocumentFormBase from session");
          form = (ActionForm) userSessionObject;
        } else {
          ActionForm tempForm =
              getSessionDocumentService()
                  .getDocumentForm(
                      documentNumber, docFormKey, userSession, request.getRemoteAddr());
          if (tempForm != null) {
            form = tempForm;
          }
        }

        request.setAttribute(mapping.getAttribute(), form);
        if (form != null) {
          return form;
        }
      }
    }
    return form;
  }
예제 #12
0
  /**
   * Hooks into validate to catch any errors from the populate, and translate the ErrorMap to
   * ActionMessages.
   */
  @Override
  protected boolean processValidate(
      HttpServletRequest request,
      HttpServletResponse response,
      ActionForm form,
      ActionMapping mapping)
      throws IOException, ServletException, InvalidCancelException {

    // skip form validate if we had errors from populate
    if (GlobalVariables.getMessageMap().hasNoErrors()) {
      if (form == null) {
        return (true);
      }
      // Was this request cancelled?
      if (request.getAttribute(Globals.CANCEL_KEY) != null) {
        if (LOG.isDebugEnabled()) {
          LOG.debug(" Cancelled transaction, skipping validation");
        }
        return (true);
      }

      // Has validation been turned off for this mapping?
      if (!mapping.getValidate()) {
        return (true);
      }

      // call super to call forms validate
      super.processValidate(request, response, form, mapping);
    }

    publishMessages(request);
    if (!GlobalVariables.getMessageMap().hasNoErrors()) {
      // Special handling for multipart request
      if (form.getMultipartRequestHandler() != null) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("  Rolling back multipart request");
        }
        form.getMultipartRequestHandler().rollback();
      }

      // Fix state that could be incorrect because of validation failure
      if (form instanceof PojoForm) {
        ((PojoForm) form).processValidationFail();
      }

      // Was an input path (or forward) specified for this mapping?
      String input = mapping.getInput();
      if (input == null) {
        if (LOG.isDebugEnabled()) {
          LOG.debug("  Validation failed but no input form available");
        }
        response.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            getInternal().getMessage("noInput", mapping.getPath()));
        return (false);
      }

      if (moduleConfig.getControllerConfig().getInputForward()) {
        ForwardConfig forward = mapping.findForward(input);
        processForwardConfig(request, response, forward);
      } else {
        internalModuleRelativeForward(input, request, response);
      }

      return (false);
    }
    return true;
  }
  public ActionForward grouperExecute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession session,
      GrouperSession grouperSession)
      throws Exception {
    Class sortOverrideClass = Group.class;
    NavExceptionHelper neh = getExceptionHelper(session);
    DynaActionForm subjectForm = (DynaActionForm) form;
    if ("true".equals(request.getParameter("changeMode")))
      PopulateSearchSubjectsAction.initMode(session);
    session.setAttribute("subtitle", "subject.action.show-summary");
    if (isEmpty(subjectForm.get("callerPageId"))) {
      if (isEmpty(subjectForm.get("subjectId"))) {
        LOG.info("Restoring lastSubjectSummaryForm");
        restoreDynaFormBean(session, subjectForm, "lastSubjectSummaryForm");
      } else {
        LOG.info("Saving lastSubjectSummaryForm");
        saveDynaFormBean(session, subjectForm, "lastSubjectSummaryForm");
        saveAsCallerPage(request, subjectForm);
      }
    }
    saveAsCallerPage(request, subjectForm);

    String listField = (String) subjectForm.get("listField");
    String membershipField = "members";

    if (!isEmpty(listField)) {
      membershipField = listField;
    }
    Field mField = null;
    try {
      mField = FieldFinder.find(membershipField, true);
    } catch (SchemaException e) {
      LOG.error("Could not find Field: " + membershipField, e);
      if ("members".equals(membershipField)) {
        LOG.fatal("Built in field: members, missing");
        throw new UnrecoverableErrorException(e);
      } else {
        mField = FieldFinder.find("members", true);
        request.setAttribute(
            "message", new Message("error.subject-summary.missing-field", listField, true));
      }
    }

    subjectForm.set("contextSubject", "true");
    String subjectId = (String) subjectForm.get("subjectId");
    String subjectType = (String) subjectForm.get("subjectType");
    String subjectSource = (String) subjectForm.get("sourceId");
    if (isEmpty(subjectId) || isEmpty(subjectType) || isEmpty(subjectSource)) {
      String msg =
          neh.missingParameters(
              subjectId, "subjectId", subjectType, "subjectType", subjectSource, "sourceId");
      LOG.error(msg);
      if (doRedirectToCaller(subjectForm)) {
        session.setAttribute(
            "sessionMessage", new Message("error.subject-summary.missing-parameter", true));
        return redirectToCaller(subjectForm);
      }
      throw new UnrecoverableErrorException("error.subject-summary.missing-parameter");
    }
    Subject subject = null;
    try {
      subject = SubjectFinder.findById(subjectId, subjectType, subjectSource, true);
    } catch (Exception e) {
      LOG.error(e);
      if (e instanceof SubjectNotFoundException) {
        subject = new UnresolvableSubject(subjectId, subjectType, subjectSource);
        addMessage(
            new Message(
                "error.subject.unresolvable", new String[] {subjectId, subjectSource}, true),
            request);
      } else {

        String contextError = "error.subject-summary.subject.exception";
        session.setAttribute("sessionMessage", new Message(neh.key(e), contextError, true));
        if (doRedirectToCaller(subjectForm)) return redirectToCaller(subjectForm);
        throw new UnrecoverableErrorException(contextError, e);
      }
    }
    Map subjectMap = GrouperHelper.subject2Map(subject);
    request.setAttribute("subject", subjectMap);

    String order = null;
    try {
      order =
          GrouperUiFilter.retrieveSessionMediaResourceBundle()
              .getString("subject.attributes.order." + subject.getSource().getId());
      request.setAttribute("subjectAttributeNames", order.split(","));
    } catch (Exception e) {
      // No order specified, so go with all, in whatever order they come
      List extendedAttr = new ArrayList(GrouperUtil.nonNull(subject.getAttributes()).keySet());
      extendedAttr.add("subjectType");
      extendedAttr.add("id");
      request.setAttribute("subjectAttributeNames", extendedAttr);
    }
    String membershipListScope = (String) subjectForm.get("membershipListScope");

    if ("any-access".equals(membershipListScope)) {
      if ("false".equals(request.getParameter("advancedSearch"))) {
        membershipListScope = null;
      } else {
        request.setAttribute("fromSubjectSummary", Boolean.TRUE);

        session.setAttribute("groupSearchSubject", subject);
        session.setAttribute("groupSearchSubjectMap", subjectMap);
        return mapping.findForward(FORWARD_GroupSearch);
      }
    }
    if (":all:imm:eff:access:naming:".indexOf(":" + membershipListScope + ":") == -1) {
      membershipListScope = (String) session.getAttribute("subjectMembershipListScope");
    }
    if (membershipListScope == null) membershipListScope = "imm";
    session.setAttribute("subjectMembershipListScope", membershipListScope);
    subjectForm.set("membershipListScope", membershipListScope);

    String accessPriv = (String) subjectForm.get("accessPriv");
    if (isEmpty(accessPriv)) accessPriv = (String) session.getAttribute("subjectSummaryAccessPriv");
    if (isEmpty(accessPriv)) accessPriv = "read";
    session.setAttribute("subjectSummaryAccessPriv", accessPriv);
    subjectForm.set("accessPriv", accessPriv);

    String namingPriv = (String) subjectForm.get("namingPriv");
    if (isEmpty(namingPriv)) namingPriv = (String) session.getAttribute("subjectSummaryNamingPriv");
    if (isEmpty(namingPriv)) namingPriv = "create";
    session.setAttribute("subjectSummaryNamingPriv", namingPriv);
    subjectForm.set("namingPriv", namingPriv);
    // Retrieve the membership according to scope selected by user
    Member member = null;
    try {
      member = MemberFinder.findBySubject(grouperSession, subject, true);
      if (member == null) {
        throw new MemberNotFoundException("Unresolvable subject is also not a Member");
      }
    } catch (Exception e) {
      LOG.error(e);
      if (doRedirectToCaller(subjectForm)) {
        session.setAttribute(
            "sessionMessage", new Message("error.subject-summary.member.exception", true));
        return redirectToCaller(subjectForm);
      }
      throw new UnrecoverableErrorException("error.subject-summary.member.exception", e);
    }
    Set subjectScopes = null;
    List subjectScopeMaps = null;
    Map listViews = new HashMap();
    listViews.put("titleKey", "subject.summary.memberships");
    listViews.put("noResultsKey", "subject.list-membership.none");
    listViews.put("view", "whereSubjectsAreMembers");
    // listViews.put("itemView","whereIsMemberLink");
    listViews.put("itemView", "subjectSummary");
    listViews.put("headerView", "genericListHeader");
    listViews.put("footerView", "genericListFooter");

    if ("imm".equals(membershipListScope)) {
      subjectScopes = member.getImmediateMemberships(mField);
      listViews.put("noResultsKey", "subject.list-membership.imm.none");
    } else if ("eff".equals(membershipListScope)) {
      if (membershipField.equals("members")) {
        subjectScopes = member.getMemberships();
        subjectScopes.removeAll(member.getImmediateMemberships());

      } else {
        subjectScopes = member.getEffectiveMemberships(mField);
        listViews.put("noResultsKey", "subject.list-membership.all.none");
      }
      if ("members".equals(membershipField)) {
        listViews.put("noResultsKey", "subject.list-membership.eff.none");
      } else {
        listViews.put("noResultsKey", "subject.list-membership.custom.eff.none");
      }

    } else if ("all".equals(membershipListScope)) {
      subjectScopes = member.getMemberships(mField);
      listViews.put("noResultsKey", "subject.list-membership.all.none");
    } else if ("access".equals(membershipListScope)) {

      subjectScopes = GrouperHelper.getGroupsOrStemsWhereMemberHasPriv(member, accessPriv);

      // filter out groups where the subject can't see privs
      removeObjectsNotAllowedToSeePrivs(subjectScopes);

      subjectScopeMaps =
          GrouperHelper.subjects2SubjectPrivilegeMaps(
              grouperSession, subjectScopes, subject, accessPriv);
      listViews.put("titleKey", "subject.summary.access-privs");
      listViews.put("noResultsKey", "subject.list-access.none");
      listViews.put("view", "subjectSummaryPrivileges");
      listViews.put("itemView", "subjectSummaryPrivilege");
    } else {
      sortOverrideClass = Stem.class;
      subjectScopes = GrouperHelper.getGroupsOrStemsWhereMemberHasPriv(member, namingPriv);

      // filter out stems where the subject can't see privs
      removeObjectsNotAllowedToSeePrivs(subjectScopes);

      subjectScopeMaps =
          GrouperHelper.subjects2SubjectPrivilegeMaps(
              grouperSession, subjectScopes, subject, namingPriv);
      listViews.put("titleKey", "subject.summary.naming-privs");
      listViews.put("noResultsKey", "subject.list-naming.none");
      listViews.put("view", "subjectSummaryPrivileges");
      listViews.put("itemView", "subjectSummaryPrivilege");
    }
    request.setAttribute("scopeListData", listViews);
    if (subjectScopeMaps == null) {
      Map countMap = new HashMap();
      Map sources = new HashMap();
      List uniqueSubjectScopes =
          GrouperHelper.getOneMembershipPerSubjectOrGroup(
              subjectScopes, "subject", countMap, sources, 0);
      subjectScopeMaps = GrouperHelper.memberships2Maps(grouperSession, uniqueSubjectScopes);
      GrouperHelper.setMembershipCountPerSubjectOrGroup(subjectScopeMaps, "subject", countMap);
    }
    // This is a hack to force sorting by Group/Stem rather than Subject - which is generally what
    // happens with Memberships
    // DefaultComparatorImpl has been updated to read the TheadLocal
    UIThreadLocal.put("GrouperComparatorHelperOverrideClass", sortOverrideClass);
    subjectScopeMaps = sort(subjectScopeMaps, request, "subjectSummary", -1, null);
    UIThreadLocal.replace("GrouperComparatorHelperOverrideClass", null);
    String startStr = (String) subjectForm.get("start");
    if (startStr == null || "".equals(startStr)) startStr = "0";

    int start = Integer.parseInt(startStr);
    int pageSize = getPageSize(session);
    int end = start + pageSize;
    if (end > subjectScopeMaps.size()) end = subjectScopeMaps.size();
    CollectionPager pager =
        new CollectionPager(
            null, subjectScopeMaps, subjectScopeMaps.size(), null, start, null, pageSize);

    if (!isEmpty(listField)) pager.setParam("listField", listField);
    pager.setParam("subjectId", subjectId);
    pager.setParam("subjectType", subjectType);
    pager.setParam("sourceId", subjectSource);
    pager.setParam("returnTo", subjectForm.get("returnTo"));
    pager.setParam("returnToLinkKey", subjectForm.get("returnToLinkKey"));
    pager.setTarget(mapping.getPath());
    request.setAttribute("pager", pager);
    request.setAttribute("linkParams", pager.getParams().clone());
    request.setAttribute("listFieldParams", pager.getParams().clone());

    Map saveParams = new HashMap();
    saveParams.put("subjectId", subject.getId());
    saveParams.put("subjectType", subject.getType().getName());
    saveParams.put("sourceId", subject.getSource().getId());
    saveParams.put("callerPageId", request.getAttribute("thisPageId"));
    request.setAttribute("saveParams", saveParams);

    if (subjectType.equals("group")) {
      List lists = GrouperHelper.getReadableListFieldsForGroup(grouperSession, subjectId);
      if (!lists.isEmpty()) request.setAttribute("listFields", lists);
    }

    List memberOfListFields = GrouperHelper.getListFieldsForSubject(grouperSession, subject);
    if (memberOfListFields.size() > 0) {
      request.setAttribute("memberOfListFields", memberOfListFields);
    }

    Collection accessPrivs =
        GrouperHelper.getGroupPrivsWithLabels(GrouperUiFilter.retrieveSessionNavResourceBundle());
    Collection namingPrivs =
        GrouperHelper.getStemPrivsWithLabels(GrouperUiFilter.retrieveSessionNavResourceBundle());
    request.setAttribute("allAccessPrivs", accessPrivs);
    request.setAttribute("allNamingPrivs", namingPrivs);

    return mapping.findForward(FORWARD_SubjectSummary);
  }
예제 #14
0
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    ActionMessages msgs = new ActionMessages();

    SessionInfo sessionInfo = LogonControllerFactory.getInstance().getSessionInfo(request);

    if (sessionInfo == null
        && request.getSession().getAttribute(Constants.SESSION_LOCKED) == null
        && LogonControllerFactory.getInstance().hasClientLoggedOn(request, response)
            == LogonController.LOGGED_ON) {
      if (log.isDebugEnabled()) log.debug(request.getRemoteHost() + " is already authenticated");

      return mapping.findForward("success");
    }

    /*
     * Get the authentication session and module to use to validate this
     * authentication attempt
     */
    AuthenticationScheme scheme =
        (AuthenticationScheme) request.getSession().getAttribute(Constants.AUTH_SESSION);
    LogonStateAndCache logonStateMachine =
        (LogonStateAndCache)
            request.getSession().getAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);

    // there are different users so we need to logon again, clearing the authentication scheme and
    // logon machine.
    if (sessionInfo != null
        && logonStateMachine != null
        && !sessionInfo.getUser().equals(logonStateMachine.getUser())) {
      request.getSession().removeAttribute(Constants.AUTH_SESSION);
      request.getSession().removeAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);
      LogonControllerFactory.getInstance().logoffSession(request, response);
      msgs.add(
          Globals.ERROR_KEY,
          new ActionMessage("login.logonNotAllowed", "Session no longer valid, logon again."));
      saveErrors(request, msgs);
      return new RedirectWithMessages(mapping.findForward("logon"), request);
    }

    if (logonStateMachine == null) {
      logonStateMachine =
          new LogonStateAndCache(LogonStateAndCache.STATE_STARTED, request.getSession());
      request.getSession().setAttribute(LogonStateAndCache.LOGON_STATE_MACHINE, logonStateMachine);
    }
    if (scheme == null) {

      ActionForward fwd = null;
      try {
        fwd =
            ShowLogonAction.checkAuthSession(
                null, false, mapping, request, response, logonStateMachine);
      } catch (CoreException ce) {

      } catch (Throwable e) {
        log.error("Logon not allowed.", e);
        ActionMessages errs = new ActionMessages();
        if (e instanceof CoreException) {
          errs.add(Globals.ERROR_KEY, ((CoreException) e).getBundleActionMessage());
        } else {
          errs.add(
              Globals.ERROR_KEY,
              new ActionMessage("login.logonNotAllowed", "Please contact your administrator."));
        }
        saveErrors(request, errs);
        request.getSession().removeAttribute(Constants.AUTH_SESSION);
        request.getSession().removeAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);
        if (form != null) form.reset(mapping, request);
        return new RedirectWithMessages(mapping.findForward("failed"), request);
      }
      if (fwd != null) {
        scheme = (AuthenticationScheme) request.getSession().getAttribute(Constants.AUTH_SESSION);
      }
    }

    if (scheme != null) {
      AuthenticationModule module = scheme.currentAuthenticationModule();
      if (module == null) {
        log.error("No authentication module.");
        request.getSession().removeAttribute(Constants.AUTH_SESSION);
        return mapping.findForward("logon");
      }

      try {
        // If there is no user in the scheme then it is an invalid login
        if (scheme.getUser() == null) {
          throw new InvalidLoginCredentialsException();
        }

        // Check the account is enabled and not locked
        if (!PolicyUtil.isEnabled(scheme.getUser())) {
          throw new AccountLockedException(scheme.getUsername(), "Account disabled.", true, 0);
        }

        // Check for locks
        LogonControllerFactory.getInstance()
            .checkForAccountLock(
                scheme.getUsername(), scheme.getUser().getRealm().getResourceName());

        // Authenticate
        authenticate(scheme, request);

        // Check logon is currently allowed
        String logonNotAllowedReason =
            LogonControllerFactory.getInstance().checkLogonAllowed(scheme.getUser());

        if (logonNotAllowedReason != null) {
          log.warn("Logon not allowed because '" + logonNotAllowedReason + "'");
          msgs.add(
              Globals.ERROR_KEY, new ActionMessage("login.logonNotAllowed", logonNotAllowedReason));
          saveErrors(request, msgs);
          return new RedirectWithMessages(mapping.findForward("logon"), request);
        }

        // Check for the next authentication modules
        AuthenticationModule nextModule = scheme.nextAuthenticationModule();
        if (nextModule != null
            && request.getSession().getAttribute(Constants.SESSION_LOCKED) == null) {
          if (log.isDebugEnabled())
            log.debug(
                "There are more authentication modules to satisfy (current mapping = "
                    + mapping.getPath());
          ActionForward fw = new RedirectWithMessages(mapping.findForward("logon"), request);
          return fw;
        }

        return finishAuthentication(scheme, request, response);
      } catch (InputRequiredException ex) {
        // The page wants to display or redirect somewhere
        if (ex.getForward() == null) return mapping.findForward("logon");
        else return ex.getForward();
      } catch (AccountLockedException ale) {
        return accountLocked(mapping, request, ale, msgs);
      } catch (InvalidLoginCredentialsException ex) {
        log.error("[" + request.getRemoteHost() + "] authentication failed", ex);

        LogonForm logonForm = (LogonForm) form;

        CoreServlet.getServlet()
            .fireCoreEvent(
                new CoreEvent(this, CoreEventConstants.LOGON, null, null, ex)
                    .addAttribute(
                        CoreAttributeConstants.EVENT_ATTR_IP_ADDRESS, request.getRemoteAddr())
                    .addAttribute(CoreAttributeConstants.EVENT_ATTR_HOST, request.getRemoteHost())
                    .addAttribute(CoreAttributeConstants.EVENT_ATTR_SCHEME, scheme.getSchemeName())
                    .addAttribute(
                        CoreAttributeConstants.EVENT_ATTR_ACCOUNT, logonForm.getUsername()));

        request.getSession().removeAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);
        request.getSession().removeAttribute(Constants.AUTH_SESSION);

        try {
          scheme.setAccountLock(
              LogonControllerFactory.getInstance()
                  .logonFailed(
                      ((LogonForm) form).getUsername(),
                      ((LogonForm) form).getRealmName(),
                      scheme.getAccountLock()));
        } catch (AccountLockedException ale) {
          return accountLocked(mapping, request, ale, msgs);
        }

        msgs.add(Globals.ERROR_KEY, new ActionMessage("login.invalidCredentials"));
        saveErrors(request, msgs);
        return new RedirectWithMessages(mapping.findForward("logon"), request);
      } catch (Exception e) {
        log.error("Internal error authenticating.", e);
        msgs.add(
            Globals.ERROR_KEY, new BundleActionMessage("security", "login.error", e.getMessage()));
        saveErrors(request, msgs);
        request.getSession().setAttribute(Constants.EXCEPTION, e);
        request.getSession().removeAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);
        request.getSession().removeAttribute(Constants.AUTH_SESSION);
        return new RedirectWithMessages(mapping.findForward("logon"), request);
      }
    } else {
      ActionMessages errs = new ActionMessages();
      errs.add(
          Globals.MESSAGE_KEY,
          new BundleActionMessage("security", "login.logonNotAllowed", "No scheme available."));
      saveErrors(request, errs);
      request.getSession().removeAttribute(LogonStateAndCache.LOGON_STATE_MACHINE);
      request.getSession().removeAttribute(Constants.AUTH_SESSION);
      if (form != null) form.reset(mapping, request);
      return new RedirectWithMessages(mapping.findForward("logon"), request);
    }
  }