public String invoke(
      Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response)
      throws EventHandlerException {
    try {
      Map<String, Object> groovyContext = FastMap.newInstance();
      groovyContext.put("request", request);
      groovyContext.put("response", response);
      HttpSession session = request.getSession();
      groovyContext.put("session", session);

      groovyContext.put("dispatcher", request.getAttribute("dispatcher"));
      groovyContext.put("delegator", request.getAttribute("delegator"));
      groovyContext.put("security", request.getAttribute("security"));
      groovyContext.put("locale", UtilHttp.getLocale(request));
      groovyContext.put("timeZone", UtilHttp.getTimeZone(request));
      groovyContext.put("userLogin", session.getAttribute("userLogin"));
      groovyContext.put(
          "parameters",
          UtilHttp.getCombinedMap(
              request,
              UtilMisc.toSet(
                  "delegator", "dispatcher", "security", "locale", "timeZone", "userLogin")));

      Object result = GroovyUtil.runScriptAtLocation(event.path + event.invoke, groovyContext);
      // check the result
      if (result != null && !(result instanceof String)) {
        throw new EventHandlerException(
            "Event did not return a String result, it returned a " + result.getClass().getName());
      }
      return (String) result;
    } catch (Exception e) {
      throw new EventHandlerException("Groovy Event Error", e);
    }
  }
  public static String getCatalogTopCategory(ServletRequest request, String defaultTopCategory) {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Map<String, Object> requestParameters = UtilHttp.getParameterMap(httpRequest);
    String topCatName = null;
    boolean fromSession = false;

    // first see if a new category was specified as a parameter
    topCatName = (String) requestParameters.get("CATALOG_TOP_CATEGORY");
    // if no parameter, try from session
    if (topCatName == null) {
      topCatName = (String) httpRequest.getSession().getAttribute("CATALOG_TOP_CATEGORY");
      if (topCatName != null) fromSession = true;
    }
    // if nothing else, just use a default top category name
    if (topCatName == null) topCatName = defaultTopCategory;
    if (topCatName == null) topCatName = "CATALOG1";

    if (!fromSession) {
      if (Debug.infoOn())
        Debug.logInfo(
            "[CategoryWorker.getCatalogTopCategory] Setting new top category: " + topCatName,
            module);
      httpRequest.getSession().setAttribute("CATALOG_TOP_CATEGORY", topCatName);
    }
    return topCatName;
  }
Beispiel #3
0
  /** Simple event to set the users per-session currency uom value */
  public static String setSessionCurrencyUom(
      HttpServletRequest request, HttpServletResponse response) {
    String currencyUom = request.getParameter("currencyUom");
    if (UtilValidate.isNotEmpty(currencyUom)) {
      // update the session
      UtilHttp.setCurrencyUom(request.getSession(), currencyUom);

      // update the UserLogin object
      GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
      if (userLogin == null) {
        userLogin = (GenericValue) request.getSession().getAttribute("autoUserLogin");
      }

      if (userLogin != null) {
        GenericValue ulUpdate = GenericValue.create(userLogin);
        ulUpdate.set("lastCurrencyUom", currencyUom);
        try {
          ulUpdate.store();
          userLogin.refreshFromCache();
        } catch (GenericEntityException e) {
          Debug.logWarning(e, module);
        }
      }
    }
    return "success";
  }
Beispiel #4
0
  public static String jsonResponseFromRequestAttributes(
      HttpServletRequest request, HttpServletResponse response) {
    // pull out the service response from the request attribute
    Map<String, Object> attrMap = UtilHttp.getJSONAttributeMap(request);

    // create a JSON Object for return
    JSONObject json = JSONObject.fromObject(attrMap);
    writeJSONtoResponse(json, response);

    return "success";
  }
  public static String replaceShoppingListItem(
      HttpServletRequest request, HttpServletResponse response) {
    String quantityStr = request.getParameter("quantity");

    // just call the updateShoppingListItem service
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    Locale locale = UtilHttp.getLocale(request);

    BigDecimal quantity = null;
    try {
      quantity = new BigDecimal(quantityStr);
    } catch (Exception e) {
      // do nothing, just won't pass to service if it is null
    }

    Map<String, Object> serviceInMap = FastMap.newInstance();
    serviceInMap.put("shoppingListId", request.getParameter("shoppingListId"));
    serviceInMap.put("shoppingListItemSeqId", request.getParameter("shoppingListItemSeqId"));
    serviceInMap.put("productId", request.getParameter("add_product_id"));
    serviceInMap.put("userLogin", userLogin);
    if (quantity != null) serviceInMap.put("quantity", quantity);
    Map<String, Object> result = null;
    try {
      result = dispatcher.runSync("updateShoppingListItem", serviceInMap);
    } catch (GenericServiceException e) {
      String errMsg =
          UtilProperties.getMessage(
                  resource_error, "shoppingListEvents.error_calling_update", locale)
              + ": "
              + e.toString();
      request.setAttribute("_ERROR_MESSAGE_", errMsg);
      String errorMsg =
          "Error calling the updateShoppingListItem in handleShoppingListItemVariant: "
              + e.toString();
      Debug.logError(e, errorMsg, module);
      return "error";
    }

    ServiceUtil.getMessages(request, result, "", "", "", "", "", "", "");
    if ("error".equals(result.get(ModelService.RESPONSE_MESSAGE))) {
      return "error";
    } else {
      return "success";
    }
  }
  public static void getRelatedCategories(
      ServletRequest request, String attributeName, boolean limitView) {
    Map<String, Object> requestParameters = UtilHttp.getParameterMap((HttpServletRequest) request);
    String requestId = null;

    requestId =
        UtilFormatOut.checkNull(
            (String) requestParameters.get("catalog_id"),
            (String) requestParameters.get("CATALOG_ID"),
            (String) requestParameters.get("category_id"),
            (String) requestParameters.get("CATEGORY_ID"));

    if (requestId.equals("")) return;
    if (Debug.infoOn())
      Debug.logInfo("[CategoryWorker.getRelatedCategories] RequestID: " + requestId, module);
    getRelatedCategories(request, attributeName, requestId, limitView);
  }
Beispiel #7
0
  /* call run test suite from webtool selenium */
  public static String runTestSuite(HttpServletRequest request, HttpServletResponse response) {
    Map parameters = UtilHttp.getParameterMap(request);
    String para = (String) parameters.get("testSuitePath");
    if (para == null) {
      System.out.println("Error message : Test suite Path  is null");
      return "success";
    }
    if (para.length() == 0) {
      System.out.println("Error message : Test suite Path  is null");
      return "success";
    }
    try {
      URL url = UtilURL.fromResource("seleniumXml.properties");
      if (props == null) {
        props = new Properties();
        initConfig(url);
      }
      SeleniumXml sel = new SeleniumXml();
      File testFile = new File(para.trim());
      if (testFile.exists()) {
        System.err.println(" Argument : " + para.trim());
        System.err.println(" Full absolute path of file : " + testFile.getAbsolutePath());
        System.err.println(" Full canonical path of file : " + testFile.getCanonicalPath());

        sel.testCaseDirectory = sel.getFileDirectory(testFile.getAbsolutePath());
        System.err.println(" testCaseDirectory: " + sel.testCaseDirectory);
        sel.runTest(testFile.getAbsolutePath());
      } else {
        System.err.println("Test File is not exist :" + para.trim());
      }
    } catch (JDOMException jdome) {
      System.out.println(jdome.getMessage());
    } catch (IOException ioe) {
      System.out.println("Error message : " + ioe.getMessage());
    } finally {
      return "success";
    }
  }
 public void renderContainerBegin(
     Appendable writer, Map<String, Object> context, ModelScreenWidget.Container container)
     throws IOException {
   String containerId = container.getId(context);
   String autoUpdateTarget = container.getAutoUpdateTargetExdr(context);
   HttpServletRequest request = (HttpServletRequest) context.get("request");
   String autoUpdateLink = "";
   if (UtilValidate.isNotEmpty(autoUpdateTarget) && UtilHttp.isJavaScriptEnabled(request)) {
     if (UtilValidate.isEmpty(containerId)) {
       containerId = getNextElementId();
     }
     HttpServletResponse response = (HttpServletResponse) context.get("response");
     ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
     RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
     autoUpdateLink = rh.makeLink(request, response, autoUpdateTarget);
   }
   Map<String, Object> parameters = FastMap.newInstance();
   parameters.put("id", containerId);
   parameters.put("style", container.getStyle(context));
   parameters.put("autoUpdateLink", autoUpdateLink);
   parameters.put("autoUpdateInterval", container.getAutoUpdateInterval());
   executeMacro(writer, "renderContainerBegin", parameters);
 }
