Пример #1
0
 public void ifCmd(Element elem) throws TestCaseException {
   String isRun = replaceParam(elem.getAttributeValue("condition"));
   if (isRun != null && !isRun.equals("") && Boolean.valueOf(isRun)) {
     List<Element> children = UtilGenerics.cast(elem.getChildren());
     this.runCommands(children);
   } else {
     Element child = elem.getChild("else");
     List<Element> children = UtilGenerics.cast(child.getChildren());
     this.runCommands(children);
   }
 }
  protected void logRequestInfo(HttpServletRequest request) {
    ServletContext servletContext = this.getServletContext();
    HttpSession session = request.getSession();

    Debug.logVerbose("--- Start Request Headers: ---", module);
    Enumeration<String> headerNames = UtilGenerics.cast(request.getHeaderNames());
    while (headerNames.hasMoreElements()) {
      String headerName = headerNames.nextElement();
      Debug.logVerbose(headerName + ":" + request.getHeader(headerName), module);
    }
    Debug.logVerbose("--- End Request Headers: ---", module);

    Debug.logVerbose("--- Start Request Parameters: ---", module);
    Enumeration<String> paramNames = UtilGenerics.cast(request.getParameterNames());
    while (paramNames.hasMoreElements()) {
      String paramName = paramNames.nextElement();
      Debug.logVerbose(paramName + ":" + request.getParameter(paramName), module);
    }
    Debug.logVerbose("--- End Request Parameters: ---", module);

    Debug.logVerbose("--- Start Request Attributes: ---", module);
    Enumeration<String> reqNames = UtilGenerics.cast(request.getAttributeNames());
    while (reqNames != null && reqNames.hasMoreElements()) {
      String attName = reqNames.nextElement();
      Debug.logVerbose(attName + ":" + request.getAttribute(attName), module);
    }
    Debug.logVerbose("--- End Request Attributes ---", module);

    Debug.logVerbose("--- Start Session Attributes: ---", module);
    Enumeration<String> sesNames = null;
    try {
      sesNames = UtilGenerics.cast(session.getAttributeNames());
    } catch (IllegalStateException e) {
      Debug.logVerbose("Cannot get session attributes : " + e.getMessage(), module);
    }
    while (sesNames != null && sesNames.hasMoreElements()) {
      String attName = sesNames.nextElement();
      Debug.logVerbose(attName + ":" + session.getAttribute(attName), module);
    }
    Debug.logVerbose("--- End Session Attributes ---", module);

    Enumeration<String> appNames = UtilGenerics.cast(servletContext.getAttributeNames());
    Debug.logVerbose("--- Start ServletContext Attributes: ---", module);
    while (appNames != null && appNames.hasMoreElements()) {
      String attName = appNames.nextElement();
      Debug.logVerbose(attName + ":" + servletContext.getAttribute(attName), module);
    }
    Debug.logVerbose("--- End ServletContext Attributes ---", module);
  }
Пример #3
0
  public void remoteRequest(Element elem) {

    String requestUrl = elem.getAttributeValue("url");
    String host = elem.getAttributeValue("host");
    if (host == null || host.length() == 0) {
      host = props.getProperty("startUrl");
    }
    String responseHandlerMode = elem.getAttributeValue("responseHandlerMode");
    List<Element> children = UtilGenerics.cast(elem.getChildren());
    List<Element> loginAs = UtilGenerics.cast(elem.getChildren("login-as"));
    logger.info("remoteRequest: children=" + children + " loginAs=" + loginAs);
    RemoteRequest loader =
        new RemoteRequest(this, children, loginAs, requestUrl, host, responseHandlerMode);
    loader.runTest();
  }
Пример #4
0
    @Override
    public void renderWidgetString(
        Appendable writer, Map<String, Object> context, ScreenStringRenderer screenStringRenderer) {
      // isolate the scope
      MapStack<String> contextMs;
      if (!(context instanceof MapStack)) {
        contextMs = MapStack.create(context);
        context = contextMs;
      } else {
        contextMs = UtilGenerics.cast(context);
      }

      // create a standAloneStack, basically a "save point" for this SectionsRenderer, and make a
      // new "screens" object just for it so it is isolated and doesn't follow the stack down
      MapStack<String> standAloneStack = contextMs.standAloneChildStack();
      standAloneStack.put(
          "screens", new ScreenRenderer(writer, standAloneStack, screenStringRenderer));
      SectionsRenderer sections =
          new SectionsRenderer(this.sectionMap, standAloneStack, writer, screenStringRenderer);

      // put the sectionMap in the context, make sure it is in the sub-scope, ie after calling push
      // on the MapStack
      contextMs.push();
      context.put("sections", sections);

      renderHtmlTemplate(writer, this.locationExdr, context);
      contextMs.pop();
    }
  public void renderPortalPageBegin(
      Appendable writer, Map<String, Object> context, ModelScreenWidget.PortalPage portalPage)
      throws GeneralException, IOException {
    String portalPageId = portalPage.getActualPortalPageId();
    String originalPortalPageId = portalPage.getOriginalPortalPageId();
    String confMode = portalPage.getConfMode(context);

    Map<String, String> uiLabelMap = UtilGenerics.cast(context.get("uiLabelMap"));
    String addColumnLabel = "";
    String addColumnHint = "";
    if (uiLabelMap == null) {
      Debug.logWarning("Could not find uiLabelMap in context", module);
    } else {
      addColumnLabel = uiLabelMap.get("CommonAddColumn");
      addColumnHint = uiLabelMap.get("CommonAddAColumnToThisPortalPage");
    }

    StringWriter sr = new StringWriter();
    sr.append("<@renderPortalPageBegin ");
    sr.append("originalPortalPageId=\"");
    sr.append(originalPortalPageId);
    sr.append("\" portalPageId=\"");
    sr.append(portalPageId);
    sr.append("\" confMode=\"");
    sr.append(confMode);
    sr.append("\" addColumnLabel=\"");
    sr.append(addColumnLabel);
    sr.append("\" addColumnHint=\"");
    sr.append(addColumnHint);
    sr.append("\" />");
    executeMacro(writer, sr.toString());
  }
  public <X> void getListLimits(Map<String, Object> context, List<X> items) {
    listSize = items.size();

    if (getPaginate(context)) {
      try {
        Map<String, String> params = UtilGenerics.cast(context.get("parameters"));
        String viewIndexString = params.get("VIEW_INDEX" + "_" + getPaginatorNumber(context));
        String viewSizeString = params.get("VIEW_SIZE" + "_" + getPaginatorNumber(context));
        viewIndex = Integer.parseInt(viewIndexString);
        viewSize = Integer.parseInt(viewSizeString);
      } catch (Exception e) {
        try {
          viewIndex = ((Integer) context.get("viewIndex")).intValue();
        } catch (Exception e2) {
          viewIndex = 0;
        }
      }
      context.put("viewIndex", Integer.valueOf(this.viewIndex));

      lowIndex = viewIndex * viewSize;
      highIndex = (viewIndex + 1) * viewSize;
    } else {
      viewIndex = 0;
      viewSize = MAX_PAGE_SIZE;
      lowIndex = 0;
      highIndex = MAX_PAGE_SIZE;
    }
  }
