public static String addBulkFromCart(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");

    String shoppingListId = request.getParameter("shoppingListId");
    String shoppingListTypeId = request.getParameter("shoppingListTypeId");
    String selectedCartItems[] = request.getParameterValues("selectedItem");
    if (UtilValidate.isEmpty(selectedCartItems)) {
      selectedCartItems = makeCartItemsArray(cart);
    }

    try {
      shoppingListId =
          addBulkFromCart(
              delegator,
              dispatcher,
              cart,
              userLogin,
              shoppingListId,
              shoppingListTypeId,
              selectedCartItems,
              true,
              true);
    } catch (IllegalArgumentException e) {
      request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
      return "error";
    }

    request.setAttribute("shoppingListId", shoppingListId);
    return "success";
  }
  @Override
  public BroadcastAction filter(
      HttpServletRequest request, HttpServletResponse response, Object message) {

    if (request.getHeader("User-Agent") != null
            && request.getAttribute("X-Atmosphere-Transport") == null
        || request.getAttribute("X-Atmosphere-Transport") != null
            && ((String) request.getAttribute("X-Atmosphere-Transport"))
                .equalsIgnoreCase("long-polling")) {
      String userAgent = request.getHeader("User-Agent").toLowerCase();
      if (userAgent != null && userAgent.startsWith("opera") && message instanceof String) {
        StringBuilder sb =
            new StringBuilder("<script id=\"atmosphere_")
                .append(uniqueScriptToken.getAndIncrement())
                .append("\">")
                .append("window.parent.$.atmosphere.streamingCallback")
                .append("('")
                .append(message.toString())
                .append("');</script>");
        message = sb.toString();
        return new BroadcastAction(BroadcastAction.ACTION.CONTINUE, message);
      }
    }
    return new BroadcastAction(BroadcastAction.ACTION.CONTINUE, null);
  }
  /**
   * 登录获取验证码 不用登录
   *
   * @return
   */
  @RequestMapping(value = "/v1.0/verificationcode", method = RequestMethod.GET)
  @ResponseBody
  public ResultJSON getVerificationCode(HttpServletRequest request, HttpServletResponse response) {

    // 返回json的结果对象
    ResultJSON result = new ResultJSON();
    // 异常
    CustomException exception = (CustomException) request.getAttribute(CustomException.request_key);
    // 当前登录用户id
    Long currentUserId = (Long) request.getAttribute("currentUserId");
    // 返回
    Object data = null;

    try {

      data = VerificationCodeGenerator.getCode();
      exception = CustomException.SUCCESS;
    } catch (Exception e) {
      e.printStackTrace();
      exception = CustomException.getCustomExceptionByCode(e.getMessage());
    } finally {
      result.setCode(exception.getCode());
      result.setMessage(exception.getMessage());
      result.setData(data == null ? "" : data);
      result.setSign("");
    }
    return result;
  }
  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView)
      throws Exception {
    Long executeTime = (Long) request.getAttribute(EXECUTE_TIME_ATTRIBUTE_NAME);
    if (executeTime == null) {
      Long startTime = (Long) request.getAttribute(START_TIME_ATTRIBUTE_NAME);
      Long endTime = System.currentTimeMillis();
      executeTime = endTime - startTime;
      request.setAttribute(START_TIME_ATTRIBUTE_NAME, startTime);
    }

    if (modelAndView != null) {
      String viewName = modelAndView.getViewName();
      if (!StringUtils.startsWith(viewName, REDIRECT_VIEW_NAME_PREFIX)) {
        modelAndView.addObject(EXECUTE_TIME_ATTRIBUTE_NAME, executeTime);
      }
    }
    if (logger.isDebugEnabled()) {
      logger.debug("[" + handler + "] executeTime: " + executeTime + "ms");
    }
  }
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws FenixActionException, FenixFilterException {
    try {
      super.execute(mapping, form, request, response);
    } catch (Exception e1) {
      e1.printStackTrace();
    }

    String groupPropertiesCodeString = request.getParameter("groupPropertiesCode");
    Integer groupPropertiesCode = new Integer(groupPropertiesCodeString);
    ISiteComponent shiftsAndGroupsView = new InfoSiteShiftsAndGroups();
    readSiteView(request, shiftsAndGroupsView, null, groupPropertiesCode, null);

    InfoExecutionPeriod infoExecutionPeriod =
        (InfoExecutionPeriod) request.getAttribute(PresentationConstants.EXECUTION_PERIOD);

    InfoExecutionDegree infoExecutionDegree =
        RequestUtils.getExecutionDegreeFromRequest(
            request, infoExecutionPeriod.getInfoExecutionYear());

    Integer curricularYear = (Integer) request.getAttribute("curYear");

    List infoExecutionCourses =
        (List)
            SelectExportExecutionCourse.run(
                infoExecutionDegree, infoExecutionPeriod, curricularYear);
    Collections.sort(infoExecutionCourses, new BeanComparator("nome"));
    request.setAttribute("exeCourseList", infoExecutionCourses);
    return mapping.findForward("sucess");
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // get all zipcodes
    System.out.println("Reached");
    List<Integer> l = new DAOOrderToBillOracle().getAllZipcodes();
    System.out.println("zipcodes" + l.toString());

    request.setAttribute("l", l);

    //
    DAOOrderToBillOracle dest = new DAOOrderToBillOracle();
    System.out.println("order key " + request.getAttribute("orderKey"));
    Order order = dest.getOrderDetails((int) request.getAttribute("orderKey"));

    // ad-hoc
    // Order order = dest.getOrderDetails(1);

    System.out.println("Hey order" + order);

    System.out.println("order cust id" + order.getCustomerId());
    System.out.println("Service Address Id: " + dest.getServiceAddressId(order.getCustomerId()));
    int dzip = dest.getZipcode(dest.getServiceAddressId(order.getCustomerId()));
    System.out.println("dzip " + dzip);
    request.setAttribute("dzip", dzip);

    List<String> ddevice = dest.getDeviceIdsInZipcode(dzip);
    System.out.println("ddevic e ids in zipcode " + ddevice);

    HttpSession hs = request.getSession();
    hs.setAttribute("ddevice", ddevice);
    hs.setAttribute("order", order);

    RequestDispatcher rd = request.getRequestDispatcher("AddOrder.jsp");
    rd.forward(request, response);
  }