Beispiel #9
0
  public static ModelTree getTreeFromWebappContext(
      String resourceName, String treeName, HttpServletRequest request)
      throws IOException, SAXException, ParserConfigurationException {
    String webappName = UtilHttp.getApplicationName(request);
    String cacheKey = webappName + "::" + resourceName;

    Map<String, ModelTree> modelTreeMap = treeWebappCache.get(cacheKey);
    if (modelTreeMap == null) {
      synchronized (TreeFactory.class) {
        modelTreeMap = treeWebappCache.get(cacheKey);
        if (modelTreeMap == null) {
          ServletContext servletContext = (ServletContext) request.getAttribute("servletContext");
          Delegator delegator = (Delegator) request.getAttribute("delegator");
          LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");

          URL treeFileUrl = servletContext.getResource(resourceName);
          Document treeFileDoc = UtilXml.readXmlDocument(treeFileUrl, true);
          modelTreeMap = readTreeDocument(treeFileDoc, delegator, dispatcher, cacheKey);
          treeWebappCache.put(cacheKey, modelTreeMap);
        }
      }
    }

    ModelTree modelTree = (ModelTree) modelTreeMap.get(treeName);
    if (modelTree == null) {
      throw new IllegalArgumentException(
          "Could not find tree with name ["
              + treeName
              + "] in webapp resource ["
              + resourceName
              + "] in the webapp ["
              + webappName
              + "]");
    }
    return modelTree;
  }
  public static String editShipmentPlan(HttpServletRequest request, HttpServletResponse response)
      throws GenericEntityException {

    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    Locale locale = UtilHttp.getLocale(request);
    String picklistId;
    String orderId = request.getParameter("orderId");
    List<GenericValue> pickListBin;
    GenericValue pickList;
    GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
    pickListBin = delegator.findByAnd("PicklistBin", UtilMisc.toMap("primaryOrderId", orderId));
    for (GenericValue gv : pickListBin) {
      picklistId = gv.getString("picklistId");
      pickList = delegator.findByPrimaryKey("Picklist", UtilMisc.toMap("picklistId", picklistId));
      String statusId = pickList.getString("statusId");
      if ("PICKLIST_INPUT".equals(statusId)) {
        request.setAttribute(
            "_ERROR_MESSAGE_", "Order is already picked. Please pack through Auto Shipment");
        return "error";
      }
    }
    return "success";
  }
  public static String viewShipmentPackageRouteSegLabelImage(
      HttpServletRequest request, HttpServletResponse response) {

    Delegator delegator = (Delegator) request.getAttribute("delegator");

    String shipmentId = request.getParameter("shipmentId");
    String shipmentRouteSegmentId = request.getParameter("shipmentRouteSegmentId");
    String shipmentPackageSeqId = request.getParameter("shipmentPackageSeqId");

    GenericValue shipmentPackageRouteSeg = null;
    try {
      shipmentPackageRouteSeg =
          delegator.findByPrimaryKey(
              "ShipmentPackageRouteSeg",
              UtilMisc.toMap(
                  "shipmentId",
                  shipmentId,
                  "shipmentRouteSegmentId",
                  shipmentRouteSegmentId,
                  "shipmentPackageSeqId",
                  shipmentPackageSeqId));
    } catch (GenericEntityException e) {
      String errorMsg = "Error looking up ShipmentPackageRouteSeg: " + e.toString();
      Debug.logError(e, errorMsg, module);
      request.setAttribute("_ERROR_MESSAGE_", errorMsg);
      return "error";
    }

    if (shipmentPackageRouteSeg == null) {
      request.setAttribute(
          "_ERROR_MESSAGE_",
          "Could not find ShipmentPackageRouteSeg where shipmentId=["
              + shipmentId
              + "], shipmentRouteSegmentId=["
              + shipmentRouteSegmentId
              + "], shipmentPackageSeqId=["
              + shipmentPackageSeqId
              + "]");
      return "error";
    }

    byte[] bytes = shipmentPackageRouteSeg.getBytes("labelImage");
    if (bytes == null || bytes.length == 0) {
      request.setAttribute(
          "_ERROR_MESSAGE_",
          "The ShipmentPackageRouteSeg was found where shipmentId=["
              + shipmentId
              + "], shipmentRouteSegmentId=["
              + shipmentRouteSegmentId
              + "], shipmentPackageSeqId=["
              + shipmentPackageSeqId
              + "], but there was no labelImage on the value.");
      return "error";
    }

    // TODO: record the image format somehow to make this block nicer.  Right now we're just trying
    // GIF first as a default, then if it doesn't work, trying PNG.
    // It would be nice to store the actual type of the image alongside the image data.
    try {
      UtilHttp.streamContentToBrowser(response, bytes, "image/gif");
    } catch (IOException e1) {
      try {
        UtilHttp.streamContentToBrowser(response, bytes, "image/png");
      } catch (IOException e2) {
        String errorMsg = "Error writing labelImage to OutputStream: " + e2.toString();
        Debug.logError(e2, errorMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errorMsg);
        return "error";
      }
    }

    return "success";
  }
 public static void setTrail(ServletRequest request, String currentCategory) {
   Map<String, Object> requestParameters = UtilHttp.getParameterMap((HttpServletRequest) request);
   String previousCategory = (String) requestParameters.get("pcategory");
   setTrail(request, currentCategory, previousCategory);
 }