Пример #7
0
 public void partialRunDependency(Element elem) throws TestCaseException {
   String isRun = replaceParam(elem.getAttributeValue("isRun"));
   if (isRun != null && Boolean.valueOf(isRun)) {
     List<Element> children = UtilGenerics.cast(elem.getChildren());
     this.runCommands(children);
   }
 }
Пример #8
0
  public void dataLoop(Element elem) throws TestCaseException {

    String dataListName = elem.getAttributeValue("dataListName");
    List<Element> children = UtilGenerics.cast(elem.getChildren());

    DataLoop looper = new DataLoop(dataListName, this, children);
    looper.runTest();
  }
Пример #9
0
  public void loadData(Element elem) throws TestCaseException {

    String file = elem.getAttributeValue("file");
    String iterations = elem.getAttributeValue("iterations");
    List<Element> children = UtilGenerics.cast(elem.getChildren());

    DataLoader loader = new DataLoader(file, iterations, this, children);
    loader.runTest();
  }
Пример #10
0
 @Override
 public Class<T> getTypeClass(ClassLoader loader) {
   try {
     return UtilGenerics.cast(ObjectType.loadClass(type, loader));
   } catch (ClassNotFoundException e) {
     Debug.logError(e, "Could not find class for type: " + type, module);
     return null;
   }
 }
Пример #11
0
 /**
  * Returns an appropriate <code>Converter</code> instance for <code>sourceClass</code> and <code>
  * targetClass</code>. If no matching <code>Converter</code> is found, the method throws <code>
  * ClassNotFoundException</code>.
  *
  * <p>This method is intended to be used when the source or target <code>Object</code> types are
  * unknown at compile time. If the source and target <code>Object</code> types are known at
  * compile time, then one of the "ready made" converters should be used.
  *
  * @param sourceClass The object class to convert from
  * @param targetClass The object class to convert to
  * @return A matching <code>Converter</code> instance
  * @throws ClassNotFoundException
  */
 public static <S, T> Converter<S, T> getConverter(Class<S> sourceClass, Class<T> targetClass)
     throws ClassNotFoundException {
   String key = sourceClass.getName().concat(DELIMITER).concat(targetClass.getName());
   if (Debug.verboseOn()) {
     Debug.logVerbose("Getting converter: " + key, module);
   }
   OUTER:
   do {
     Converter<?, ?> result = converterMap.get(key);
     if (result != null) {
       return UtilGenerics.cast(result);
     }
     if (noConversions.contains(key)) {
       throw new ClassNotFoundException("No converter found for " + key);
     }
     Class<?> foundSourceClass = null;
     Converter<?, ?> foundConverter = null;
     for (Converter<?, ?> value : converterMap.values()) {
       if (value.canConvert(sourceClass, targetClass)) {
         // this converter can deal with the source/target pair
         if (foundSourceClass == null
             || foundSourceClass.isAssignableFrom(value.getSourceClass())) {
           // remember the current target source class; if we find another converter, check
           // to see if it's source class is assignable to this one, and if so, it means it's
           // a child class, so we'll then take that converter.
           foundSourceClass = value.getSourceClass();
           foundConverter = value;
         }
       }
     }
     if (foundConverter != null) {
       converterMap.putIfAbsent(key, foundConverter);
       continue OUTER;
     }
     for (ConverterCreator value : creators) {
       result = createConverter(value, sourceClass, targetClass);
       if (result != null) {
         converterMap.putIfAbsent(key, result);
         continue OUTER;
       }
     }
     if (noConversions.add(key)) {
       Debug.logWarning(
           "*** No converter found, converting from "
               + sourceClass.getName()
               + " to "
               + targetClass.getName()
               + ". Please report this message to the developer community so "
               + "a suitable converter can be created. ***",
           module);
     }
     throw new ClassNotFoundException("No converter found for " + key);
   } while (true);
 }