Beispiel #7
0
  /**
   * 记录页面错误 错误日志记录
   * [page/eception][username][statusCode][errorMessage][servletName][uri][exceptionName][ip][exception]
   *
   * @param request http请求
   */
  public static void logPageError(HttpServletRequest request) {
    String username = getUsername();

    Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
    String message = (String) request.getAttribute("javax.servlet.error.message");
    String uri = (String) request.getAttribute("javax.servlet.error.request_uri");
    Throwable t = (Throwable) request.getAttribute("javax.servlet.error.exception");

    if (statusCode == null) {
      statusCode = 0;
    }

    StringBuilder s = new StringBuilder();
    s.append(getBlock(t == null ? "page" : "exception"));
    s.append(getBlock(username));
    s.append(getBlock(statusCode));
    s.append(getBlock(message));
    s.append(getBlock(IpUtils.getIpAddr(request)));

    s.append(getBlock(uri));
    s.append(getBlock(request.getHeader("Referer")));
    StringWriter sw = new StringWriter();

    while (t != null) {
      t.printStackTrace(new PrintWriter(sw));
      t = t.getCause();
    }
    s.append(getBlock(sw.toString()));
    getErrorLog().error(s.toString());
  }
  /**
   * 获取文件格式
   *
   * @return
   */
  @RequestMapping(value = "/v1.0/resource/fileFormat", method = RequestMethod.GET)
  @ResponseBody
  public ResultJSON getFileFormat(HttpServletRequest request, HttpServletResponse response) {
    // 返回json的结果对象
    ResultJSON result = new ResultJSON();
    // 异常
    CustomException exception = (CustomException) request.getAttribute(CustomException.request_key);
    // 当前登录用户id
    Long currentUserId = (Long) request.getAttribute("currentUserId");
    // 返回
    Object data = null;

    try {
      if (currentUserId != null && exception == null) {
        long userId = currentUserId;
        data = assetService.getAllFileFormat();
        exception = CustomException.SUCCESS;
      } else {
        exception = CustomException.INVALIDACCESSTOKEN;
      }
    } catch (Exception e) {
      exception = CustomException.getCustomExceptionByCode(e.getMessage());
      // 如果是普通的异常
      if (exception.getStatus() == 500) {
        e.printStackTrace();
      }
    } finally {
      result.setCode(exception.getCode());
      result.setMessage(exception.getMessage());
      result.setData(data == null ? "" : data);
      result.setSign("");
    }
    return result;
  }