Beispiel #13
0
  public static String timeSheetChecker(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();
    Delegator delegator = (Delegator) session.getAttribute("delegator");
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    List<Map<String, Object>> noTimeEntryList = new LinkedList<Map<String, Object>>();
    String partyId = userLogin.getString("partyId");
    Timestamp now = UtilDateTime.nowTimestamp();
    Timestamp weekStart = UtilDateTime.getWeekStart(now);

    if (UtilValidate.isEmpty(delegator)) {
      delegator = (Delegator) request.getAttribute("delegator");
    }

    try {
      // should be scrum team or scrum master.
      EntityConditionList<EntityExpr> exprOrs =
          EntityCondition.makeCondition(
              UtilMisc.toList(
                  EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SCRUM_TEAM"),
                  EntityCondition.makeCondition(
                      "roleTypeId", EntityOperator.EQUALS, "SCRUM_MASTER")),
              EntityOperator.OR);
      EntityConditionList<EntityCondition> exprAnds =
          EntityCondition.makeCondition(
              UtilMisc.toList(
                  exprOrs,
                  EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId)),
              EntityOperator.AND);
      List<GenericValue> partyRoleList =
          EntityQuery.use(delegator).from("PartyRole").where(exprAnds).queryList();
      if (UtilValidate.isNotEmpty(partyRoleList)) {
        List<GenericValue> timesheetList =
            EntityQuery.use(delegator)
                .from("Timesheet")
                .where("partyId", partyId, "statusId", "TIMESHEET_IN_PROCESS")
                .cache(true)
                .queryList();
        if (UtilValidate.isNotEmpty(timesheetList)) {
          for (GenericValue timesheetMap : timesheetList) {
            String timesheetId = timesheetMap.getString("timesheetId");
            Timestamp timesheetDate = timesheetMap.getTimestamp("fromDate");
            // check monday - friday
            for (int i = 0; i < 5; i++) {
              Timestamp realTimeDate = UtilDateTime.addDaysToTimestamp(timesheetDate, i);
              Timestamp nowStartDate = UtilDateTime.getDayStart(now);
              // compare week and compare date
              if ((timesheetDate.compareTo(weekStart) <= 0)
                  && (realTimeDate.compareTo(nowStartDate) < 0)) {
                // check time entry
                List<GenericValue> timeEntryList =
                    timesheetMap.getRelated(
                        "TimeEntry",
                        UtilMisc.toMap(
                            "partyId",
                            partyId,
                            "timesheetId",
                            timesheetId,
                            "fromDate",
                            realTimeDate),
                        null,
                        false);
                // check EmplLeave
                List<GenericValue> emplLeaveList =
                    EntityQuery.use(delegator)
                        .from("EmplLeave")
                        .where("partyId", partyId, "fromDate", realTimeDate)
                        .cache(true)
                        .queryList();
                if (UtilValidate.isEmpty(timeEntryList) && UtilValidate.isEmpty(emplLeaveList)) {
                  Map<String, Object> noEntryMap = new HashMap<String, Object>();
                  noEntryMap.put("timesheetId", timesheetId);
                  noTimeEntryList.add(noEntryMap);
                  break;
                }
              }
            }
          }
        }
      }
    } catch (GenericEntityException EntEx) {
      EntEx.printStackTrace();
      Debug.logError(EntEx.getMessage(), module);
    }
    if (UtilValidate.isNotEmpty(noTimeEntryList)) {
      StringBuilder warningDataBuffer = new StringBuilder();
      int size = noTimeEntryList.size();
      for (Map<String, Object> dataMap : noTimeEntryList) {
        if (--size == 0) {
          warningDataBuffer.append(dataMap.get("timesheetId"));
        } else {
          warningDataBuffer.append(dataMap.get("timesheetId")).append(", ");
        }
        warningDataBuffer.append(dataMap.get("timesheetId"));
      }
      String warningData = warningDataBuffer.toString();
      Debug.logInfo("The following time sheet no time entry: [" + warningData + "]", module);
      request.setAttribute(
          "_ERROR_MESSAGE_",
          UtilProperties.getMessage(
              "scrumUiLabels",
              "ScrumTimesheetWarningMessage",
              UtilMisc.toMap("warningMessage", warningData),
              UtilHttp.getLocale(request)));
    }
    return "success";
  }
  public String invoke(
      Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response)
      throws EventHandlerException {

    if (Debug.infoOn()) {
      Debug.logInfo("In GwtRpcGroovyEventHandler", module);
    }

    String requestPayload = null;

    try {

      requestPayload = GwtRpcPayloadUtil.getRequestPayload(request);

    } catch (IOException ioe) {
      throw new EventHandlerException("Exception while getting requestPayload", ioe);
    } catch (ServletException se) {
      throw new EventHandlerException("Exception while getting requestPayload", se);
    }

    HashMap<String, String> gwtParameters = GwtRpcPayloadUtil.getParameters(requestPayload);
    if (Debug.infoOn()) {
      Debug.logInfo("gwtParameters : " + gwtParameters, module);
    }

    if (null != gwtParameters) {

      HttpSession session = request.getSession();

      Map<String, Object> groovyContext = FastMap.newInstance();
      groovyContext.put("request", request);
      groovyContext.put("response", response);
      groovyContext.put("session", session);
      groovyContext.put("dispatcher", request.getAttribute("dispatcher"));
      groovyContext.put("delegator", request.getAttribute("delegator"));
      groovyContext.put("security", request.getAttribute("security"));
      groovyContext.put("locale", UtilHttp.getLocale(request));
      groovyContext.put("timeZone", UtilHttp.getTimeZone(request));
      groovyContext.put("userLogin", session.getAttribute("userLogin"));

      Map<String, Object> parameters =
          UtilHttp.getCombinedMap(
              request,
              UtilMisc.toSet(
                  "delegator", "dispatcher", "security", "locale", "timeZone", "userLogin"));
      if (Debug.infoOn()) {
        Debug.logInfo("parameters : " + parameters, module);
      }

      Set<String> keys = gwtParameters.keySet();
      Iterator<String> iter = keys.iterator();

      while (iter.hasNext()) {
        String key = iter.next();
        parameters.put(key, gwtParameters.get(key));
      }

      groovyContext.put("parameters", parameters);

      Object result = null;

      try {
        result = GroovyUtil.runScriptAtLocation(event.path + event.invoke, groovyContext);
        if (Debug.infoOn()) {
          Debug.logInfo("groovy script result : " + result, module);
        }
      } catch (GeneralException ge) {
        throw new EventHandlerException("Exception while executing groovy script : ", ge);
      }

      Map<String, Object> resultMap = (Map<String, Object>) result;

      // ServletContext sc = (ServletContext)request.getAttribute("servletContext");
      // RequestDispatcher rd = sc.getRequestDispatcher("/gwtrpc");

      request.setAttribute(GwtRpcPayload.OFBIZ_PAYLOAD, resultMap);
      request.setAttribute(GwtRpcPayload.REQUEST_PAYLOAD, requestPayload);

      /*try {
          rd.forward(request, response);
      } catch(IOException ioe) {
          throw new EventHandlerException("IO Exception while forwarding request to GWT RPC servlet  : ",ioe);
      } catch(ServletException se) {
          throw new EventHandlerException("Servlet Exception while forwarding request to GWT RPC servlet  : ",se);
      }*/

      try {

        GwtRpcServletUtil servletUtil = new GwtRpcServletUtil();
        String responsePayload = servletUtil.invokeServlet(request, response, requestPayload);
        servletUtil.writeResponse(servletContext, request, response, responsePayload);

      } catch (Exception e) {
        Debug.logError(e, "gwt remote servlet invocation failed " + e.getMessage(), module);
        throw new EventHandlerException(e);
      }

    } else {
      throw new EventHandlerException("GWT parameters are null  : " + gwtParameters);
    }

    return "success";
  }
  /**
   * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    long requestStartTime = System.currentTimeMillis();
    RequestHandler requestHandler = this.getRequestHandler();
    HttpSession session = request.getSession();

    // setup DEFAULT chararcter encoding and content type, this will be overridden in the
    // RequestHandler for view rendering
    String charset = getServletContext().getInitParameter("charset");
    if (UtilValidate.isEmpty(charset)) charset = request.getCharacterEncoding();
    if (UtilValidate.isEmpty(charset)) charset = "UTF-8";
    if (Debug.verboseOn())
      Debug.logVerbose(
          "The character encoding of the request is: ["
              + request.getCharacterEncoding()
              + "]. The character encoding we will use for the request and response is: ["
              + charset
              + "]",
          module);

    if (!"none".equals(charset)) {
      request.setCharacterEncoding(charset);
    }

    // setup content type
    String contentType = "text/html";
    if (charset.length() > 0 && !"none".equals(charset)) {
      response.setContentType(contentType + "; charset=" + charset);
      response.setCharacterEncoding(charset);
    } else {
      response.setContentType(contentType);
    }

    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    // Debug.log("Cert Chain: " + request.getAttribute("javax.servlet.request.X509Certificate"),
    // module);

    // set the Entity Engine user info if we have a userLogin
    if (userLogin != null) {
      GenericDelegator.pushUserIdentifier(userLogin.getString("userLoginId"));
    }

    // workaraound if we are in the root webapp
    String webappName = UtilHttp.getApplicationName(request);

    String rname = "";
    if (request.getPathInfo() != null) {
      rname = request.getPathInfo().substring(1);
    }
    if (rname.indexOf('/') > 0) {
      rname = rname.substring(0, rname.indexOf('/'));
    }

    UtilTimer timer = null;
    if (Debug.timingOn()) {
      timer = new UtilTimer();
      timer.setLog(true);
      timer.timerString(
          "["
              + rname
              + "(Domain:"
              + request.getServerName()
              + ")] Request Begun, encoding=["
              + charset
              + "]",
          module);
    }

    // Setup the CONTROL_PATH for JSP dispatching.
    String contextPath = request.getContextPath();
    if (contextPath == null || "/".equals(contextPath)) {
      contextPath = "";
    }
    request.setAttribute("_CONTROL_PATH_", contextPath + request.getServletPath());
    if (Debug.verboseOn())
      Debug.logVerbose("Control Path: " + request.getAttribute("_CONTROL_PATH_"), module);

    // for convenience, and necessity with event handlers, make security and delegator available in
    // the request:
    // try to get it from the session first so that we can have a delegator/dispatcher/security for
    // a certain user if desired
    Delegator delegator = null;
    String delegatorName = (String) session.getAttribute("delegatorName");
    if (UtilValidate.isNotEmpty(delegatorName)) {
      delegator = DelegatorFactory.getDelegator(delegatorName);
    }
    if (delegator == null) {
      delegator = (Delegator) getServletContext().getAttribute("delegator");
    }
    if (delegator == null) {
      Debug.logError("[ControlServlet] ERROR: delegator not found in ServletContext", module);
    } else {
      request.setAttribute("delegator", delegator);
      // always put this in the session too so that session events can use the delegator
      session.setAttribute("delegatorName", delegator.getDelegatorName());
    }

    LocalDispatcher dispatcher = (LocalDispatcher) session.getAttribute("dispatcher");
    if (dispatcher == null) {
      dispatcher = (LocalDispatcher) getServletContext().getAttribute("dispatcher");
    }
    if (dispatcher == null) {
      Debug.logError("[ControlServlet] ERROR: dispatcher not found in ServletContext", module);
    }
    request.setAttribute("dispatcher", dispatcher);

    Authorization authz = (Authorization) session.getAttribute("authz");
    if (authz == null) {
      authz = (Authorization) getServletContext().getAttribute("authz");
    }
    if (authz == null) {
      Debug.logError("[ControlServlet] ERROR: authorization not found in ServletContext", module);
    }
    request.setAttribute("authz", authz); // maybe we should also add the value to 'security'

    Security security = (Security) session.getAttribute("security");
    if (security == null) {
      security = (Security) getServletContext().getAttribute("security");
    }
    if (security == null) {
      Debug.logError("[ControlServlet] ERROR: security not found in ServletContext", module);
    }
    request.setAttribute("security", security);

    request.setAttribute("_REQUEST_HANDLER_", requestHandler);

    ServletContextHashModel ftlServletContext =
        new ServletContextHashModel(this, BeansWrapper.getDefaultInstance());
    request.setAttribute("ftlServletContext", ftlServletContext);

    // setup some things that should always be there
    UtilHttp.setInitialRequestInfo(request);
    VisitHandler.getVisitor(request, response);

    // set the Entity Engine user info if we have a userLogin
    String visitId = VisitHandler.getVisitId(session);
    if (UtilValidate.isNotEmpty(visitId)) {
      GenericDelegator.pushSessionIdentifier(visitId);
    }

    // display details on the servlet objects
    if (Debug.verboseOn()) {
      logRequestInfo(request);
    }

    // some containers call filters on EVERY request, even forwarded ones, so let it know that it
    // came from the control servlet
    request.setAttribute(ContextFilter.FORWARDED_FROM_SERVLET, Boolean.TRUE);

    String errorPage = null;
    try {
      // the ServerHitBin call for the event is done inside the doRequest method
      requestHandler.doRequest(request, response, null, userLogin, delegator);
    } catch (RequestHandlerException e) {
      Throwable throwable = e.getNested() != null ? e.getNested() : e;
      Debug.logError(throwable, "Error in request handler: ", module);
      StringUtil.HtmlEncoder encoder = new StringUtil.HtmlEncoder();
      request.setAttribute("_ERROR_MESSAGE_", encoder.encode(throwable.toString()));
      errorPage = requestHandler.getDefaultErrorPage(request);
    } catch (Exception e) {
      Debug.logError(e, "Error in request handler: ", module);
      StringUtil.HtmlEncoder encoder = new StringUtil.HtmlEncoder();
      request.setAttribute("_ERROR_MESSAGE_", encoder.encode(e.toString()));
      errorPage = requestHandler.getDefaultErrorPage(request);
    }

    // Forward to the JSP
    // if (Debug.infoOn()) Debug.logInfo("[" + rname + "] Event done, rendering page: " + nextPage,
    // module);
    // if (Debug.timingOn()) timer.timerString("[" + rname + "] Event done, rendering page: " +
    // nextPage, module);

    if (errorPage != null) {
      Debug.logError("An error occurred, going to the errorPage: " + errorPage, module);

      RequestDispatcher rd = request.getRequestDispatcher(errorPage);

      // use this request parameter to avoid infinite looping on errors in the error page...
      if (request.getAttribute("_ERROR_OCCURRED_") == null && rd != null) {
        request.setAttribute("_ERROR_OCCURRED_", Boolean.TRUE);
        Debug.logError("Including errorPage: " + errorPage, module);

        // NOTE DEJ20070727 after having trouble with all of these, try to get the page out and as a
        // last resort just send something back
        try {
          rd.include(request, response);
        } catch (Throwable t) {
          Debug.logWarning(
              "Error while trying to send error page using rd.include (will try response.getOutputStream or response.getWriter): "
                  + t.toString(),
              module);

          String errorMessage =
              "ERROR rendering error page ["
                  + errorPage
                  + "], but here is the error text: "
                  + request.getAttribute("_ERROR_MESSAGE_");
          try {
            if (UtilJ2eeCompat.useOutputStreamNotWriter(getServletContext())) {
              response.getOutputStream().print(errorMessage);
            } else {
              response.getWriter().print(errorMessage);
            }
          } catch (Throwable t2) {
            try {
              int errorToSend = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
              Debug.logWarning(
                  "Error while trying to write error message using response.getOutputStream or response.getWriter: "
                      + t.toString()
                      + "; sending error code ["
                      + errorToSend
                      + "], and message ["
                      + errorMessage
                      + "]",
                  module);
              response.sendError(errorToSend, errorMessage);
            } catch (Throwable t3) {
              // wow, still bad... just throw an IllegalStateException with the message and let the
              // servlet container handle it
              throw new IllegalStateException(errorMessage);
            }
          }
        }

      } else {
        if (rd == null) {
          Debug.logError("Could not get RequestDispatcher for errorPage: " + errorPage, module);
        }

        String errorMessage =
            "<html><body>ERROR in error page, (infinite loop or error page not found with name ["
                + errorPage
                + "]), but here is the text just in case it helps you: "
                + request.getAttribute("_ERROR_MESSAGE_")
                + "</body></html>";
        if (UtilJ2eeCompat.useOutputStreamNotWriter(getServletContext())) {
          response.getOutputStream().print(errorMessage);
        } else {
          response.getWriter().print(errorMessage);
        }
      }
    }

    // sanity check: make sure we don't have any transactions in place
    try {
      // roll back current TX first
      if (TransactionUtil.isTransactionInPlace()) {
        Debug.logWarning(
            "*** NOTICE: ControlServlet finished w/ a transaction in place! Rolling back.", module);
        TransactionUtil.rollback();
      }

      // now resume/rollback any suspended txs
      if (TransactionUtil.suspendedTransactionsHeld()) {
        int suspended = TransactionUtil.cleanSuspendedTransactions();
        Debug.logWarning("Resumed/Rolled Back [" + suspended + "] transactions.", module);
      }
    } catch (GenericTransactionException e) {
      Debug.logWarning(e, module);
    }

    // run these two again before the ServerHitBin.countRequest call because on a logout this will
    // end up creating a new visit
    if (response.isCommitted() && request.getSession(false) == null) {
      // response committed and no session, and we can't get a new session, what to do!
      // without a session we can't log the hit, etc; so just do nothing; this should NOT happen
      // much!
      Debug.logError(
          "Error in ControlServlet output where response isCommitted and there is no session (probably because of a logout); not saving ServerHit/Bin information because there is no session and as the response isCommitted we can't get a new one. The output was successful, but we just can't save ServerHit/Bin info.",
          module);
    } else {
      try {
        UtilHttp.setInitialRequestInfo(request);
        VisitHandler.getVisitor(request, response);
        if (requestHandler.trackStats(request)) {
          ServerHitBin.countRequest(
              webappName + "." + rname,
              request,
              requestStartTime,
              System.currentTimeMillis() - requestStartTime,
              userLogin);
        }
      } catch (Throwable t) {
        Debug.logError(
            t,
            "Error in ControlServlet saving ServerHit/Bin information; the output was successful, but can't save this tracking information. The error was: "
                + t.toString(),
            module);
      }
    }
    if (Debug.timingOn())
      timer.timerString(
          "[" + rname + "(Domain:" + request.getServerName() + ")] Request Done", module);

    // sanity check 2: make sure there are no user or session infos in the delegator, ie clear the
    // thread
    GenericDelegator.clearUserIdentifierStack();
    GenericDelegator.clearSessionIdentifierStack();
  }
  /**
   * An HTTP WebEvent handler that logs in a userLogin. This should run before the security check.
   *
   * @param request The HTTP request object for the current JSP or Servlet request.
   * @param response The HTTP response object for the current JSP or Servlet request.
   * @return Return a boolean which specifies whether or not the calling Servlet or JSP should
   *     generate its own content. This allows an event to override the default content.
   */
  public static String login(HttpServletRequest request, HttpServletResponse response) {

    Element rootElement = getRootElement(request);
    String result = "error";
    if (rootElement != null) {
      String className =
          UtilXml.childElementValue(
              rootElement,
              "AuthenticationHandler",
              "org.ofbiz.ldap.openldap.OFBizLdapAuthenticationHandler");
      try {
        Class<?> handlerClass = Class.forName(className);
        InterfaceOFBizAuthenticationHandler authenticationHandler =
            (InterfaceOFBizAuthenticationHandler) handlerClass.newInstance();
        result = authenticationHandler.login(request, response, rootElement);
      } catch (ClassNotFoundException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (InstantiationException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (IllegalAccessException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (NamingException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (Exception e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      }
    }

    if (result.equals("error")) {
      boolean useOFBizLoginWhenFail =
          Boolean.getBoolean(
              UtilXml.childElementValue(rootElement, "UseOFBizLoginWhenLDAPFail", "false"));
      if (useOFBizLoginWhenFail) {
        return LoginWorker.login(request, response);
      }
    }
    return result;
  }
  /**
   * An HTTP WebEvent handler that logs out a userLogin by clearing the session.
   *
   * @param request The HTTP request object for the current request.
   * @param response The HTTP response object for the current request.
   * @return Return a boolean which specifies whether or not the calling request should generate its
   *     own content. This allows an event to override the default content.
   */
  public static String logout(HttpServletRequest request, HttpServletResponse response) {
    // run the before-logout events
    RequestHandler rh = RequestHandler.getRequestHandler(request.getSession().getServletContext());
    rh.runBeforeLogoutEvents(request, response);

    // invalidate the security group list cache
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");

    doBasicLogout(userLogin, request, response);

    Element rootElement = getRootElement(request);

    String result = "error";
    if (rootElement != null) {
      String className =
          UtilXml.childElementValue(
              rootElement,
              "AuthenticationHandler",
              "org.ofbiz.ldap.openldap.OFBizLdapAuthenticationHandler");
      try {
        Class<?> handlerClass = Class.forName(className);
        InterfaceOFBizAuthenticationHandler authenticationHandler =
            (InterfaceOFBizAuthenticationHandler) handlerClass.newInstance();
        result = authenticationHandler.logout(request, response, rootElement);
      } catch (ClassNotFoundException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (InstantiationException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (IllegalAccessException e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      } catch (Exception e) {
        Debug.logError(e, "Error calling userLogin service", module);
        Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
        String errMsg =
            UtilProperties.getMessage(
                resourceWebapp,
                "loginevents.following_error_occurred_during_login",
                messageMap,
                UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
      }
    }

    if (request.getAttribute("_AUTO_LOGIN_LOGOUT_") == null) {
      return autoLoginCheck(request, response);
    }
    return result;
  }
Beispiel #18
0
  public static Map<String, Object> payPalCheckoutUpdate(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");

    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);

    String token = (String) paramMap.get("TOKEN");
    WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token));
    ShoppingCart cart = null;
    if (weakCart != null) {
      cart = weakCart.get();
    }
    if (cart == null) {
      Debug.logError("Could locate the ShoppingCart for token " + token, module);
      return ServiceUtil.returnSuccess();
    }
    // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll
    // create one and
    // then delete once we're done, now is not the time to worry about updating everything
    String contactMechId = null;
    Map<String, Object> inMap = FastMap.newInstance();
    inMap.put("address1", paramMap.get("SHIPTOSTREET"));
    inMap.put("address2", paramMap.get("SHIPTOSTREET2"));
    inMap.put("city", paramMap.get("SHIPTOCITY"));
    String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY");
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator);
    if (countryGeoId == null) {
      return ServiceUtil.returnSuccess();
    }
    inMap.put("countryGeoId", countryGeoId);
    inMap.put(
        "stateProvinceGeoId",
        parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator));
    inMap.put("postalCode", paramMap.get("SHIPTOZIP"));

    try {
      GenericValue userLogin =
          EntityQuery.use(delegator)
              .from("UserLogin")
              .where("userLoginId", "system")
              .cache()
              .queryOne();
      inMap.put("userLogin", userLogin);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }
    boolean beganTransaction = false;
    Transaction parentTransaction = null;
    try {
      parentTransaction = TransactionUtil.suspend();
      beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
      Debug.logError(e1, module);
    }
    try {
      Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap);
      contactMechId = (String) outMap.get("contactMechId");
    } catch (GenericServiceException e) {
      Debug.logError(e.getMessage(), module);
      return ServiceUtil.returnSuccess();
    }
    try {
      TransactionUtil.commit(beganTransaction);
      if (parentTransaction != null) TransactionUtil.resume(parentTransaction);
    } catch (GenericTransactionException e) {
      Debug.logError(e, module);
    }
    // clone the cart so we can modify it temporarily
    CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
    String oldShipAddress = cart.getShippingContactMechId();
    coh.setCheckOutShippingAddress(contactMechId);
    ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0);
    int line = 0;
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "CallbackResponse");

    for (GenericValue shipMethod : estWrapper.getShippingMethods()) {
      BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod);
      // Check that we have a valid estimate (allowing zero value estimates for now)
      if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) {
        continue;
      }
      cart.setAllShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId"));
      cart.setAllCarrierPartyId(shipMethod.getString("partyId"));
      try {
        coh.calcAndAddTax();
      } catch (GeneralException e) {
        Debug.logError(e, module);
        continue;
      }
      String estimateLabel =
          shipMethod.getString("partyId") + " - " + shipMethod.getString("description");
      encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel);
      encoder.add(
          "L_SHIPPINGOPTIONAMOUNT" + line,
          estimate.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
      // Just make this first one default for now
      encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false");
      encoder.add(
          "L_TAXAMT" + line,
          cart.getTotalSalesTax().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
      line++;
    }
    String responseMsg = null;
    try {
      responseMsg = encoder.encode();
    } catch (PayPalException e) {
      Debug.logError(e, module);
    }
    if (responseMsg != null) {
      try {
        response.setContentLength(responseMsg.getBytes("UTF-8").length);
      } catch (UnsupportedEncodingException e) {
        Debug.logError(e, module);
      }

      try {
        Writer writer = response.getWriter();
        writer.write(responseMsg);
        writer.close();
      } catch (IOException e) {
        Debug.logError(e, module);
      }
    }

    // Remove the temporary ship address
    try {
      GenericValue postalAddress =
          EntityQuery.use(delegator)
              .from("PostalAddress")
              .where("contactMechId", contactMechId)
              .queryOne();
      postalAddress.remove();
      GenericValue contactMech =
          EntityQuery.use(delegator)
              .from("ContactMech")
              .where("contactMechId", contactMechId)
              .queryOne();
      contactMech.remove();
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }
    coh.setCheckOutShippingAddress(oldShipAddress);
    return ServiceUtil.returnSuccess();
  }
  protected void renderScreenletPaginateMenu(
      Appendable writer, Map<String, Object> context, ModelScreenWidget.Form form)
      throws IOException {
    HttpServletResponse response = (HttpServletResponse) context.get("response");
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    ModelForm modelForm = form.getModelForm(context);
    modelForm.runFormActions(context);
    modelForm.preparePager(context);
    String targetService = modelForm.getPaginateTarget(context);
    if (targetService == null) {
      targetService = "${targetService}";
    }

    // get the parametrized pagination index and size fields
    int paginatorNumber = WidgetWorker.getPaginatorNumber(context);
    String viewIndexParam = modelForm.getMultiPaginateIndexField(context);
    String viewSizeParam = modelForm.getMultiPaginateSizeField(context);

    int viewIndex = modelForm.getViewIndex(context);
    int viewSize = modelForm.getViewSize(context);
    int listSize = modelForm.getListSize(context);

    int highIndex = modelForm.getHighIndex(context);
    int actualPageSize = modelForm.getActualPageSize(context);

    // if this is all there seems to be (if listSize < 0, then size is unknown)
    if (actualPageSize >= listSize && listSize >= 0) return;

    // needed for the "Page" and "rows" labels
    Map<String, String> uiLabelMap = UtilGenerics.cast(context.get("uiLabelMap"));
    String ofLabel = "";
    if (uiLabelMap == null) {
      Debug.logWarning("Could not find uiLabelMap in context", module);
    } else {
      ofLabel = uiLabelMap.get("CommonOf");
      ofLabel = ofLabel.toLowerCase();
    }

    // for legacy support, the viewSizeParam is VIEW_SIZE and viewIndexParam is VIEW_INDEX when the
    // fields are "viewSize" and "viewIndex"
    if (viewIndexParam.equals("viewIndex" + "_" + paginatorNumber))
      viewIndexParam = "VIEW_INDEX" + "_" + paginatorNumber;
    if (viewSizeParam.equals("viewSize" + "_" + paginatorNumber))
      viewSizeParam = "VIEW_SIZE" + "_" + paginatorNumber;

    ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
    RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");

    Map<String, Object> inputFields = UtilGenerics.toMap(context.get("requestParameters"));
    // strip out any multi form fields if the form is of type multi
    if (modelForm.getType().equals("multi")) {
      inputFields = UtilHttp.removeMultiFormParameters(inputFields);
    }
    String queryString = UtilHttp.urlEncodeArgs(inputFields);
    // strip legacy viewIndex/viewSize params from the query string
    queryString = UtilHttp.stripViewParamsFromQueryString(queryString, "" + paginatorNumber);
    // strip parametrized index/size params from the query string
    HashSet<String> paramNames = new HashSet<String>();
    paramNames.add(viewIndexParam);
    paramNames.add(viewSizeParam);
    queryString = UtilHttp.stripNamedParamsFromQueryString(queryString, paramNames);

    String anchor = "";
    String paginateAnchor = modelForm.getPaginateTargetAnchor();
    if (paginateAnchor != null) anchor = "#" + paginateAnchor;

    // preparing the link text, so that later in the code we can reuse this and just add the
    // viewIndex
    String prepLinkText = "";
    prepLinkText = targetService;
    if (prepLinkText.indexOf("?") < 0) {
      prepLinkText += "?";
    } else if (!prepLinkText.endsWith("?")) {
      prepLinkText += "&amp;";
    }
    if (!UtilValidate.isEmpty(queryString) && !queryString.equals("null")) {
      prepLinkText += queryString + "&amp;";
    }
    prepLinkText += viewSizeParam + "=" + viewSize + "&amp;" + viewIndexParam + "=";

    String linkText;

    // The current screenlet title bar navigation syling requires rendering
    // these links in reverse order
    // Last button
    String lastLinkUrl = "";
    if (highIndex < listSize) {
      int page = (listSize / viewSize);
      linkText = prepLinkText + page + anchor;
      lastLinkUrl = rh.makeLink(request, response, linkText);
    }
    String nextLinkUrl = "";
    if (highIndex < listSize) {
      linkText = prepLinkText + (viewIndex + 1) + anchor;
      // - make the link
      nextLinkUrl = rh.makeLink(request, response, linkText);
    }
    String previousLinkUrl = "";
    if (viewIndex > 0) {
      linkText = prepLinkText + (viewIndex - 1) + anchor;
      previousLinkUrl = rh.makeLink(request, response, linkText);
    }
    String firstLinkUrl = "";
    if (viewIndex > 0) {
      linkText = prepLinkText + 0 + anchor;
      firstLinkUrl = rh.makeLink(request, response, linkText);
    }

    Map<String, Object> parameters = FastMap.newInstance();
    parameters.put("lowIndex", modelForm.getLowIndex(context));
    parameters.put("actualPageSize", actualPageSize);
    parameters.put("ofLabel", ofLabel);
    parameters.put("listSize", listSize);
    parameters.put("paginateLastStyle", modelForm.getPaginateLastStyle());
    parameters.put("lastLinkUrl", lastLinkUrl);
    parameters.put("paginateLastLabel", modelForm.getPaginateLastLabel(context));
    parameters.put("paginateNextStyle", modelForm.getPaginateNextStyle());
    parameters.put("nextLinkUrl", nextLinkUrl);
    parameters.put("paginateNextLabel", modelForm.getPaginateNextLabel(context));
    parameters.put("paginatePreviousStyle", modelForm.getPaginatePreviousStyle());
    parameters.put("paginatePreviousLabel", modelForm.getPaginatePreviousLabel(context));
    parameters.put("previousLinkUrl", previousLinkUrl);
    parameters.put("paginateFirstStyle", modelForm.getPaginateFirstStyle());
    parameters.put("paginateFirstLabel", modelForm.getPaginateFirstLabel(context));
    parameters.put("firstLinkUrl", firstLinkUrl);
    executeMacro(writer, "renderScreenletPaginateMenu", parameters);
  }
  public void renderScreenletBegin(
      Appendable writer,
      Map<String, Object> context,
      boolean collapsed,
      ModelScreenWidget.Screenlet screenlet)
      throws IOException {
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");
    boolean javaScriptEnabled = UtilHttp.isJavaScriptEnabled(request);
    ModelScreenWidget.Menu tabMenu = screenlet.getTabMenu();
    if (tabMenu != null) {
      tabMenu.renderWidgetString(writer, context, this);
    }

    String title = screenlet.getTitle(context);
    boolean collapsible = screenlet.collapsible();
    ModelScreenWidget.Menu navMenu = screenlet.getNavigationMenu();
    ModelScreenWidget.Form navForm = screenlet.getNavigationForm();
    String expandToolTip = "";
    String collapseToolTip = "";
    String fullUrlString = "";
    String menuString = "";
    boolean showMore = false;
    if (UtilValidate.isNotEmpty(title) || navMenu != null || navForm != null || collapsible) {
      showMore = true;
      if (collapsible) {
        this.getNextElementId();
        Map<String, Object> uiLabelMap = UtilGenerics.checkMap(context.get("uiLabelMap"));
        Map<String, Object> paramMap = UtilGenerics.checkMap(context.get("requestParameters"));
        Map<String, Object> requestParameters = new HashMap<String, Object>(paramMap);
        if (uiLabelMap != null) {
          expandToolTip = (String) uiLabelMap.get("CommonExpand");
          collapseToolTip = (String) uiLabelMap.get("CommonCollapse");
        }
        if (!javaScriptEnabled) {
          requestParameters.put(
              screenlet.getPreferenceKey(context) + "_collapsed", collapsed ? "false" : "true");
          String queryString = UtilHttp.urlEncodeArgs(requestParameters);
          fullUrlString = request.getRequestURI() + "?" + queryString;
        }
      }
      if (!collapsed) {
        StringWriter sb = new StringWriter();
        if (navMenu != null) {
          MenuStringRenderer savedRenderer = (MenuStringRenderer) context.get("menuStringRenderer");
          MenuStringRenderer renderer = new ScreenletMenuRenderer(request, response);
          context.put("menuStringRenderer", renderer);
          navMenu.renderWidgetString(sb, context, this);
          context.put("menuStringRenderer", savedRenderer);
        } else if (navForm != null) {
          renderScreenletPaginateMenu(sb, context, navForm);
        }
        menuString = sb.toString();
      }
    }

    Map<String, Object> parameters = FastMap.newInstance();
    parameters.put("id", screenlet.getId(context));
    parameters.put("title", title);
    parameters.put("collapsible", collapsible);
    parameters.put("saveCollapsed", screenlet.saveCollapsed());
    parameters.put("collapsibleAreaId", screenlet.getId(context) + "_col");
    parameters.put("expandToolTip", expandToolTip);
    parameters.put("collapseToolTip", collapseToolTip);
    parameters.put("fullUrlString", fullUrlString);
    parameters.put("padded", screenlet.padded());
    parameters.put("menuString", menuString);
    parameters.put("showMore", showMore);
    parameters.put("collapsed", collapsed);
    parameters.put("javaScriptEnabled", javaScriptEnabled);
    executeMacro(writer, "renderScreenletBegin", parameters);
  }
  public void renderNextPrev(Appendable writer, Map<String, Object> context) throws IOException {
    String targetService = this.getPaginateTarget(context);
    if (targetService == null) {
      targetService = "${targetService}";
    }

    Map<String, Object> inputFields = UtilGenerics.checkMap(context.get("requestParameters"));
    Map<String, Object> queryStringMap = UtilGenerics.toMap(context.get("queryStringMap"));
    if (UtilValidate.isNotEmpty(queryStringMap)) {
      inputFields.putAll(queryStringMap);
    }

    String queryString = UtilHttp.urlEncodeArgs(inputFields);
    int paginatorNumber = this.getPaginatorNumber(context);
    queryString = UtilHttp.stripViewParamsFromQueryString(queryString, "" + paginatorNumber);

    if (UtilValidate.isEmpty(targetService)) {
      Debug.logWarning("TargetService is empty.", module);
      return;
    }

    int viewIndex = -1;
    try {
      viewIndex = ((Integer) context.get("viewIndex")).intValue();
    } catch (Exception e) {
      viewIndex = 0;
    }

    int viewSize = -1;
    try {
      viewSize = ((Integer) context.get("viewSize")).intValue();
    } catch (Exception e) {
      viewSize = this.getViewSize();
    }

    int listSize = -1;
    try {
      listSize = this.getListSize();
    } catch (Exception e) {
      listSize = -1;
    }

    /*
    int highIndex = -1;
    try {
        highIndex = modelForm.getHighIndex();
    } catch (Exception e) {
        highIndex = 0;
    }

    int lowIndex = -1;
    try {
        lowIndex = modelForm.getLowIndex();
    } catch (Exception e) {
        lowIndex = 0;
    }
     */

    int lowIndex = viewIndex * viewSize;
    int highIndex = (viewIndex + 1) * viewSize;
    int actualPageSize = this.getActualPageSize();
    // if this is all there seems to be (if listSize < 0, then size is unknown)
    if (actualPageSize >= listSize && listSize > 0) {
      return;
    }

    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");

    ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
    RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");

    writer.append("<table border=\"0\" width=\"100%\" cellpadding=\"2\">\n");
    writer.append("  <tr>\n");
    writer.append("    <td align=\"right\">\n");
    writer.append("      <b>\n");
    if (viewIndex > 0) {
      writer.append(" <a href=\"");
      StringBuilder linkText = new StringBuilder(targetService);
      if (linkText.indexOf("?") < 0) linkText.append("?");
      else linkText.append("&amp;");
      // if (queryString != null && !queryString.equals("null")) linkText += queryString + "&";
      if (UtilValidate.isNotEmpty(queryString)) {
        linkText.append(queryString).append("&amp;");
      }
      linkText
          .append("VIEW_SIZE_" + paginatorNumber + "=")
          .append(viewSize)
          .append("&amp;VIEW_INDEX_" + paginatorNumber + "=")
          .append(viewIndex - 1)
          .append("\"");

      // make the link
      writer.append(rh.makeLink(request, response, linkText.toString(), false, false, false));
      String previous =
          UtilProperties.getMessage(
              "CommonUiLabels", "CommonPrevious", (Locale) context.get("locale"));
      writer.append(" class=\"buttontext\">[").append(previous).append("]</a>\n");
    }
    if (listSize > 0) {
      Map<String, Integer> messageMap =
          UtilMisc.toMap(
              "lowCount",
              Integer.valueOf(lowIndex + 1),
              "highCount",
              Integer.valueOf(lowIndex + actualPageSize),
              "total",
              Integer.valueOf(listSize));
      String commonDisplaying =
          UtilProperties.getMessage(
              "CommonUiLabels", "CommonDisplaying", messageMap, (Locale) context.get("locale"));
      writer.append(" <span class=\"tabletext\">").append(commonDisplaying).append("</span> \n");
    }
    if (highIndex < listSize) {
      writer.append(" <a href=\"");
      StringBuilder linkText = new StringBuilder(targetService);
      if (linkText.indexOf("?") < 0) linkText.append("?");
      else linkText.append("&amp;");
      if (UtilValidate.isNotEmpty(queryString)) {
        linkText.append(queryString).append("&amp;");
      }
      linkText
          .append("VIEW_SIZE_" + paginatorNumber + "=")
          .append(viewSize)
          .append("&amp;VIEW_INDEX_" + paginatorNumber + "=")
          .append(viewIndex + 1)
          .append("\"");

      // make the link
      writer.append(rh.makeLink(request, response, linkText.toString(), false, false, false));
      String next =
          UtilProperties.getMessage("CommonUiLabels", "CommonNext", (Locale) context.get("locale"));
      writer.append(" class=\"buttontext\">[").append(next).append("]</a>\n");
    }
    writer.append("      </b>\n");
    writer.append("    </td>\n");
    writer.append("  </tr>\n");
    writer.append("</table>\n");
  }