Пример #12
0
 private void validateSOAPBody(SOAPBody reqBody) throws EventHandlerException {
   // ensure the SOAPBody contains only one service call request
   Integer numServiceCallRequests = 0;
   Iterator<Object> serviceIter = UtilGenerics.cast(reqBody.getChildElements());
   while (serviceIter.hasNext()) {
     numServiceCallRequests++;
     serviceIter.next();
   }
   if (numServiceCallRequests != 1) {
     throw new EventHandlerException(
         "One service call expected, but received: " + numServiceCallRequests.toString());
   }
 }
 private static TimeZone getTimeZone(TimeZone timeZone, Map<String, ? extends Object> context) {
   if (timeZone == null) {
     timeZone = (TimeZone) context.get("timeZone");
     if (timeZone == null && context.containsKey("autoUserLogin")) {
       Map<String, String> autoUserLogin = UtilGenerics.cast(context.get("autoUserLogin"));
       timeZone = UtilDateTime.toTimeZone(autoUserLogin.get("lastTimeZone"));
     }
     if (timeZone == null) {
       timeZone = TimeZone.getDefault();
     }
   }
   return timeZone;
 }
 private static Locale getLocale(Locale locale, Map<String, ? extends Object> context) {
   if (locale == null) {
     locale = (Locale) context.get("locale");
     if (locale == null && context.containsKey("autoUserLogin")) {
       Map<String, Object> autoUserLogin = UtilGenerics.cast(context.get("autoUserLogin"));
       locale = UtilMisc.ensureLocale(autoUserLogin.get("lastLocale"));
     }
     if (locale == null) {
       locale = Locale.getDefault();
     }
   }
   return locale;
 }
Пример #15
0
  private String getUserLoginSession(HttpSession session) {
    Map<String, ?> userLoginSession = UtilGenerics.cast(session.getAttribute("userLoginSession"));

    String sessionData = null;
    if (UtilValidate.isNotEmpty(userLoginSession)) {
      try {
        sessionData = XmlSerializer.serialize(userLoginSession);
      } catch (Exception e) {
        Debug.logWarning(e, "Problems serializing UserLoginSession", module);
      }
    }
    return sessionData;
  }
Пример #16
0
  private GenericMessageListener loadListener(String serverKey, Element server)
      throws GenericServiceException {
    String serverName = server.getAttribute("jndi-server-name");
    String jndiName = server.getAttribute("jndi-name");
    String queueName = server.getAttribute("topic-queue");
    String type = server.getAttribute("type");
    String userName = server.getAttribute("username");
    String password = server.getAttribute("password");
    String className = server.getAttribute("listener-class");

    if (UtilValidate.isEmpty(className)) {
      if (type.equals("topic")) className = JmsListenerFactory.TOPIC_LISTENER_CLASS;
      else if (type.equals("queue")) className = JmsListenerFactory.QUEUE_LISTENER_CLASS;
    }

    GenericMessageListener listener = listeners.get(serverKey);

    if (listener == null) {
      synchronized (this) {
        listener = listeners.get(serverKey);
        if (listener == null) {
          ClassLoader cl = this.getClass().getClassLoader();

          try {
            Class<?> c = cl.loadClass(className);
            Constructor<GenericMessageListener> cn =
                UtilGenerics.cast(
                    c.getConstructor(
                        ServiceDispatcher.class,
                        String.class,
                        String.class,
                        String.class,
                        String.class,
                        String.class));

            listener =
                cn.newInstance(dispatcher, serverName, jndiName, queueName, userName, password);
          } catch (Exception e) {
            throw new GenericServiceException(e.getMessage(), e);
          }
          if (listener != null) listeners.put(serverKey, listener);
          loadable++;
        }
      }
    }
    if (listener != null && !listener.isConnected()) {
      listener.load();
      if (listener.isConnected()) connected++;
    }
    return listener;
  }
Пример #17
0
  private boolean defineElement() {
    element = null;
    pageContext.removeAttribute(name, PageContext.PAGE_SCOPE);
    boolean verboseOn = Debug.verboseOn();

    if (this.iterator.hasNext()) {
      element = this.iterator.next();
      if (verboseOn) Debug.logVerbose("iterator has another object: " + element, module);
    } else {
      if (verboseOn) Debug.logVerbose("iterator has no more objects", module);
    }
    if (element != null) {
      if (verboseOn)
        Debug.logVerbose(
            "set attribute " + name + " to be " + element + " as next value from iterator", module);
      pageContext.setAttribute(name, element);

      // expand a map element here if requested
      if (expandMap) {
        Map<String, ?> tempMap = UtilGenerics.cast(element);
        Iterator<Map.Entry<String, ?>> mapEntries =
            UtilGenerics.cast(tempMap.entrySet().iterator());

        while (mapEntries.hasNext()) {
          Map.Entry<String, ?> entry = mapEntries.next();
          Object value = entry.getValue();

          if (value == null) value = "";
          pageContext.setAttribute(entry.getKey(), value);
        }
      }

      return true;
    }
    if (verboseOn) Debug.logVerbose("no more iterations; element = " + element, module);
    return false;
  }