Beispiel #9
0
  @Override
  protected void setAttributes(HttpServletRequest request) {
    PortletRequest portletRequest =
        (PortletRequest) request.getAttribute(JavaConstants.JAVAX_PORTLET_REQUEST);

    request.setAttribute("liferay-ui:error:key", _key);
    request.setAttribute("liferay-ui:error:message", _message);
    request.setAttribute("liferay-ui:error:rowBreak", _rowBreak);
    request.setAttribute("liferay-ui:error:translateMessage", String.valueOf(_translateMessage));

    if (SessionErrors.contains(portletRequest, _key)) {
      String errorMarkerKey = (String) request.getAttribute("liferay-ui:error-marker:key");
      String errorMarkerValue = (String) request.getAttribute("liferay-ui:error-marker:value");

      if (Validator.isNotNull(errorMarkerKey) && Validator.isNotNull(errorMarkerValue)) {

        request.setAttribute(errorMarkerKey, errorMarkerValue);

        Object exception = getException(portletRequest);

        if (exception instanceof Exception) {
          request.setAttribute("liferay-ui:error:exception", exception);
        }

        request.setAttribute("liferay-ui:error:focusField", _focusField);
      }
    }
  }
 @RequestMapping(value = "tjlb")
 public String tjlb(Model model, HttpServletRequest request) throws ParseException {
   model.addAttribute("nav", "lb");
   model.addAttribute("nav_on", 2);
   if (null != request.getAttribute("isLogin") && (Boolean) request.getAttribute("isLogin")) {
     model.addAttribute("loginState", 1);
     @SuppressWarnings("unchecked")
     Map<String, Object> user = (Map<String, Object>) request.getSession().getAttribute("user");
     request.setAttribute(
         "userName", user.get("loginName") == null ? "" : user.get("loginName").toString());
     request.setAttribute(
         "userImg",
         user.get("timg") == null
             ? "webviews/common/img/icon_head.jpg"
             : user.get("timg").toString());
     request.setAttribute(
         "userMoney", user.get("ncoin") == null ? "0" : user.get("ncoin").toString());
     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
     Integer i = ToolUtil.compareDate(df.parse(user.get("lastQdTime").toString()).getTime());
     if (i == 0) {
       model.addAttribute("isSign", 1);
     }
   }
   return "/webviews/package/package_content.jsp";
 }
  /**
   * 分页获取我的最近浏览
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/v1.0/resource/userview", method = RequestMethod.GET)
  @ResponseBody
  public ResultJSON getMyViewList(HttpServletRequest request, HttpServletResponse response) {
    // 返回json的结果对象
    ResultJSON result = new ResultJSON();
    // 异常
    CustomException exception = (CustomException) request.getAttribute(CustomException.request_key);
    // 当前登录用户id
    Long currentUserId = (Long) request.getAttribute("currentUserId");
    // 返回
    Object data = null;
    try {
      if (currentUserId != null && exception == null) {
        // 获取文件服务器的访问url
        String resServiceLocal = (String) request.getAttribute("resServiceLocal");
        String currentResPath = (String) request.getAttribute("currentResPath");

        long userId = currentUserId;
        long unifyTypeId = 0;
        int page = 1;
        int prePage = 10;

        String _unifyTypeId = request.getParameter("unifyTypeId");
        String _page = request.getParameter("page");
        String _prePage = request.getParameter("perPage");
        String fileFormat = request.getParameter("fileFormat");
        if (StringUtils.isNotEmpty(_unifyTypeId)) {
          unifyTypeId = Long.parseLong(_unifyTypeId);
        }
        if (StringUtils.isNotEmpty(_page)) {
          page = Integer.parseInt(_page);
        }
        if (StringUtils.isNotEmpty(_prePage)) {
          prePage = Integer.parseInt(_prePage);
        }

        // 获取结果
        PageInfo info =
            userLogService.getMyViewLogFroResource(userId, unifyTypeId, fileFormat, page, prePage);
        Pagination _p = new PageInfoToPagination().transfer(info.getList());
        // 获取缩略图的最终url
        JPrepareContentViewUtil.convertToPurpose_view(
            _p.getList(), resServiceLocal, currentResPath);
        data = _p;
        exception = CustomException.SUCCESS;
      } else {
        exception = CustomException.INVALIDACCESSTOKEN;
      }
    } catch (Exception e) {
      exception = CustomException.getCustomExceptionByCode(e.getMessage());
      // 如果是普通的异常
      e.printStackTrace();
    } finally {
      result.setCode(exception.getCode());
      result.setMessage(exception.getMessage());
      result.setData(data == null ? "" : data);
      result.setSign("");
    }
    return result;
  }
Beispiel #12
0
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
      LOG.debug(String.format("*****Servlet***** - Starting"));

      // HttpUtils.dump(request);

      LOG.debug(String.format("*****Servlet***** - getRequestURL:   %s", request.getRequestURL()));
      LOG.debug(String.format("*****Servlet***** - getRemotePort:   %s", request.getRemotePort()));
      LOG.debug(
          String.format(
              "*****Servlet***** - Authorization:   %s", request.getHeader("Authorization")));
      LOG.debug(
          String.format(
              "*****Servlet***** - SSL Session Id:  %s",
              request.getAttribute("javax.servlet.request.ssl_session_id")));

      X509Certificate[] certs =
          (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate");
      if (certs != null && certs.length > 0) {
        LOG.debug(
            String.format(
                "*****Servlet***** - X509Certificate: %s", certs[0].getSubjectDN().getName()));
      }

      response.setContentType("text/html;charset=utf-8");
      response.setStatus(HttpServletResponse.SC_OK);
      response.getWriter().println("<h1>Hello World Servlet</h1>");

      LOG.debug(String.format("*****Servlet***** - Done"));
    }
  private void deleteAction(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Survey survey = (Survey) request.getAttribute(RequestUtils.SURVEY);

    List<Question> questions = (List<Question>) request.getAttribute(RequestUtils.QUESTIONS);
    List<Language> languages = (List<Language>) request.getAttribute(RequestUtils.LANGUAGES);
    List<AnswerSet> answerSets = (List<AnswerSet>) request.getAttribute(RequestUtils.ANSWER_SETS);

    if (!questions.isEmpty()) {
      EditUtils.addEditUsingKey(request, "surveyCantBeDeletedWithQuestionsMessage");
    }

    if (!languages.isEmpty()) {
      EditUtils.addEditUsingKey(request, "surveyCantBeDeletedWithLanguagesMessage");
    }

    if (!answerSets.isEmpty()) {
      EditUtils.addEditUsingKey(request, "surveyCantBeDeletedWithAnswerSetsMessage");
    }

    if (!EditUtils.hasEdits(request)) {
      survey.setLastUpdateUserId(request.getUserPrincipal().getName());
      SurveyDelete.execute(survey);
    }

    if (!EditUtils.hasEdits(request)) {
      RequestUtils.forwardTo(request, response, ControllerConstants.SURVEYS_REDIRECT);
    } else {
      RequestUtils.forwardTo(request, response, ControllerConstants.SURVEY_UPDATE);
    }
  }
  /**
   * Copied from Tomcat
   *
   * <p>Return the page resource path from the request. For example:
   *
   * <pre class="codeHtml">
   * <span class="blue">http://www.mycorp.com/banking/secure/login.htm</span>  ->  <span class="red">/secure/login.htm</span>
   * </pre>
   *
   * @param request the page servlet request
   * @return the page resource path from the request
   */
  public String getResourcePath(HttpServletRequest request) {
    // Adapted from VelocityViewServlet.handleRequest() method:

    // If we get here from RequestDispatcher.include(), getServletPath()
    // will return the original (wrong) URI requested.  The following
    // special attribute holds the correct path.  See section 8.3 of the
    // Servlet 2.3 specification.

    String path = (String) request.getAttribute("javax.servlet.include.servlet_path");

    // Also take into account the PathInfo stated on
    // SRV.4.4 Request Path Elements.
    String info = (String) request.getAttribute("javax.servlet.include.path_info");

    if (path == null) {
      path = request.getServletPath();
      info = request.getPathInfo();
    }

    if (info != null) {
      path += info;
    }

    return path;
  }
  public ActionForward nextPage(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    DynaActionForm escolherContextoForm = (DynaActionForm) form;

    String nextPage = (String) request.getAttribute(PresentationConstants.NEXT_PAGE);
    if (nextPage == null) {
      nextPage = request.getParameter(PresentationConstants.NEXT_PAGE);
    }

    Integer semestre =
        ((InfoExecutionPeriod) request.getAttribute(PresentationConstants.EXECUTION_PERIOD))
            .getSemester();
    Integer anoCurricular = (Integer) escolherContextoForm.get("curricularYear");

    int index = Integer.parseInt((String) escolherContextoForm.get("index"));

    request.setAttribute("anoCurricular", anoCurricular);
    request.setAttribute("semestre", semestre);

    List infoExecutionDegreeList =
        ReadExecutionDegreesByExecutionYear.run(
            ((InfoExecutionPeriod) request.getAttribute(PresentationConstants.EXECUTION_PERIOD))
                .getInfoExecutionYear());
    List licenciaturas = new ArrayList();
    licenciaturas.add(new LabelValueBean("escolher", ""));
    Collections.sort(infoExecutionDegreeList, new ComparatorByNameForInfoExecutionDegree());
    // ////

    InfoExecutionDegree infoExecutionDegree =
        (InfoExecutionDegree) infoExecutionDegreeList.get(index);

    if (infoExecutionDegree != null) {
      CurricularYearAndSemesterAndInfoExecutionDegree cYSiED =
          new CurricularYearAndSemesterAndInfoExecutionDegree(
              anoCurricular, semestre, infoExecutionDegree);
      request.setAttribute(PresentationConstants.CONTEXT_KEY, cYSiED);

      request.setAttribute(PresentationConstants.CURRICULAR_YEAR_KEY, anoCurricular);
      request.setAttribute(PresentationConstants.CURRICULAR_YEAR_OID, anoCurricular.toString());
      request.setAttribute(PresentationConstants.INFO_EXECUTION_DEGREE_KEY, infoExecutionDegree);
      request.setAttribute(PresentationConstants.EXECUTION_DEGREE, infoExecutionDegree);
      request.setAttribute(
          PresentationConstants.EXECUTION_DEGREE_OID,
          infoExecutionDegree.getExternalId().toString());
    } else {
      return mapping.findForward("Licenciatura execucao inexistente");
    }

    if (nextPage != null) {
      return mapping.findForward(nextPage);
    }

    // TODO : throw a proper exception
    throw new Exception("SomeOne is messing around with the links");
  }
  /** @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    s = HibernateUtils.getSession();

    InventaireClient inventaireClient = new InventaireClient();
    Client client = new Client();
    ArrayList<Client> listC = ServiceClientCortex2i.listObjectToClientCortex2i(s);
    ArrayList<Object> listInventaireo =
        ServiceInventaireClient.listeInventaireClient(s, inventaireClient);
    try {

      ArrayList<InventaireClient> listInventaire =
          ServiceInventaireClient.listeInventaireClientToInventaireClient(listInventaireo);
      request.setAttribute("listI", listInventaire);
    } catch (Exception e) {
      // TODO: handle exception
    }
    request.setAttribute("listC", listC);
    System.out.println(listC);

    request.setAttribute("message", request.getAttribute("message"));
    request.setAttribute("messageR", request.getAttribute("messageR"));
    request.setAttribute("invR", request.getAttribute("invR"));
    request
        .getServletContext()
        .getRequestDispatcher("/GestionInventaire.jsp")
        .forward(request, response);
    s.close();
  }
  /**
   * Method execute
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @return ActionForward
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response) {
    // IdAF idAF = (IdAF) form;// TODO Auto-generated method stub
    try {
      // 把 PAYID 传过来放在SESSION 里
      if (request.getAttribute("payId_num") != null) {
        HttpSession session = request.getSession();
        session.setAttribute("payId_num_session", (String) request.getAttribute("payId_num"));
      }

      IAgentBS agentBS =
          (IAgentBS) BSUtils.getBusinessService("agentBS", this, mapping.getModuleConfig());
      Pagination pagination =
          getPagination(PAGINATION_KEY, request, (String) request.getAttribute("payId_num"));
      PaginationUtils.updatePagination(pagination, request);
      // TB  集合
      List list = agentBS.queryAgentInfoTbList(pagination);
      // TB  数量
      int count = agentBS.queryAgentInfoTbListCount(pagination);

      pagination.setNrOfElements(count);
      AgentInfoQueryTbAF agentInfoQueryTbAF = new AgentInfoQueryTbAF();
      agentInfoQueryTbAF.setList(list);
      request.setAttribute("agentInfoQueryTbAF", agentInfoQueryTbAF);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return mapping.findForward("to_agentInfoQueryTb_show");
  }
  @Test
  public void testRequestAttributesForAccessLog() throws Exception {
    // PREPARE
    FilterDef filterDef = new FilterDef();
    filterDef.addInitParameter("protocolHeader", "x-forwarded-proto");
    filterDef.addInitParameter("remoteIpHeader", "x-my-forwarded-for");
    filterDef.addInitParameter("httpServerPort", "8080");

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRemoteAddr("192.168.0.10");
    request.setHeader("x-my-forwarded-for", "140.211.11.130");
    request.setHeader("x-forwarded-proto", "http");

    // TEST
    HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request);

    // VERIFY
    Assert.assertEquals(
        "org.apache.catalina.AccessLog.ServerPort",
        Integer.valueOf(8080),
        actualRequest.getAttribute(AccessLog.SERVER_PORT_ATTRIBUTE));

    Assert.assertEquals(
        "org.apache.catalina.AccessLog.RemoteAddr",
        "140.211.11.130",
        actualRequest.getAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE));

    Assert.assertEquals(
        "org.apache.catalina.AccessLog.RemoteHost",
        "140.211.11.130",
        actualRequest.getAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE));
  }
  public ActionForward create(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    DynaValidatorForm classForm = (DynaValidatorForm) form;
    String className = (String) classForm.get("className");

    InfoCurricularYear infoCurricularYear =
        (InfoCurricularYear) request.getAttribute(PresentationConstants.CURRICULAR_YEAR);
    InfoExecutionDegree infoExecutionDegree =
        (InfoExecutionDegree) request.getAttribute(PresentationConstants.EXECUTION_DEGREE);
    AcademicInterval academicInterval =
        AcademicInterval.getAcademicIntervalFromResumedString(
            (String) request.getAttribute(PresentationConstants.ACADEMIC_INTERVAL));

    Integer curricularYear = infoCurricularYear.getYear();

    try {
      CriarTurma.run(className, curricularYear, infoExecutionDegree, academicInterval);

    } catch (DomainException e) {
      throw new ExistingActionException("A SchoolClass", e);
    }

    return listClasses(mapping, form, request, response);
  }
  /*
   * (non-Javadoc)
   *
   * @see org.sakaiproject.portal.api.PortalRenderEngine#setupForward(javax.servlet.http.HttpServletRequest,
   *      javax.servlet.http.HttpServletResponse,
   *      org.sakaiproject.tool.api.Placement, java.lang.String)
   */
  public void setupForward(
      HttpServletRequest req, HttpServletResponse res, Placement p, String skin) {

    String headJs = (String) req.getAttribute("sakai.html.head.js");
    String headCssToolBase = (String) req.getAttribute("sakai.html.head.css.base");
    String headCssToolSkin = (String) req.getAttribute("sakai.html.head.css.skin");
    String bodyonload = (String) req.getAttribute("sakai.html.body.onload");
    String customUserCss = generateStyleAbleStyleSheet();
    if (customUserCss != null) {
      customUserCss =
          "<style type=\"text/css\" title=\"StyleAble\">\n" + customUserCss + "</style>\n";
    } else {
      customUserCss = "";
    }
    String styleAbleJs = generateStyleAbleJavaScript();
    if (styleAbleJs != null) {
      styleAbleJs =
          "<script "
              + "type=\"text/javascript\" language=\"JavaScript\">\n"
              + styleAbleJs
              + "\n</script>\n";
      headJs = headJs + styleAbleJs;
      bodyonload = bodyonload + "styleableonload();";
    }
    headCssToolSkin = headCssToolSkin + customUserCss;
    String headCss = headCssToolBase + headCssToolSkin + customUserCss;
    String head = headCss + headJs;

    req.setAttribute("sakai.html.head", head);
    req.setAttribute("sakai.html.head.css", headCss);
    req.setAttribute("sakai.html.head.js", headJs);
    req.setAttribute("sakai.html.head.css.base", headCssToolBase);
    req.setAttribute("sakai.html.head.css.skin", headCssToolSkin);
    req.setAttribute("sakai.html.body.onload", bodyonload);
  }
 @RequestMapping(value = "/login", method = RequestMethod.POST)
 public void login(
     @ModelAttribute("user") User user,
     HttpSession session,
     HttpServletRequest request,
     HttpServletResponse response,
     @RequestParam(value = "userId", required = true) String userId,
     @RequestParam(value = "passwd", required = true) String passwd)
     throws Exception {
   user = this.userService.getUser(userId, passwd);
   PrintWriter pw = response.getWriter();
   if (user != null) {
     Cookie cookie = new Cookie(Constants.BRUSERID, user.getId());
     cookie.setPath("/");
     cookie.setMaxAge(10 * 365 * 24 * 3600);
     response.addCookie(cookie);
     WebContextThreadLocal.setCurrentUser(user);
     LoggerUtil.info(this.getClass(), "当前登录用户为:" + user.getUserName());
     AuthenticateRole.authenticate(request, user, (String) request.getAttribute("userIdRuleReg"));
     request.setAttribute("user", user);
     session.setAttribute("user", user);
     this.userService.flush();
     pw.write(
         "{\"login\" : true ,\"user\":\""
             + user.getUserName()
             + "\",\"isTeacher\":\""
             + request.getAttribute("isTeacher")
             + "\"}");
   } else {
     LoggerUtil.debug(this.getClass(), "用户名或密码错误!");
     pw.write("{\"login\":false}");
   }
   pw.close();
 }
  /**
   * Redirects to the map url
   *
   * @param componentContext
   * @param request
   * @param response
   * @throws Exception
   */
  public void addOverviewMap(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    logger.debug("Adding overview map to request");
    String key = (String) request.getAttribute("key");
    String entityType = (String) request.getAttribute("entityType");

    Float minLatitude = ServletRequestUtils.getFloatParameter(request, "minLatitude");
    Float minLongitude = ServletRequestUtils.getFloatParameter(request, "minLongitude");
    Float maxLatitude = ServletRequestUtils.getFloatParameter(request, "maxLatitude");
    Float maxLongitude = ServletRequestUtils.getFloatParameter(request, "maxLongitude");

    MapContentProvider mapContentProvider =
        (MapContentProvider) getWebAppContext(request).getBean("mapContentProvider");
    if (minLatitude != null
        && minLongitude != null
        && maxLatitude != null
        && maxLongitude != null) {
      BoundingBoxDTO bbDTO =
          new BoundingBoxDTO(minLongitude, minLatitude, maxLongitude, maxLatitude);
      mapContentProvider.addMapContentForEntity(
          request, EntityType.entityTypesByName.get(entityType), key, bbDTO);
    } else {
      mapContentProvider.addMapContentForEntity(
          request, EntityType.entityTypesByName.get(entityType), key);
    }
  }
  /**
   * Translate the SHIB request so that cas renew and/or gateway are set properly before handing off
   * to CAS.
   *
   * @see
   *     edu.internet2.middleware.shibboleth.idp.authn.LoginHandler#login(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @Override
  public void login(HttpServletRequest request, HttpServletResponse response) {
    Boolean force =
        (Boolean) request.getAttribute(ExternalAuthnSystemLoginHandler.FORCE_AUTHN_PARAM);
    if (null == force) {
      force = Boolean.FALSE;
    }
    setSupportsForceAuthentication(force);
    String authnType = (force) ? "&renew=false" : "&renew=true";

    Boolean passive =
        (Boolean) request.getAttribute(ExternalAuthnSystemLoginHandler.PASSIVE_AUTHN_PARAM);
    if (null != passive) {
      setSupportsPassive(passive);
      if (passive) {
        authnType += "&gateway=true";
      }
    }

    try {
      response.sendRedirect(
          response.encodeRedirectURL(casLoginUrl + "?service=" + callbackUrl + authnType));
    } catch (IOException e) {
      logger.error("Unable to redirect to CAS from LoginHandler", e);
    }
  }
  @SuppressWarnings("unchecked")
  public Serializable getAttribute(HttpServletRequest request, String name) {
    // 为了避免同一个请求多次获取缓存session,所以将缓存session保存至request中。
    Map<String, Serializable> session =
        (Map<String, Serializable>) request.getAttribute(CURRENT_SESSION);
    if (session != null) {
      return session.get(name);
    }

    String root = (String) request.getAttribute(CURRENT_SESSION_ID);
    if (root == null) {
      root = RequestUtils.getRequestedSessionId(request);
    }
    if (StringUtils.isBlank(root)) {
      request.setAttribute(CURRENT_SESSION, new HashMap<String, Serializable>());
      return null;
    }
    session = sessionCache.getSession(root);
    if (session != null) {
      request.setAttribute(CURRENT_SESSION_ID, root);
      request.setAttribute(CURRENT_SESSION, session);
      return session.get(name);
    } else {
      return null;
    }
  }
  public static String addListToCart(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);

    String shoppingListId = request.getParameter("shoppingListId");
    String includeChild = request.getParameter("includeChild");
    String prodCatalogId = CatalogWorker.getCurrentCatalogId(request);

    String eventMessage = null;
    try {
      addListToCart(
          delegator,
          dispatcher,
          cart,
          prodCatalogId,
          shoppingListId,
          (includeChild != null),
          true,
          true);
    } catch (IllegalArgumentException e) {
      request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
      return "error";
    }

    if (UtilValidate.isNotEmpty(eventMessage)) {
      request.setAttribute("_EVENT_MESSAGE_", eventMessage);
    }

    return "success";
  }
 @SuppressWarnings("unchecked")
 public void setAttribute(
     HttpServletRequest request, HttpServletResponse response, String name, Serializable value) {
   Map<String, Serializable> session =
       (Map<String, Serializable>) request.getAttribute(CURRENT_SESSION);
   String root;
   if (session == null) {
     root = RequestUtils.getRequestedSessionId(request);
     if (root != null && root.length() == 32) {
       session = sessionCache.getSession(root);
     }
     if (session == null) {
       session = new HashMap<String, Serializable>();
       do {
         root = sessionIdGenerator.get();
       } while (sessionCache.exist(root));
       response.addCookie(createCookie(request, root));
     }
     request.setAttribute(CURRENT_SESSION, session);
     request.setAttribute(CURRENT_SESSION_ID, root);
   } else {
     root = (String) request.getAttribute(CURRENT_SESSION_ID);
     if (root == null) {
       do {
         root = sessionIdGenerator.get();
       } while (sessionCache.exist(root));
       response.addCookie(createCookie(request, root));
       request.setAttribute(CURRENT_SESSION_ID, root);
     }
   }
   session.put(name, value);
   sessionCache.setSession(root, session, sessionTimeout);
 }
  protected AuthnRequest buildAuthnRequest(HttpServletRequest request) throws SSOAgentException {

    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer =
        issuerBuilder.buildObject("urn:oasis:names:tc:SAML:2.0:assertion", "Issuer", "samlp");
    issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId());

    /* NameIDPolicy */
    NameIDPolicyBuilder nameIdPolicyBuilder = new NameIDPolicyBuilder();
    NameIDPolicy nameIdPolicy = nameIdPolicyBuilder.buildObject();
    nameIdPolicy.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
    nameIdPolicy.setSPNameQualifier("Issuer");
    nameIdPolicy.setAllowCreate(true);

    /* AuthnContextClass */
    AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
    AuthnContextClassRef authnContextClassRef =
        authnContextClassRefBuilder.buildObject(
            "urn:oasis:names:tc:SAML:2.0:assertion", "AuthnContextClassRef", "saml");
    authnContextClassRef.setAuthnContextClassRef(
        "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");

    /* AuthnContex */
    RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
    RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);

    DateTime issueInstant = new DateTime();

    /* Creation of AuthRequestObject */
    AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
    AuthnRequest authRequest =
        authRequestBuilder.buildObject(
            "urn:oasis:names:tc:SAML:2.0:protocol", "AuthnRequest", "samlp");

    authRequest.setForceAuthn(ssoAgentConfig.getSAML2().isForceAuthn());
    authRequest.setIsPassive(ssoAgentConfig.getSAML2().isPassiveAuthn());
    authRequest.setIssueInstant(issueInstant);
    authRequest.setProtocolBinding(ssoAgentConfig.getSAML2().getHttpBinding());
    authRequest.setAssertionConsumerServiceURL(ssoAgentConfig.getSAML2().getACSURL());
    authRequest.setIssuer(issuer);
    authRequest.setNameIDPolicy(nameIdPolicy);
    authRequest.setRequestedAuthnContext(requestedAuthnContext);
    authRequest.setID(SSOAgentUtils.createID());
    authRequest.setVersion(SAMLVersion.VERSION_20);
    authRequest.setDestination(ssoAgentConfig.getSAML2().getIdPURL());
    if (request.getAttribute(Extensions.LOCAL_NAME) != null) {
      authRequest.setExtensions((Extensions) request.getAttribute(Extensions.LOCAL_NAME));
    }

    /* Requesting Attributes. This Index value is registered in the IDP */
    if (ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex() != null
        && ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex().trim().length() > 0) {
      authRequest.setAttributeConsumingServiceIndex(
          Integer.parseInt(ssoAgentConfig.getSAML2().getAttributeConsumingServiceIndex()));
    }

    return authRequest;
  }