Beispiel #22
0
  public static void buildHyperlinkUrl(
      Appendable externalWriter,
      String target,
      String targetType,
      Map<String, String> parameterMap,
      String prefix,
      boolean fullPath,
      boolean secure,
      boolean encode,
      HttpServletRequest request,
      HttpServletResponse response,
      Map<String, Object> context)
      throws IOException {

    // We may get an encoded request like:
    // &#47;projectmgr&#47;control&#47;EditTaskContents&#63;workEffortId&#61;10003
    // Try to reducing a possibly encoded string down to its simplest form:
    // /projectmgr/control/EditTaskContents?workEffortId=10003
    // This step make sure the following appending externalLoginKey operation to work correctly
    String localRequestName = StringEscapeUtils.unescapeHtml(target);

    localRequestName = UtilHttp.encodeAmpersands(localRequestName);
    Appendable localWriter = new StringWriter();

    if ("intra-app".equals(targetType)) {
      if (request != null && response != null) {
        ServletContext servletContext = request.getSession().getServletContext();
        RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_");
        externalWriter.append(
            rh.makeLink(request, response, "/" + localRequestName, fullPath, secure, encode));
      } else if (prefix != null) {
        externalWriter.append(prefix);
        externalWriter.append(localRequestName);
      } else {
        externalWriter.append(localRequestName);
      }
    } else if ("inter-app".equals(targetType)) {
      String fullTarget = localRequestName;
      localWriter.append(fullTarget);
      String externalLoginKey = (String) request.getAttribute("externalLoginKey");
      if (UtilValidate.isNotEmpty(externalLoginKey)) {
        if (fullTarget.indexOf('?') == -1) {
          localWriter.append('?');
        } else {
          localWriter.append("&amp;");
        }
        localWriter.append("externalLoginKey=");
        localWriter.append(externalLoginKey);
      }
    } else if ("content".equals(targetType)) {
      appendContentUrl(localWriter, localRequestName, request);
    } else if ("plain".equals(targetType)) {
      localWriter.append(localRequestName);
    } else {
      localWriter.append(localRequestName);
    }

    if (UtilValidate.isNotEmpty(parameterMap)) {
      String localUrl = localWriter.toString();
      externalWriter.append(localUrl);
      boolean needsAmp = true;
      if (localUrl.indexOf('?') == -1) {
        externalWriter.append('?');
        needsAmp = false;
      }

      for (Map.Entry<String, String> parameter : parameterMap.entrySet()) {
        String parameterValue = null;
        if (parameter.getValue() instanceof String) {
          parameterValue = parameter.getValue();
        } else {
          Object parameterObject = parameter.getValue();

          // skip null values
          if (parameterObject == null) continue;

          if (parameterObject instanceof String[]) {
            // it's probably a String[], just get the first value
            String[] parameterArray = (String[]) parameterObject;
            parameterValue = parameterArray[0];
            Debug.logInfo(
                "Found String array value for parameter ["
                    + parameter.getKey()
                    + "], using first value: "
                    + parameterValue,
                module);
          } else {
            // not a String, and not a String[], just use toString
            parameterValue = parameterObject.toString();
          }
        }

        if (needsAmp) {
          externalWriter.append("&amp;");
        } else {
          needsAmp = true;
        }
        externalWriter.append(parameter.getKey());
        externalWriter.append('=');
        StringUtil.SimpleEncoder simpleEncoder =
            (StringUtil.SimpleEncoder) context.get("simpleEncoder");
        if (simpleEncoder != null && parameterValue != null) {
          externalWriter.append(
              simpleEncoder.encode(
                  URLEncoder.encode(parameterValue, Charset.forName("UTF-8").displayName())));
        } else {
          externalWriter.append(parameterValue);
        }
      }
    } else {
      externalWriter.append(localWriter.toString());
    }
  }
  protected static Element getRootElement(HttpServletRequest request) {
    if (Debug.infoOn()) {
      Debug.log("Applet config file: " + ldapConfig);
    }
    File configFile = new File(ldapConfig);
    FileInputStream configFileIS = null;
    Element rootElement = null;
    try {
      configFileIS = new FileInputStream(configFile);
      Document configDoc =
          UtilXml.readXmlDocument(configFileIS, "LDAP configuration file " + ldapConfig);
      rootElement = configDoc.getDocumentElement();
    } catch (FileNotFoundException e) {
      Debug.logError(e, "Error calling userLogin service", module);
      Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
      String errMsg =
          UtilProperties.getMessage(
              resourceWebapp,
              "loginevents.following_error_occurred_during_login",
              messageMap,
              UtilHttp.getLocale(request));
      request.setAttribute("_ERROR_MESSAGE_", errMsg);
    } catch (SAXException e) {
      Debug.logError(e, "Error calling userLogin service", module);
      Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
      String errMsg =
          UtilProperties.getMessage(
              resourceWebapp,
              "loginevents.following_error_occurred_during_login",
              messageMap,
              UtilHttp.getLocale(request));
      request.setAttribute("_ERROR_MESSAGE_", errMsg);
    } catch (ParserConfigurationException e) {
      Debug.logError(e, "Error calling userLogin service", module);
      Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
      String errMsg =
          UtilProperties.getMessage(
              resourceWebapp,
              "loginevents.following_error_occurred_during_login",
              messageMap,
              UtilHttp.getLocale(request));
      request.setAttribute("_ERROR_MESSAGE_", errMsg);
    } catch (IOException e) {
      Debug.logError(e, "Error calling userLogin service", module);
      Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
      String errMsg =
          UtilProperties.getMessage(
              resourceWebapp,
              "loginevents.following_error_occurred_during_login",
              messageMap,
              UtilHttp.getLocale(request));
      request.setAttribute("_ERROR_MESSAGE_", errMsg);
    } finally {
      if (configFileIS != null) {
        try {
          configFileIS.close();
        } catch (IOException e) {
        }
      }
    }

    return rootElement;
  }
  public void render(
      String name,
      String page,
      String info,
      String contentType,
      String encoding,
      HttpServletRequest request,
      HttpServletResponse response)
      throws ViewHandlerException {
    // some containers call filters on EVERY request, even forwarded ones,
    // so let it know that it came from the control servlet

    if (request == null) {
      throw new ViewHandlerException(
          "The HttpServletRequest object was null, how did that happen?");
    }
    if (UtilValidate.isEmpty(page)) {
      throw new ViewHandlerException("View page was null or empty, but must be specified");
    }
    if (UtilValidate.isEmpty(info)) {
      Debug.logInfo(
          "View info string was null or empty, (optionally used to specify an Entity that is mapped to the Entity Engine datasource that the report will use).",
          module);
    }

    // tell the ContextFilter we are forwarding
    request.setAttribute(ContextFilter.FORWARDED_FROM_SERVLET, Boolean.valueOf(true));
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    if (delegator == null) {
      throw new ViewHandlerException("The delegator object was null, how did that happen?");
    }

    try {
      JasperReport report = (JasperReport) jasperReportsCompiledCache.get(page);
      if (report == null) {
        synchronized (this) {
          report = (JasperReport) jasperReportsCompiledCache.get(page);
          if (report == null) {
            InputStream is = context.getResourceAsStream(page);
            report = JasperCompileManager.compileReport(is);
            jasperReportsCompiledCache.put(page, report);
          }
        }
      }

      response.setContentType("application/xls");

      Map parameters = (Map) request.getAttribute("jrParameters");
      if (parameters == null) {
        parameters = UtilHttp.getParameterMap(request);
      }

      JRDataSource jrDataSource = (JRDataSource) request.getAttribute("jrDataSource");
      JasperPrint jp = null;
      if (jrDataSource == null) {
        String datasourceName = delegator.getEntityHelperName(info);
        if (UtilValidate.isNotEmpty(datasourceName)) {
          Debug.logInfo(
              "Filling report with connection from datasource: " + datasourceName, module);
          jp =
              JasperFillManager.fillReport(
                  report, parameters, ConnectionFactory.getConnection(datasourceName));
        } else {
          Debug.logInfo("Filling report with an empty JR datasource", module);
          jp = JasperFillManager.fillReport(report, parameters, new JREmptyDataSource());
        }
      } else {
        Debug.logInfo("Filling report with a passed in jrDataSource", module);
        jp = JasperFillManager.fillReport(report, parameters, jrDataSource);
      }

      if (jp.getPages().size() < 1) {
        throw new ViewHandlerException("Report is Empty (no results?)");
      } else {
        Debug.logInfo("Got report, there are " + jp.getPages().size() + " pages.", module);
      }
      JExcelApiExporter exporter = new JExcelApiExporter();
      exporter.setParameter(JExcelApiExporterParameter.JASPER_PRINT, jp);
      exporter.setParameter(JExcelApiExporterParameter.OUTPUT_STREAM, response.getOutputStream());
      exporter.exportReport();

    } catch (IOException ie) {
      throw new ViewHandlerException("IO Error in report", ie);
    } catch (java.sql.SQLException e) {
      throw new ViewHandlerException("Database error while running report", e);
    } catch (Exception e) {
      throw new ViewHandlerException("Error in report", e);
      // } catch (ServletException se) {
      // throw new ViewHandlerException("Error in region", se.getRootCause());
    }
  }
  /**
   * An HTTP WebEvent handler that checks to see is a userLogin is logged in. If not, the user is
   * forwarded to the login page.
   *
   * @param request The HTTP request object for the current JSP or Servlet request.
   * @param response The HTTP response object for the current JSP or Servlet request.
   * @return String
   */
  public static String checkLogin(HttpServletRequest request, HttpServletResponse response) {
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    // anonymous shoppers are not logged in
    if (userLogin != null && "anonymous".equals(userLogin.getString("userLoginId"))) {
      userLogin = null;
    }

    // user is logged in; check to see if they have globally logged out if not
    // check if they have permission for this login attempt; if not log them out
    if (userLogin != null) {
      Element rootElement = getRootElement(request);
      boolean hasLdapLoggedOut = false;
      if (rootElement != null) {
        String className =
            UtilXml.childElementValue(
                rootElement,
                "AuthenticationHandler",
                "org.ofbiz.ldap.openldap.OFBizLdapAuthenticationHandler");
        try {
          Class<?> handlerClass = Class.forName(className);
          InterfaceOFBizAuthenticationHandler authenticationHandler =
              (InterfaceOFBizAuthenticationHandler) handlerClass.newInstance();
          hasLdapLoggedOut = authenticationHandler.hasLdapLoggedOut(request, response, rootElement);
        } catch (ClassNotFoundException e) {
          Debug.logError(e, "Error calling checkLogin service", module);
          Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
          String errMsg =
              UtilProperties.getMessage(
                  resourceWebapp,
                  "loginevents.following_error_occurred_during_login",
                  messageMap,
                  UtilHttp.getLocale(request));
          request.setAttribute("_ERROR_MESSAGE_", errMsg);
        } catch (InstantiationException e) {
          Debug.logError(e, "Error calling checkLogin service", module);
          Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
          String errMsg =
              UtilProperties.getMessage(
                  resourceWebapp,
                  "loginevents.following_error_occurred_during_login",
                  messageMap,
                  UtilHttp.getLocale(request));
          request.setAttribute("_ERROR_MESSAGE_", errMsg);
        } catch (IllegalAccessException e) {
          Debug.logError(e, "Error calling checkLogin service", module);
          Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
          String errMsg =
              UtilProperties.getMessage(
                  resourceWebapp,
                  "loginevents.following_error_occurred_during_login",
                  messageMap,
                  UtilHttp.getLocale(request));
          request.setAttribute("_ERROR_MESSAGE_", errMsg);
        } catch (Exception e) {
          Debug.logError(e, "Error calling checkLogin service", module);
          Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
          String errMsg =
              UtilProperties.getMessage(
                  resourceWebapp,
                  "loginevents.following_error_occurred_during_login",
                  messageMap,
                  UtilHttp.getLocale(request));
          request.setAttribute("_ERROR_MESSAGE_", errMsg);
        }
      }

      if (!hasBasePermission(userLogin, request)
          || isFlaggedLoggedOut(userLogin)
          || hasLdapLoggedOut) {
        Debug.logInfo("User does not have permission or is flagged as logged out", module);
        doBasicLogout(userLogin, request, response);
        userLogin = null;
      }
    }

    if (userLogin == null) {
      return login(request, response);
    }

    return "success";
  }