Пример #18
0
 public void logStats(HttpSession session, GenericValue visit) {
   if (Debug.verboseOn() || session.getAttribute("org.ofbiz.log.session.stats") != null) {
     Debug.log("<===================================================================>", module);
     Debug.log("Session ID     : " + session.getId(), module);
     Debug.log("Created Time   : " + session.getCreationTime(), module);
     Debug.log("Last Access    : " + session.getLastAccessedTime(), module);
     Debug.log("Max Inactive   : " + session.getMaxInactiveInterval(), module);
     Debug.log("--------------------------------------------------------------------", module);
     Debug.log("Total Sessions : " + ControlEventListener.getTotalActiveSessions(), module);
     Debug.log("Total Active   : " + ControlEventListener.getTotalActiveSessions(), module);
     Debug.log("Total Passive  : " + ControlEventListener.getTotalPassiveSessions(), module);
     Debug.log("** note : this session has been counted as destroyed.", module);
     Debug.log("--------------------------------------------------------------------", module);
     Debug.log("Visit ID       : " + visit.getString("visitId"), module);
     Debug.log("Party ID       : " + visit.getString("partyId"), module);
     Debug.log("Client IP      : " + visit.getString("clientIpAddress"), module);
     Debug.log("Client Host    : " + visit.getString("clientHostName"), module);
     Debug.log("Client User    : "******"clientUser"), module);
     Debug.log("WebApp         : " + visit.getString("webappName"), module);
     Debug.log("Locale         : " + visit.getString("initialLocale"), module);
     Debug.log("UserAgent      : " + visit.getString("initialUserAgent"), module);
     Debug.log("Referrer       : " + visit.getString("initialReferrer"), module);
     Debug.log("Initial Req    : " + visit.getString("initialRequest"), module);
     Debug.log("Visit From     : " + visit.getString("fromDate"), module);
     Debug.log("Visit Thru     : " + visit.getString("thruDate"), module);
     Debug.log("--------------------------------------------------------------------", module);
     Debug.log("--- Start Session Attributes: ---", module);
     Enumeration<String> sesNames = null;
     try {
       sesNames = UtilGenerics.cast(session.getAttributeNames());
     } catch (IllegalStateException e) {
       Debug.log("Cannot get session attributes : " + e.getMessage(), module);
     }
     while (sesNames != null && sesNames.hasMoreElements()) {
       String attName = sesNames.nextElement();
       Debug.log(attName + ":" + session.getAttribute(attName), module);
     }
     Debug.log("--- End Session Attributes ---", module);
     Debug.log("<===================================================================>", module);
   }
 }
Пример #19
0
  public static String getJSONuiLabelArray(
      HttpServletRequest request, HttpServletResponse response) {
    String requiredLabels = request.getParameter("requiredLabels");

    JSONObject uiLabelObject = null;
    if (UtilValidate.isNotEmpty(requiredLabels)) {
      // Transform JSON String to Object
      uiLabelObject = (JSONObject) JSONSerializer.toJSON(requiredLabels);
    }

    JSONObject jsonUiLabel = new JSONObject();
    Locale locale = request.getLocale();
    if (!uiLabelObject.isEmpty()) {
      Set<String> resourceSet = UtilGenerics.checkSet(uiLabelObject.keySet());
      // Iterate over the resouce set
      for (String resource : resourceSet) {
        JSONArray labels = uiLabelObject.getJSONArray(resource);
        if (labels.isEmpty() || labels == null) {
          continue;
        }

        // Iterate over the uiLabel List
        Iterator<String> jsonLabelIterator = UtilGenerics.cast(labels.iterator());
        JSONArray resourceLabelList = new JSONArray();
        while (jsonLabelIterator.hasNext()) {
          String label = jsonLabelIterator.next();
          String receivedLabel = UtilProperties.getMessage(resource, label, locale);
          if (UtilValidate.isNotEmpty(receivedLabel)) {
            resourceLabelList.add(receivedLabel);
          }
        }
        jsonUiLabel.element(resource, resourceLabelList);
      }
    }

    writeJSONtoResponse(jsonUiLabel, response);
    return "success";
  }