Beispiel #28
0
  @RequestMapping(value = {"/{login:login;?.*}"})
  // spring3.2.2 bug see http://jinnianshilongnian.iteye.com/blog/1831408
  public String loginForm(HttpServletRequest request, ModelMap model) {
    // 表示退出
    if (!StringUtils.isEmpty(request.getParameter("logout"))) {
      model.addAttribute(
          Constants.MESSAGE, messageSource.getMessage("user.logout.success", null, null));
    }

    // 表示用户删除了 @see org.apache.shiro.web.filter.user.SysUserFilter
    if (!StringUtils.isEmpty(request.getParameter("notfound"))) {
      model.addAttribute(Constants.ERROR, messageSource.getMessage("user.notfound", null, null));
    }

    // 表示用户被管理员强制退出
    if (!StringUtils.isEmpty(request.getParameter("forcelogout"))) {
      model.addAttribute(Constants.ERROR, messageSource.getMessage("user.forcelogout", null, null));
    }

    // 表示用户输入的验证码错误
    if (!StringUtils.isEmpty(request.getParameter("jcaptchaError"))) {
      model.addAttribute(
          Constants.ERROR, messageSource.getMessage("jcaptcha.validate.error", null, null));
    }

    // 表示用户锁定了 @see org.apache.shiro.web.filter.user.SysUserFilter
    if (!StringUtils.isEmpty(request.getParameter("blocked"))) {
      User user = (User) request.getAttribute(Constants.CURRENT_USER);
      String reason = userStatusHistoryService.getLastReason(user);
      model.addAttribute(
          Constants.ERROR, messageSource.getMessage("user.blocked", new Object[] {reason}, null));
    }

    if (!StringUtils.isEmpty(request.getParameter("unknown"))) {
      model.addAttribute(
          Constants.ERROR, messageSource.getMessage("user.unknown.error", null, null));
    }

    // 登录失败了 提取错误消息
    Exception shiroLoginFailureEx =
        (Exception) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
    if (shiroLoginFailureEx != null) {
      model.addAttribute(Constants.ERROR, shiroLoginFailureEx.getMessage());
    }

    // 如果用户直接到登录页面 先退出一下
    // 原因:isAccessAllowed实现是subject.isAuthenticated()---->即如果用户验证通过 就允许访问
    // 这样会导致登录一直死循环
    Subject subject = SecurityUtils.getSubject();
    if ((subject != null) && subject.isAuthenticated()) {
      subject.logout();
    }

    // 如果同时存在错误消息 和 普通消息 只保留错误消息
    if (model.containsAttribute(Constants.ERROR)) {
      model.remove(Constants.MESSAGE);
    }

    return "front/login";
  }
 /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   PrintWriter yazdirici = response.getWriter();
   yazdirici.write(request.getAttribute("degisken").toString());
   yazdirici.write("<br>");
   yazdirici.write(request.getAttribute("degisken1").toString());
 }
  @RequestMapping(value = "/registration.html", method = RequestMethod.GET)
  public String displayRegistration(
      final Model model, final HttpServletRequest request, final HttpServletResponse response)
      throws Exception {

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);

    model.addAttribute(
        "recapatcha_public_key", coreConfiguration.getProperty(Constants.RECAPATCHA_PUBLIC_KEY));

    SecuredShopPersistableCustomer customer = new SecuredShopPersistableCustomer();
    AnonymousCustomer anonymousCustomer =
        (AnonymousCustomer) request.getAttribute(Constants.ANONYMOUS_CUSTOMER);
    if (anonymousCustomer != null) {
      customer.setBilling(anonymousCustomer.getBilling());
    }

    model.addAttribute("customer", customer);

    /** template * */
    StringBuilder template =
        new StringBuilder()
            .append(ControllerConstants.Tiles.Customer.register)
            .append(".")
            .append(store.getStoreTemplate());

    return template.toString();
  }