Пример #20
0
  /**
   * @see org.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event,
   *     ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse)
   */
  public String invoke(
      Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response)
      throws EventHandlerException {
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");

    // first check for WSDL request
    String wsdlReq = request.getParameter("wsdl");
    if (wsdlReq == null) {
      wsdlReq = request.getParameter("WSDL");
    }
    if (wsdlReq != null) {
      String serviceName = RequestHandler.getOverrideViewUri(request.getPathInfo());
      DispatchContext dctx = dispatcher.getDispatchContext();
      String locationUri = this.getLocationURI(request);

      if (serviceName != null) {
        Document wsdl = null;
        try {
          wsdl = dctx.getWSDL(serviceName, locationUri);
        } catch (GenericServiceException e) {
          serviceName = null;
        } catch (WSDLException e) {
          sendError(response, "Unable to obtain WSDL", serviceName);
          throw new EventHandlerException("Unable to obtain WSDL", e);
        }

        if (wsdl != null) {
          try {
            OutputStream os = response.getOutputStream();
            response.setContentType("text/xml");
            UtilXml.writeXmlDocument(os, wsdl);
            response.flushBuffer();
          } catch (IOException e) {
            throw new EventHandlerException(e);
          }
          return null;
        } else {
          sendError(response, "Unable to obtain WSDL", serviceName);
          throw new EventHandlerException("Unable to obtain WSDL");
        }
      }

      if (serviceName == null) {
        try {
          Writer writer = response.getWriter();
          StringBuilder sb = new StringBuilder();
          sb.append("<html><head><title>OFBiz SOAP/1.1 Services</title></head>");
          sb.append("<body>No such service.").append("<p>Services:<ul>");

          for (String scvName : dctx.getAllServiceNames()) {
            ModelService model = dctx.getModelService(scvName);
            if (model.export) {
              sb.append("<li><a href=\"")
                  .append(locationUri)
                  .append("/")
                  .append(model.name)
                  .append("?wsdl\">");
              sb.append(model.name).append("</a></li>");
            }
          }
          sb.append("</ul></p></body></html>");

          writer.write(sb.toString());
          writer.flush();
          return null;
        } catch (Exception e) {
          sendError(response, "Unable to obtain WSDL", null);
          throw new EventHandlerException("Unable to obtain WSDL");
        }
      }
    }

    // not a wsdl request; invoke the service
    response.setContentType("text/xml");

    // request envelope
    SOAPEnvelope reqEnv = null;

    // get the service name and parameters
    try {
      XMLStreamReader xmlReader = StAXUtils.createXMLStreamReader(request.getInputStream());
      StAXSOAPModelBuilder builder = new StAXSOAPModelBuilder(xmlReader);
      reqEnv = (SOAPEnvelope) builder.getDocumentElement();

      // log the request message
      if (Debug.verboseOn()) {
        try {
          Debug.logInfo("Request Message:\n" + reqEnv + "\n", module);
        } catch (Throwable t) {
        }
      }
    } catch (Exception e) {
      sendError(response, "Problem processing the service", null);
      throw new EventHandlerException("Cannot get the envelope", e);
    }

    Debug.logVerbose("[Processing]: SOAP Event", module);

    String serviceName = null;
    try {
      SOAPBody reqBody = reqEnv.getBody();
      validateSOAPBody(reqBody);
      OMElement serviceElement = reqBody.getFirstElement();
      serviceName = serviceElement.getLocalName();
      Map<String, Object> parameters =
          UtilGenerics.cast(SoapSerializer.deserialize(serviceElement.toString(), delegator));
      try {
        // verify the service is exported for remote execution and invoke it
        ModelService model = dispatcher.getDispatchContext().getModelService(serviceName);

        if (model == null) {
          sendError(response, "Problem processing the service", serviceName);
          Debug.logError("Could not find Service [" + serviceName + "].", module);
          return null;
        }

        if (!model.export) {
          sendError(response, "Problem processing the service", serviceName);
          Debug.logError(
              "Trying to call Service [" + serviceName + "] that is not exported.", module);
          return null;
        }

        Map<String, Object> serviceResults = dispatcher.runSync(serviceName, parameters);
        Debug.logVerbose("[EventHandler] : Service invoked", module);

        createAndSendSOAPResponse(serviceResults, serviceName, response);

      } catch (GenericServiceException e) {
        if (UtilProperties.getPropertyAsBoolean("service", "secureSoapAnswer", true)) {
          sendError(
              response, "Problem processing the service, check your parameters.", serviceName);
        } else {
          if (e.getMessageList() == null) {
            sendError(response, e.getMessage(), serviceName);
          } else {
            sendError(response, e.getMessageList(), serviceName);
          }
          Debug.logError(e, module);
          return null;
        }
      }
    } catch (Exception e) {
      sendError(response, e.getMessage(), serviceName);
      Debug.logError(e, module);
      return null;
    }

    return null;
  }
Пример #21
0
  /**
   * Renders this screen to a String, i.e. in a text format, as defined with the
   * ScreenStringRenderer implementation.
   *
   * @param writer The Writer that the screen text will be written to
   * @param context Map containing the screen context; the following are reserved words in this
   *     context: - parameters (contains any special initial parameters coming in) - userLogin (if a
   *     user is logged in) - autoUserLogin (if a user is automatically logged in, ie no password
   *     has been entered) - formStringRenderer - request, response, session, application (special
   *     case, only in HTML contexts, etc) - delegator, dispatcher, authz, security - null
   *     (represents a null field value for entity operations) - sections (used for decorators to
   *     reference the sections to be decorated and render them)
   * @param screenStringRenderer An implementation of the ScreenStringRenderer interface that is
   *     responsible for the actual text generation for different screen elements; implementing your
   *     own makes it possible to use the same screen definitions for many types of screen UIs
   */
  public void renderScreenString(
      Appendable writer, Map<String, Object> context, ScreenStringRenderer screenStringRenderer)
      throws ScreenRenderException {
    // make sure the "nullField" object is in there for entity ops
    context.put("nullField", GenericEntity.NULL_FIELD);

    // wrap the whole screen rendering in a transaction, should improve performance in querying and
    // such
    Map<String, String> parameters = UtilGenerics.cast(context.get("parameters"));
    boolean beganTransaction = false;
    int transactionTimeout = -1;
    if (parameters != null) {
      String transactionTimeoutPar = parameters.get("TRANSACTION_TIMEOUT");
      if (transactionTimeoutPar != null) {
        try {
          transactionTimeout = Integer.parseInt(transactionTimeoutPar);
        } catch (NumberFormatException nfe) {
          String msg =
              "TRANSACTION_TIMEOUT parameter for screen ["
                  + this.sourceLocation
                  + "#"
                  + this.name
                  + "] is invalid and it will be ignored: "
                  + nfe.toString();
          Debug.logWarning(msg, module);
        }
      }
    }

    if (transactionTimeout < 0 && !transactionTimeoutExdr.isEmpty()) {
      // no TRANSACTION_TIMEOUT parameter, check screen attribute
      String transactionTimeoutStr = transactionTimeoutExdr.expandString(context);
      if (UtilValidate.isNotEmpty(transactionTimeoutStr)) {
        try {
          transactionTimeout = Integer.parseInt(transactionTimeoutStr);
        } catch (NumberFormatException e) {
          Debug.logWarning(
              e,
              "Could not parse transaction-timeout value, original=["
                  + transactionTimeoutExdr
                  + "], expanded=["
                  + transactionTimeoutStr
                  + "]",
              module);
        }
      }
    }

    try {
      // If transaction timeout is not present (i.e. is equal to -1), the default transaction
      // timeout is used
      // If transaction timeout is present, use it to start the transaction
      // If transaction timeout is set to zero, no transaction is started
      if (useTransaction) {
        if (transactionTimeout < 0) {
          beganTransaction = TransactionUtil.begin();
        }
        if (transactionTimeout > 0) {
          beganTransaction = TransactionUtil.begin(transactionTimeout);
        }
      }

      // render the screen, starting with the top-level section
      this.section.renderWidgetString(writer, context, screenStringRenderer);
    } catch (ScreenRenderException e) {
      throw e;
    } catch (RuntimeException e) {
      String errMsg =
          "Error rendering screen [" + this.sourceLocation + "#" + this.name + "]: " + e.toString();
      Debug.logError(errMsg + ". Rolling back transaction.", module);
      try {
        // only rollback the transaction if we started one...
        TransactionUtil.rollback(beganTransaction, errMsg, e);
      } catch (GenericEntityException e2) {
        Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
      }
      // after rolling back, rethrow the exception
      throw new ScreenRenderException(errMsg, e);
    } catch (Exception e) {
      String errMsg =
          "Error rendering screen [" + this.sourceLocation + "#" + this.name + "]: " + e.toString();
      Debug.logError(errMsg + ". Rolling back transaction.", module);
      try {
        // only rollback the transaction if we started one...
        TransactionUtil.rollback(beganTransaction, errMsg, e);
      } catch (GenericEntityException e2) {
        Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
      }

      // throw nested exception, don't need to log details here: Debug.logError(e, errMsg, module);

      // after rolling back, rethrow the exception
      throw new ScreenRenderException(errMsg, e);
    } finally {
      // only commit the transaction if we started one... this will throw an exception if it fails
      try {
        TransactionUtil.commit(beganTransaction);
      } catch (GenericEntityException e2) {
        Debug.logError(e2, "Could not commit transaction: " + e2.toString(), module);
      }
    }
  }
Пример #22
0
  private boolean defineIterator() {
    // clear the iterator, after this it may be set directly
    Iterator<?> newIterator = null;
    Collection<?> thisCollection = null;

    if (property != null) {
      if (Debug.verboseOn())
        Debug.logVerbose("Getting iterator from property: " + property, module);
      Object propertyObject = pageContext.findAttribute(property);

      if (propertyObject instanceof Iterator<?>) {
        newIterator = UtilGenerics.cast(propertyObject);
      } else {
        // if ClassCastException, it should indicate looking for a Collection
        thisCollection = UtilGenerics.cast(propertyObject);
      }
    } else {
      // Debug.logInfo("No property, check for Object Tag.", module);
      ObjectTag objectTag = (ObjectTag) findAncestorWithClass(this, ObjectTag.class);

      if (objectTag == null) return false;
      if (objectTag.getType().equals("java.util.Collection")) {
        thisCollection = UtilGenerics.cast(objectTag.getObject());
      } else {
        try {
          ClassLoader loader = Thread.currentThread().getContextClassLoader();
          Method[] m = loader.loadClass(objectTag.getType()).getDeclaredMethods();

          for (int i = 0; i < m.length; i++) {
            if (m[i].getName().equals("iterator")) {
              Debug.logVerbose("Found iterator method. Using it.", module);
              newIterator = UtilGenerics.cast(m[i].invoke(objectTag.getObject(), (Object[]) null));
              break;
            }
          }
        } catch (Exception e) {
          return false;
        }
      }
    }

    if (newIterator == null) {
      if (thisCollection == null || thisCollection.size() < 1) return false;

      if (limit > 0 || offset > 0) {
        ArrayList<? extends Object> colList = new ArrayList<Object>(thisCollection);
        int startIndex = offset > 0 ? offset : 0;
        int endIndex = limit > 0 ? offset + limit : colList.size();

        endIndex = endIndex > colList.size() ? colList.size() : endIndex;
        List<? extends Object> subList = colList.subList(startIndex, endIndex);

        newIterator = subList.iterator();
      } else {
        newIterator = thisCollection.iterator();
      }

      Debug.logVerbose("Got iterator.", module);
    } else { // already set
      Debug.logVerbose("iterator already set.", module);
    }
    this.iterator = newIterator;
    return true;
  }
  @Override
  public void renderWidgetString(
      Appendable writer, Map<String, Object> context, ScreenStringRenderer screenStringRenderer)
      throws GeneralException, IOException {

    boolean isEntrySet = false;
    // create a standAloneStack, basically a "save point" for this SectionsRenderer, and make a new
    // "screens" object just for it so it is isolated and doesn't follow the stack down
    MapStack<String> contextMs = MapStack.create(context);

    String entryName = this.entryNameExdr.expandString(context);
    String keyName = this.keyNameExdr.expandString(context);
    Object obj = listNameExdr.get(context);
    if (obj == null) {
      Debug.logError("No object found for listName:" + listNameExdr.toString(), module);
      return;
    }
    List<?> theList = null;
    if (obj instanceof Map) {
      Set<Map.Entry<String, Object>> entrySet =
          UtilGenerics.<Map<String, Object>>cast(obj).entrySet();
      Object[] a = entrySet.toArray();
      theList = Arrays.asList(a);
      isEntrySet = true;
    } else if (obj instanceof List) {
      theList = (List<?>) obj;
    } else {
      Debug.logError("Object not list or map type", module);
      return;
    }
    this.incrementPaginatorNumber(context);
    int startPageNumber = this.getPaginatorNumber(context);
    getListLimits(context, theList);
    int rowCount = 0;
    Iterator<?> iter = theList.iterator();
    int itemIndex = -1;
    int iterateIndex = 0;
    while (iter.hasNext()) {
      itemIndex++;
      if (itemIndex >= highIndex) {
        break;
      }
      Object item = iter.next();
      if (itemIndex < lowIndex) {
        continue;
      }
      if (isEntrySet) {
        Map.Entry<String, ?> entry = UtilGenerics.cast(item);
        contextMs.put(entryName, entry.getValue());
        contextMs.put(keyName, entry.getKey());
      } else {
        contextMs.put(entryName, item);
      }
      contextMs.put("itemIndex", Integer.valueOf(itemIndex));

      if (iterateIndex < listSize) {
        contextMs.put("iterateId", String.valueOf(entryName + iterateIndex));
        iterateIndex++;
      }
      rowCount++;
      for (ModelScreenWidget.Section section : this.sectionList) {
        section.renderWidgetString(writer, contextMs, screenStringRenderer);
      }
    }

    if ((itemIndex + 1) < highIndex) {
      setHighIndex(itemIndex + 1);
    }
    setActualPageSize(highIndex - lowIndex);
    if (getPaginate(context)) {
      try {
        Integer lastPageNumber = null;
        Map<String, Object> globalCtx = UtilGenerics.checkMap(context.get("globalContext"));
        if (globalCtx != null) {
          lastPageNumber = (Integer) globalCtx.get("PAGINATOR_NUMBER");
          globalCtx.put("PAGINATOR_NUMBER", Integer.valueOf(startPageNumber));
        }

        renderNextPrev(writer, context);

        if (globalCtx != null) {
          globalCtx.put("PAGINATOR_NUMBER", lastPageNumber);
        }
      } catch (IOException e) {
        Debug.logError(e, module);
        throw new RuntimeException(e.getMessage());
      }
    }
  }
Пример #24
0
  @Override
  public void run(TestResult result) {
    result.startTest(this);

    try {
      // define request
      Security security = SecurityFactory.getInstance(delegator);
      MockServletContext servletContext = new MockServletContext();
      request.setAttribute("security", security);
      request.setAttribute("servletContext", servletContext);
      request.setAttribute("delegator", delegator);
      request.setAttribute("dispatcher", dispatcher);
      Map<String, Object> serviceResult =
          SimpleMethod.runSimpleService(
              methodLocation,
              methodName,
              dispatcher.getDispatchContext(),
              UtilMisc.toMap(
                  "test",
                  this,
                  "testResult",
                  result,
                  "locale",
                  Locale.getDefault(),
                  "request",
                  request,
                  "response",
                  response));

      // do something with the errorMessage
      String errorMessage = (String) serviceResult.get(ModelService.ERROR_MESSAGE);
      if (UtilValidate.isNotEmpty(errorMessage)) {
        result.addFailure(this, new AssertionFailedError(errorMessage));
      }

      // do something with the errorMessageList
      List<Object> errorMessageList =
          UtilGenerics.cast(serviceResult.get(ModelService.ERROR_MESSAGE_LIST));
      if (UtilValidate.isNotEmpty(errorMessageList)) {
        for (Object message : errorMessageList) {
          result.addFailure(this, new AssertionFailedError(message.toString()));
        }
      }

      // do something with the errorMessageMap
      Map<String, Object> errorMessageMap =
          UtilGenerics.cast(serviceResult.get(ModelService.ERROR_MESSAGE_MAP));
      if (!UtilValidate.isEmpty(errorMessageMap)) {
        for (Map.Entry<String, Object> entry : errorMessageMap.entrySet()) {
          result.addFailure(
              this, new AssertionFailedError(entry.getKey() + ": " + entry.getValue()));
        }
      }

    } catch (MiniLangException e) {
      result.addError(this, e);
    } catch (SecurityConfigurationException e) {
      result.addError(this, e);
    }

    result.endTest(this);
  }
  public void renderPortalPagePortletBegin(
      Appendable writer,
      Map<String, Object> context,
      ModelScreenWidget.PortalPage portalPage,
      GenericValue portalPortlet)
      throws GeneralException, IOException {
    String portalPageId = portalPage.getActualPortalPageId();
    String originalPortalPageId = portalPage.getOriginalPortalPageId();
    String portalPortletId = portalPortlet.getString("portalPortletId");
    String portletSeqId = portalPortlet.getString("portletSeqId");
    String columnSeqId = portalPortlet.getString("columnSeqId");
    String confMode = portalPage.getConfMode(context);
    String editFormName = portalPortlet.getString("editFormName");
    String editFormLocation = portalPortlet.getString("editFormLocation");

    String prevPortletId = (String) context.get("prevPortletId");
    String prevPortletSeqId = (String) context.get("prevPortletSeqId");
    String nextPortletId = (String) context.get("nextPortletId");
    String nextPortletSeqId = (String) context.get("nextPortletSeqId");
    String prevColumnSeqId = (String) context.get("prevColumnSeqId");
    String nextColumnSeqId = (String) context.get("nextColumnSeqId");

    Map<String, String> uiLabelMap = UtilGenerics.cast(context.get("uiLabelMap"));
    String delPortletHint = "";
    String editAttributeHint = "";
    if (uiLabelMap == null) {
      Debug.logWarning("Could not find uiLabelMap in context", module);
    } else {
      delPortletHint = uiLabelMap.get("CommonDeleteThisPortlet");
      editAttributeHint = uiLabelMap.get("CommonEditPortletAttributes");
    }

    StringWriter sr = new StringWriter();
    sr.append("<@renderPortalPagePortletBegin ");
    sr.append("originalPortalPageId=\"");
    sr.append(originalPortalPageId);
    sr.append("\" portalPageId=\"");
    sr.append(portalPageId);
    sr.append("\" portalPortletId=\"");
    sr.append(portalPortletId);
    sr.append("\" portletSeqId=\"");
    sr.append(portletSeqId);
    sr.append("\" prevPortletId=\"");
    sr.append(prevPortletId);
    sr.append("\" prevPortletSeqId=\"");
    sr.append(prevPortletSeqId);
    sr.append("\" nextPortletId=\"");
    sr.append(nextPortletId);
    sr.append("\" nextPortletSeqId=\"");
    sr.append(nextPortletSeqId);
    sr.append("\" columnSeqId=\"");
    sr.append(columnSeqId);
    sr.append("\" prevColumnSeqId=\"");
    sr.append(prevColumnSeqId);
    sr.append("\" nextColumnSeqId=\"");
    sr.append(nextColumnSeqId);
    sr.append("\" delPortletHint=\"");
    sr.append(delPortletHint);
    sr.append("\" editAttributeHint=\"");
    sr.append(editAttributeHint);
    sr.append("\" confMode=\"");
    sr.append(confMode);
    sr.append("\"");
    if (UtilValidate.isNotEmpty(editFormName) && UtilValidate.isNotEmpty(editFormLocation)) {
      sr.append(" editAttribute=\"true\"");
    }
    sr.append("/>");
    executeMacro(writer, sr.toString());
  }
  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 renderPortalPageColumnBegin(
      Appendable writer,
      Map<String, Object> context,
      ModelScreenWidget.PortalPage portalPage,
      GenericValue portalPageColumn)
      throws GeneralException, IOException {
    String portalPageId = portalPage.getActualPortalPageId();
    String originalPortalPageId = portalPage.getOriginalPortalPageId();
    String columnSeqId = portalPageColumn.getString("columnSeqId");
    String columnWidthPercentage = portalPageColumn.getString("columnWidthPercentage");
    String columnWidthPixels = portalPageColumn.getString("columnWidthPixels");
    String confMode = portalPage.getConfMode(context);

    Map<String, String> uiLabelMap = UtilGenerics.cast(context.get("uiLabelMap"));
    String delColumnLabel = "";
    String delColumnHint = "";
    String addPortletLabel = "";
    String addPortletHint = "";
    String colWidthLabel = "";
    String setColumnSizeHint = "";

    if (uiLabelMap == null) {
      Debug.logWarning("Could not find uiLabelMap in context", module);
    } else {
      delColumnLabel = uiLabelMap.get("CommonDeleteColumn");
      delColumnHint = uiLabelMap.get("CommonDeleteThisColumn");

      addPortletLabel = uiLabelMap.get("CommonAddAPortlet");
      addPortletHint = uiLabelMap.get("CommonAddPortletToPage");
      colWidthLabel = uiLabelMap.get("CommonWidth");
      setColumnSizeHint = uiLabelMap.get("CommonSetColumnWidth");
    }

    StringWriter sr = new StringWriter();
    sr.append("<@renderPortalPageColumnBegin ");
    sr.append("originalPortalPageId=\"");
    sr.append(originalPortalPageId);
    sr.append("\" portalPageId=\"");
    sr.append(portalPageId);
    sr.append("\" columnSeqId=\"");
    sr.append(columnSeqId);
    sr.append("\" ");
    if (UtilValidate.isNotEmpty(columnWidthPixels)) {
      sr.append("width=\"");
      sr.append(columnWidthPixels);
      sr.append("px\"");
    } else if (UtilValidate.isNotEmpty(columnWidthPercentage)) {
      sr.append("width=\"");
      sr.append(columnWidthPercentage);
      sr.append("%\"");
    }
    sr.append(" confMode=\"");
    sr.append(confMode);
    sr.append("\" delColumnLabel=\"");
    sr.append(delColumnLabel);
    sr.append("\" delColumnHint=\"");
    sr.append(delColumnHint);
    sr.append("\" addPortletLabel=\"");
    sr.append(addPortletLabel);
    sr.append("\" addPortletHint=\"");
    sr.append(addPortletHint);
    sr.append("\" colWidthLabel=\"");
    sr.append(colWidthLabel);
    sr.append("\" setColumnSizeHint=\"");
    sr.append(setColumnSizeHint);
    sr.append("\" />");
    executeMacro(writer, sr.toString());
  }
Пример #28
0
 public void runCommands() throws TestCaseException {
   Element root = this.doc.getRootElement();
   List<Element> nodes = UtilGenerics.cast(root.getChildren());
   runCommands(nodes);
 }