/**
   * Returns the next recurrence of this rule.
   *
   * @param startTime The time this recurrence first began.
   * @param fromTime The time to base the next recurrence on.
   * @param currentCount The total number of times the recurrence has run.
   * @return long The next recurrence as a long.
   */
  public long next(long startTime, long fromTime, long currentCount) {
    // Set up the values
    if (startTime == 0) startTime = RecurrenceUtil.now();
    if (fromTime == 0) fromTime = startTime;

    // Test the end time of the recurrence.
    if (getEndTime() != 0 && getEndTime() <= RecurrenceUtil.now()) return 0;
    Debug.logVerbose("Rule NOT expired by end time.", module);

    // Test the recurrence limit.
    if (getCount() != -1 && currentCount >= getCount()) return 0;
    Debug.logVerbose("Rule NOT expired by max count.", module);

    boolean isSeeking = true;
    long nextRuntime = 0;
    long seekTime = fromTime;
    int loopProtection = 0;
    int maxLoop = (10 * 10 * 10 * 10 * 10);

    while (isSeeking && loopProtection < maxLoop) {
      Date nextRun = getNextFreq(startTime, seekTime);
      seekTime = nextRun.getTime();
      if (validByRule(nextRun)) {
        isSeeking = false;
        nextRuntime = nextRun.getTime();
      }
      loopProtection++;
    }
    return nextRuntime;
  }
예제 #2
0
  @Override
  public int doStartTag() throws JspTagException {
    Debug.logVerbose("Starting Iterator Tag...", module);

    if (!defineIterator()) return SKIP_BODY;

    Debug.logVerbose("We now have an iterator.", module);

    if (defineElement()) return EVAL_BODY_AGAIN;
    else return SKIP_BODY;
  }
예제 #3
0
  @Override
  public boolean exec(MethodContext methodContext) {
    Object fieldVal = null;

    if (!mapAcsr.isEmpty()) {
      Map<String, ? extends Object> fromMap = mapAcsr.get(methodContext);

      if (fromMap == null) {
        if (Debug.infoOn())
          Debug.logInfo(
              "Map not found with name " + mapAcsr + ", not copying from this map", module);
        return true;
      }

      fieldVal = fieldAcsr.get(fromMap, methodContext);
    } else {
      // no map name, try the env
      fieldVal = fieldAcsr.get(methodContext);
    }

    if (fieldVal == null) {
      if (Debug.verboseOn())
        Debug.logVerbose(
            "Field value not found with name "
                + fieldAcsr
                + " in Map with name "
                + mapAcsr
                + ", not copying field",
            module);
      return true;
    }

    // note that going to an env field will only work if it came from an env
    // field because if not specified the to-map-name will be set to the map-name
    // to go from a map field to an env field, use the field-to-env operation
    Map<String, Object> toMap = null;

    if (!toMapAcsr.isEmpty()) {
      toMap = toMapAcsr.get(methodContext);
      if (toMap == null) {
        if (Debug.verboseOn())
          Debug.logVerbose("Map not found with name " + toMapAcsr + ", creating new map", module);
        toMap = FastMap.newInstance();
        toMapAcsr.put(methodContext, toMap);
      }
      toFieldAcsr.put(toMap, fieldVal, methodContext);
    } else {
      // no to-map, so put in env
      toFieldAcsr.put(methodContext, fieldVal);
    }

    return true;
  }
예제 #4
0
  /**
   * Generic service to find party by id. By default return the party find by partyId but you can
   * pass searchPartyFirst at false if you want search in partyIdentification before or pass
   * searchAllId at true to find apartyuct with this id (party.partyId and
   * partyIdentification.idValue)
   *
   * @param delegator
   * @param idToFind
   * @param partyIdentificationTypeId
   * @param searchPartyFirst
   * @param searchAllId
   * @return
   * @throws GenericEntityException
   */
  public static List<GenericValue> findPartiesById(
      Delegator delegator,
      String idToFind,
      String partyIdentificationTypeId,
      boolean searchPartyFirst,
      boolean searchAllId)
      throws GenericEntityException {

    if (Debug.verboseOn())
      Debug.logVerbose(
          "Analyze partyIdentification: entered id = "
              + idToFind
              + ", partyIdentificationTypeId = "
              + partyIdentificationTypeId,
          module);

    GenericValue party = null;
    List<GenericValue> partiesFound = null;

    // 1) look if the idToFind given is a real partyId
    if (searchPartyFirst) {
      party = delegator.findByPrimaryKeyCache("Party", UtilMisc.toMap("partyId", idToFind));
    }

    if (searchAllId || (searchPartyFirst && UtilValidate.isEmpty(party))) {
      // 2) Retrieve party in PartyIdentification
      Map<String, String> conditions = UtilMisc.toMap("idValue", idToFind);
      if (UtilValidate.isNotEmpty(partyIdentificationTypeId)) {
        conditions.put("partyIdentificationTypeId", partyIdentificationTypeId);
      }
      partiesFound =
          delegator.findByAndCache(
              "PartyIdentificationAndParty", conditions, UtilMisc.toList("partyId"));
    }

    if (!searchPartyFirst) {
      party = delegator.findByPrimaryKeyCache("Party", UtilMisc.toMap("partyId", idToFind));
    }

    if (UtilValidate.isNotEmpty(party)) {
      if (UtilValidate.isNotEmpty(partiesFound)) partiesFound.add(party);
      else partiesFound = UtilMisc.toList(party);
    }
    if (Debug.verboseOn())
      Debug.logVerbose(
          "Analyze partyIdentification: found party.partyId = "
              + party
              + ", and list : "
              + partiesFound,
          module);
    return partiesFound;
  }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   try {
     Object obj =
         InvokerHelper.createScript(this.parsedScript, GroovyUtil.getBinding(context)).run();
     if (obj != null) {
       return obj;
     } else {
       if (Debug.verboseOn()) {
         Debug.logVerbose(
             "Groovy scriptlet evaluated to null ["
                 + this
                 + "], got no return so inserting nothing.",
             module);
       }
     }
   } catch (Exception e) {
     // handle other things, like the groovy.lang.MissingPropertyException
     Debug.logWarning(
         e,
         "Error evaluating Groovy scriptlet [" + this + "], inserting nothing; error was: " + e,
         module);
   }
   return null;
 }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   try {
     Object obj =
         BshUtil.eval(
             new String(this.chars, this.parseStart, this.parseLength),
             UtilMisc.makeMapWritable(context));
     if (obj != null) {
       return obj;
     } else {
       if (Debug.verboseOn()) {
         Debug.logVerbose(
             "BSH scriptlet evaluated to null ["
                 + this
                 + "], got no return so inserting nothing.",
             module);
       }
     }
   } catch (EvalError e) {
     Debug.logWarning(
         e,
         "Error evaluating BSH scriptlet [" + this + "], inserting nothing; error was: " + e,
         module);
   }
   return null;
 }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   Object obj = null;
   try {
     obj = UelUtil.evaluate(context, new String(this.bracketedOriginal));
   } catch (PropertyNotFoundException e) {
     if (Debug.verboseOn()) {
       Debug.logVerbose("Error evaluating expression " + this + ": " + e, module);
     }
   } catch (Exception e) {
     Debug.logError("Error evaluating expression " + this + ": " + e, module);
   }
   if (obj != null) {
     try {
       // Check for runtime nesting
       String str = (String) obj;
       if (str.contains(openBracket)) {
         FlexibleStringExpander fse = FlexibleStringExpander.getInstance(str);
         return fse.get(context, timeZone, locale);
       }
     } catch (ClassCastException e) {
     }
   }
   return obj;
 }
예제 #8
0
 private void executeMacro(
     Appendable writer, String macroName, Map<String, Object> macroParameters)
     throws IOException, TemplateException {
   StringBuilder sb = new StringBuilder("<@");
   sb.append(macroName);
   if (macroParameters != null) {
     for (Map.Entry<String, Object> parameter : macroParameters.entrySet()) {
       sb.append(' ');
       sb.append(parameter.getKey());
       sb.append("=");
       Object value = parameter.getValue();
       if (value instanceof String) {
         sb.append('"');
         sb.append(((String) value).replaceAll("\"", "\\\\\""));
         sb.append('"');
       } else {
         sb.append(value);
       }
     }
   }
   sb.append(" />");
   if (Debug.verboseOn()) {
     Debug.logVerbose("Executing macro: " + sb, module);
   }
   executeMacro(writer, sb.toString());
 }
예제 #9
0
  /**
   * Runs the service defined in the MapMessage
   *
   * @param message
   * @return Map
   */
  protected Map<String, Object> runService(MapMessage message) {
    Map<String, ? extends Object> context = null;
    String serviceName = null;
    String xmlContext = null;

    try {
      serviceName = message.getString("serviceName");
      xmlContext = message.getString("serviceContext");
      if (serviceName == null || xmlContext == null) {
        Debug.logError("Message received is not an OFB service message. Ignored!", module);
        return null;
      }

      Object o = XmlSerializer.deserialize(xmlContext, dispatcher.getDelegator());

      if (Debug.verboseOn()) Debug.logVerbose("De-Serialized Context --> " + o, module);
      if (ObjectType.instanceOf(o, "java.util.Map")) context = UtilGenerics.checkMap(o);
    } catch (JMSException je) {
      Debug.logError(je, "Problems reading message.", module);
    } catch (Exception e) {
      Debug.logError(e, "Problems deserializing the service context.", module);
    }

    try {
      ModelService model = dispatcher.getDispatchContext().getModelService(serviceName);
      if (!model.export) {
        Debug.logWarning("Attempt to invoke a non-exported service: " + serviceName, module);
        return null;
      }
    } catch (GenericServiceException e) {
      Debug.logError(e, "Unable to get ModelService for service : " + serviceName, module);
    }

    if (Debug.verboseOn()) Debug.logVerbose("Running service: " + serviceName, module);

    Map<String, Object> result = null;
    if (context != null) {
      try {
        result = dispatcher.runSync(serviceName, context);
      } catch (GenericServiceException gse) {
        Debug.logError(gse, "Problems with service invocation.", module);
      }
    }
    return result;
  }
  /**
   * Gets the end time of the recurrence rule or 0 if none.
   *
   * @return long The timestamp of the end time for this rule or 0 for none.
   */
  public long getEndTime() {
    if (rule == null) {
      Debug.logVerbose("Rule is null.", module);
      return -1;
    }
    long time = 0;
    java.sql.Timestamp stamp = null;

    stamp = rule.getTimestamp("untilDateTime");
    Debug.logVerbose("Stamp value: " + stamp, module);

    if (stamp != null) {
      long nanos = stamp.getNanos();
      time = stamp.getTime();
      time += (nanos / 1000000);
    }
    Debug.logVerbose("Returning time: " + time, module);
    return time;
  }
예제 #11
0
  // Load the JMS listeners
  private void loadListeners() {
    try {
      Element rootElement = ServiceConfigUtil.getXmlRootElement();
      NodeList nodeList = rootElement.getElementsByTagName("jms-service");

      if (Debug.verboseOn())
        Debug.logVerbose("[ServiceDispatcher] : Loading JMS Listeners.", module);
      for (int i = 0; i < nodeList.getLength(); i++) {
        Element element = (Element) nodeList.item(i);
        for (Element server : UtilXml.childElementList(element, "server")) {
          try {
            String listenerEnabled = server.getAttribute("listen");

            if (listenerEnabled.equalsIgnoreCase("true")) {
              // create a server key
              StringBuilder serverKey = new StringBuilder();

              serverKey.append(server.getAttribute("jndi-server-name") + ":");
              serverKey.append(server.getAttribute("jndi-name") + ":");
              serverKey.append(server.getAttribute("topic-queue"));
              // store the server element
              servers.put(serverKey.toString(), server);
              // load the listener
              GenericMessageListener listener = loadListener(serverKey.toString(), server);

              // store the listener w/ the key
              if (serverKey.length() > 0 && listener != null)
                listeners.put(serverKey.toString(), listener);
            }
          } catch (GenericServiceException gse) {
            Debug.logVerbose("Cannot load message listener (" + gse.toString() + ").", module);
          } catch (Exception e) {
            Debug.logError(e, "Uncaught exception.", module);
          }
        }
      }
    } catch (org.ofbiz.base.config.GenericConfigException gce) {
      Debug.logError(gce, "Cannot get serviceengine.xml root element.", module);
    } catch (Exception e) {
      Debug.logError(e, "Uncaught exception.", module);
    }
  }
예제 #12
0
파일: Converters.java 프로젝트: BPM15/bpm15
 /**
  * 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);
 }
예제 #13
0
  /**
   * Receives the MapMessage and processes the service.
   *
   * @see javax.jms.MessageListener#onMessage(Message)
   */
  public void onMessage(Message message) {
    MapMessage mapMessage = null;

    if (Debug.verboseOn()) Debug.logVerbose("JMS Message Received --> " + message, module);

    if (message instanceof MapMessage) {
      mapMessage = (MapMessage) message;
    } else {
      Debug.logError("Received message is not a MapMessage!", module);
      return;
    }
    runService(mapMessage);
  }
예제 #14
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;
  }
예제 #15
0
파일: Converters.java 프로젝트: BPM15/bpm15
 public static <S, T> void registerConverter(
     Converter<S, T> converter, Class<?> sourceClass, Class<?> targetClass) {
   StringBuilder sb = new StringBuilder();
   if (sourceClass != null) {
     sb.append(sourceClass.getName());
   } else {
     sb.append("<null>");
   }
   sb.append(DELIMITER);
   sb.append(targetClass.getName());
   String key = sb.toString();
   if (converterMap.putIfAbsent(key, converter) == null) {
     Debug.logVerbose("Registered converter " + converter.getClass().getName(), module);
   }
 }
  public void renderContentBegin(
      Appendable writer, Map<String, Object> context, ModelScreenWidget.Content content)
      throws IOException {
    String editRequest = content.getEditRequest(context);
    String enableEditName = content.getEnableEditName(context);
    String enableEditValue = (String) context.get(enableEditName);

    if (Debug.verboseOn()) Debug.logVerbose("directEditRequest:" + editRequest, module);

    Map<String, Object> parameters = FastMap.newInstance();
    parameters.put("editRequest", editRequest);
    parameters.put("enableEditValue", enableEditValue == null ? "" : enableEditValue);
    parameters.put("editContainerStyle", content.getEditContainerStyle(context));
    executeMacro(writer, "renderContentBegin", parameters);
  }
 private GenericDispatcher(String name, Delegator delegator) {
   ClassLoader loader;
   try {
     loader = Thread.currentThread().getContextClassLoader();
   } catch (SecurityException e) {
     loader = this.getClass().getClassLoader();
   }
   this.name = name;
   this.dispatcher = ServiceDispatcher.getInstance(delegator);
   DispatchContext ctx = new DispatchContext(name, loader, this);
   this.dispatcher.register(ctx);
   this.ctx = ctx;
   if (Debug.verboseOn())
     Debug.logVerbose("[GenericDispatcher] : Created Dispatcher for: " + name, module);
 }
예제 #18
0
 public void run() {
   Debug.logInfo("Starting JMS Listener Factory Thread", module);
   while (firstPass || connected < loadable) {
     if (Debug.verboseOn())
       Debug.logVerbose(
           "First Pass: "******" Connected: " + connected + " Available: " + loadable,
           module);
     this.loadListeners();
     firstPass = false;
     try {
       Thread.sleep(20000);
     } catch (InterruptedException ie) {
     }
     continue;
   }
   Debug.logInfo("JMS Listener Factory Thread Finished; All listeners connected.", module);
 }
예제 #19
0
  /**
   * Compiles and caches a regexp pattern for the given string pattern.
   *
   * @param stringPattern a pattern string
   * @param caseSensitive case sensitive true/false
   * @return compiles and caches a regexp pattern for the given string pattern
   * @throws MalformedPatternException
   */
  private Pattern getTestPattern(String stringPattern, boolean caseSensitive)
      throws MalformedPatternException {
    Pattern pattern = compiledPatterns.get(stringPattern);
    if (pattern == null) {
      if (caseSensitive) {
        pattern = compiler.compile(stringPattern);
      } else {
        pattern = compiler.compile(stringPattern, Perl5Compiler.CASE_INSENSITIVE_MASK);
      }

      compiledPatterns.put(stringPattern, pattern);
      Debug.logVerbose(
          "Compiled and cached a pattern: '" + stringPattern + "' - " + Thread.currentThread(),
          module);
    }
    return pattern;
  }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   try {
     Object obj = UelUtil.evaluate(context, new String(this.valueStr));
     if (obj != null) {
       String currencyCode = this.codeExpr.expandString(context, timeZone, locale);
       return UtilFormatOut.formatCurrency(new BigDecimal(obj.toString()), currencyCode, locale);
     }
   } catch (PropertyNotFoundException e) {
     if (Debug.verboseOn()) {
       Debug.logVerbose("Error evaluating expression: " + e, module);
     }
   } catch (Exception e) {
     Debug.logError("Error evaluating expression: " + e, module);
   }
   return null;
 }
예제 #21
0
  protected void viewHandlerRender(
      String typeToUse, HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    ServletContext context = (ServletContext) request.getAttribute("servletContext");
    RequestHandler requestHandler = (RequestHandler) context.getAttribute("_REQUEST_HANDLER_");

    // see if the type is defined in the controller.xml file
    try {
      if (Debug.verboseOn())
        Debug.logVerbose("Rendering view [" + content + "] of type [" + typeToUse + "]", module);
      ViewHandler vh = requestHandler.getViewFactory().getViewHandler(typeToUse);
      // use the default content-type and encoding for the ViewHandler -- may want to change this.
      vh.render(name, content, info, null, null, request, response);
    } catch (ViewHandlerException e) {
      throw new ServletException(e.getNonNestedMessage(), e.getNested());
    }
  }
예제 #22
0
  private void createAndSendSOAPResponse(
      Map<String, Object> serviceResults, String serviceName, HttpServletResponse response)
      throws EventHandlerException {
    try {
      // setup the response
      Debug.logVerbose("[EventHandler] : Setting up response message", module);
      String xmlResults = SoapSerializer.serialize(serviceResults);
      // Debug.logInfo("xmlResults ==================" + xmlResults, module);
      XMLStreamReader reader =
          XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xmlResults));
      StAXOMBuilder resultsBuilder = new StAXOMBuilder(reader);
      OMElement resultSer = resultsBuilder.getDocumentElement();

      // create the response soap
      SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
      SOAPEnvelope resEnv = factory.createSOAPEnvelope();
      SOAPBody resBody = factory.createSOAPBody();
      OMElement resService = factory.createOMElement(new QName(serviceName + "Response"));
      resService.addChild(resultSer.getFirstElement());
      resBody.addChild(resService);
      resEnv.addChild(resBody);

      // The declareDefaultNamespace method doesn't work see
      // (https://issues.apache.org/jira/browse/AXIS2-3156)
      // so the following doesn't work:
      // resService.declareDefaultNamespace(ModelService.TNS);
      // instead, create the xmlns attribute directly:
      OMAttribute defaultNS = factory.createOMAttribute("xmlns", null, ModelService.TNS);
      resService.addAttribute(defaultNS);

      // log the response message
      if (Debug.verboseOn()) {
        try {
          Debug.logInfo("Response Message:\n" + resEnv + "\n", module);
        } catch (Throwable t) {
        }
      }

      resEnv.serialize(response.getOutputStream());
      response.getOutputStream().flush();
    } catch (Exception e) {
      Debug.logError(e, module);
      throw new EventHandlerException(e.getMessage(), e);
    }
  }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   StringBuilder expr = new StringBuilder(this.hint);
   for (FlexibleStringExpander child : this.childElems) {
     expr.append(child.expandString(context, timeZone, locale));
   }
   if (expr.length() == 0) {
     return "";
   }
   try {
     return UelUtil.evaluate(context, openBracket.concat(expr.toString()).concat(closeBracket));
   } catch (PropertyNotFoundException e) {
     if (Debug.verboseOn()) {
       Debug.logVerbose("Error evaluating expression: " + e, module);
     }
   } catch (Exception e) {
     Debug.logError("Error evaluating expression: " + e, module);
   }
   return "";
 }
  public static void setTrail(
      ServletRequest request, String currentCategory, String previousCategory) {
    if (Debug.verboseOn())
      Debug.logVerbose(
          "[CategoryWorker.setTrail] Start: previousCategory="
              + previousCategory
              + " currentCategory="
              + currentCategory,
          module);

    // if there is no current category, just return and do nothing to that the last settings will
    // stay
    if (UtilValidate.isEmpty(currentCategory)) {
      return;
    }

    // always get the last crumb list
    List<String> crumb = getTrail(request);
    crumb = adjustTrail(crumb, currentCategory, previousCategory);
    setTrail(request, crumb);
  }
  public static List<String> adjustTrail(
      List<String> origTrail, String currentCategoryId, String previousCategoryId) {
    List<String> trail = FastList.newInstance();
    if (origTrail != null) {
      trail.addAll(origTrail);
    }

    // if no previous category was specified, check to see if currentCategory is in the list
    if (UtilValidate.isEmpty(previousCategoryId)) {
      if (trail.contains(currentCategoryId)) {
        // if cur category is in crumb, remove everything after it and return
        int cindex = trail.lastIndexOf(currentCategoryId);

        if (cindex < (trail.size() - 1)) {
          for (int i = trail.size() - 1; i > cindex; i--) {
            trail.remove(i);
            // FIXME can be removed ?
            // String deadCat = trail.remove(i);
            // if (Debug.infoOn()) Debug.logInfo("[CategoryWorker.setTrail] Removed after current
            // category index: " + i + " catname: " + deadCat, module);
          }
        }
        return trail;
      } else {
        // current category is not in the list, and no previous category was specified, go back to
        // the beginning
        trail.clear();
        trail.add("TOP");
        if (UtilValidate.isNotEmpty(previousCategoryId)) {
          trail.add(previousCategoryId);
        }
        // if (Debug.infoOn()) Debug.logInfo("[CategoryWorker.setTrail] Starting new list, added TOP
        // and previousCategory: " + previousCategoryId, module);
      }
    }

    if (!trail.contains(previousCategoryId)) {
      // previous category was NOT in the list, ERROR, start over
      // if (Debug.infoOn()) Debug.logInfo("[CategoryWorker.setTrail] previousCategory (" +
      // previousCategoryId + ") was not in the crumb list, position is lost, starting over with
      // TOP", module);
      trail.clear();
      trail.add("TOP");
      if (UtilValidate.isNotEmpty(previousCategoryId)) {
        trail.add(previousCategoryId);
      }
    } else {
      // remove all categories after the previous category, preparing for adding the current
      // category
      int index = trail.indexOf(previousCategoryId);
      if (index < (trail.size() - 1)) {
        for (int i = trail.size() - 1; i > index; i--) {
          trail.remove(i);
          // FIXME can be removed ?
          // String deadCat = trail.remove(i);
          // if (Debug.infoOn()) Debug.logInfo("[CategoryWorker.setTrail] Removed after current
          // category index: " + i + " catname: " + deadCat, module);
        }
      }
    }

    // add the current category to the end of the list
    trail.add(currentCategoryId);
    if (Debug.verboseOn())
      Debug.logVerbose(
          "[CategoryWorker.setTrail] Continuing list: Added currentCategory: " + currentCategoryId,
          module);

    return trail;
  }
  public static List<GenericValue> getRelatedCategoriesRet(
      Delegator delegator,
      String attributeName,
      String parentId,
      boolean limitView,
      boolean excludeEmpty,
      boolean recursive) {
    List<GenericValue> categories = FastList.newInstance();

    if (Debug.verboseOn())
      Debug.logVerbose("[CategoryWorker.getRelatedCategories] ParentID: " + parentId, module);

    List<GenericValue> rollups = null;

    try {
      rollups =
          delegator.findByAndCache(
              "ProductCategoryRollup",
              UtilMisc.toMap("parentProductCategoryId", parentId),
              UtilMisc.toList("sequenceNum"));
      if (limitView) {
        rollups = EntityUtil.filterByDate(rollups, true);
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
    }
    if (rollups != null) {
      // Debug.logInfo("Rollup size: " + rollups.size(), module);
      for (GenericValue parent : rollups) {
        // Debug.logInfo("Adding child of: " + parent.getString("parentProductCategoryId"), module);
        GenericValue cv = null;

        try {
          cv = parent.getRelatedOneCache("CurrentProductCategory");
        } catch (GenericEntityException e) {
          Debug.logWarning(e.getMessage(), module);
        }
        if (cv != null) {
          if (excludeEmpty) {
            if (!isCategoryEmpty(cv)) {
              // Debug.logInfo("Child : " + cv.getString("productCategoryId") + " is not empty.",
              // module);
              categories.add(cv);
              if (recursive) {
                categories.addAll(
                    getRelatedCategoriesRet(
                        delegator,
                        attributeName,
                        cv.getString("productCategoryId"),
                        limitView,
                        excludeEmpty,
                        recursive));
              }
            }
          } else {
            categories.add(cv);
            if (recursive) {
              categories.addAll(
                  getRelatedCategoriesRet(
                      delegator,
                      attributeName,
                      cv.getString("productCategoryId"),
                      limitView,
                      excludeEmpty,
                      recursive));
            }
          }
        }
      }
    }
    return categories;
  }
예제 #27
0
  /**
   * JavaMail Service that gets body content from a Screen Widget defined in the product store
   * record and if available as attachment also.
   *
   * @param dctx The DispatchContext that this service is operating in
   * @param rServiceContext Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> sendMailFromScreen(
      DispatchContext dctx, Map<String, ? extends Object> rServiceContext) {
    Map<String, Object> serviceContext = UtilMisc.makeMapWritable(rServiceContext);
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String webSiteId = (String) serviceContext.remove("webSiteId");
    String bodyText = (String) serviceContext.remove("bodyText");
    String bodyScreenUri = (String) serviceContext.remove("bodyScreenUri");
    String xslfoAttachScreenLocationParam =
        (String) serviceContext.remove("xslfoAttachScreenLocation");
    String attachmentNameParam = (String) serviceContext.remove("attachmentName");
    List<String> xslfoAttachScreenLocationListParam =
        UtilGenerics.checkList(serviceContext.remove("xslfoAttachScreenLocationList"));
    List<String> attachmentNameListParam =
        UtilGenerics.checkList(serviceContext.remove("attachmentNameList"));

    List<String> xslfoAttachScreenLocationList = FastList.newInstance();
    List<String> attachmentNameList = FastList.newInstance();
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationParam))
      xslfoAttachScreenLocationList.add(xslfoAttachScreenLocationParam);
    if (UtilValidate.isNotEmpty(attachmentNameParam)) attachmentNameList.add(attachmentNameParam);
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationListParam))
      xslfoAttachScreenLocationList.addAll(xslfoAttachScreenLocationListParam);
    if (UtilValidate.isNotEmpty(attachmentNameListParam))
      attachmentNameList.addAll(attachmentNameListParam);

    Locale locale = (Locale) serviceContext.get("locale");
    Map<String, Object> bodyParameters =
        UtilGenerics.checkMap(serviceContext.remove("bodyParameters"));
    if (bodyParameters == null) {
      bodyParameters = MapStack.create();
    }
    if (!bodyParameters.containsKey("locale")) {
      bodyParameters.put("locale", locale);
    } else {
      locale = (Locale) bodyParameters.get("locale");
    }
    String partyId = (String) serviceContext.get("partyId");
    if (partyId == null) {
      partyId = (String) bodyParameters.get("partyId");
    }
    String orderId = (String) bodyParameters.get("orderId");
    String custRequestId = (String) bodyParameters.get("custRequestId");

    bodyParameters.put("communicationEventId", serviceContext.get("communicationEventId"));
    NotificationServices.setBaseUrl(dctx.getDelegator(), webSiteId, bodyParameters);
    String contentType = (String) serviceContext.remove("contentType");

    StringWriter bodyWriter = new StringWriter();

    MapStack<String> screenContext = MapStack.create();
    screenContext.put("locale", locale);
    ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, htmlScreenRenderer);
    screens.populateContextForService(dctx, bodyParameters);
    screenContext.putAll(bodyParameters);

    if (bodyScreenUri != null) {
      try {
        screens.render(bodyScreenUri);
      } catch (GeneralException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      } catch (IOException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      } catch (SAXException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      } catch (ParserConfigurationException e) {
        Debug.logError(e, "Error rendering screen for email: " + e.toString(), module);
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendRenderingScreenEmailError",
                UtilMisc.toMap("errorString", e.toString()),
                locale));
      }
    }

    boolean isMultiPart = false;

    // check if attachment screen location passed in
    if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationList)) {
      List<Map<String, ? extends Object>> bodyParts = FastList.newInstance();
      if (bodyText != null) {
        bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
        bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyText, "type", "text/html"));
      } else {
        bodyParts.add(
            UtilMisc.<String, Object>toMap("content", bodyWriter.toString(), "type", "text/html"));
      }

      for (int i = 0; i < xslfoAttachScreenLocationList.size(); i++) {
        String xslfoAttachScreenLocation = xslfoAttachScreenLocationList.get(i);
        String attachmentName = "Details.pdf";
        if (UtilValidate.isNotEmpty(attachmentNameList) && attachmentNameList.size() >= i) {
          attachmentName = attachmentNameList.get(i);
        }
        isMultiPart = true;
        // start processing fo pdf attachment
        try {
          Writer writer = new StringWriter();
          MapStack<String> screenContextAtt = MapStack.create();
          // substitute the freemarker variables...
          ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContext, foScreenRenderer);
          screensAtt.populateContextForService(dctx, bodyParameters);
          screenContextAtt.putAll(bodyParameters);
          screensAtt.render(xslfoAttachScreenLocation);

          /*
          try { // save generated fo file for debugging
              String buf = writer.toString();
              java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("/tmp/file1.xml"));
              fw.write(buf.toString());
              fw.close();
          } catch (IOException e) {
              Debug.logError(e, "Couldn't save xsl-fo xml debug file: " + e.toString(), module);
          }
          */

          // create the input stream for the generation
          StreamSource src = new StreamSource(new StringReader(writer.toString()));

          // create the output stream for the generation
          ByteArrayOutputStream baos = new ByteArrayOutputStream();

          Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
          ApacheFopWorker.transform(src, null, fop);

          // and generate the PDF
          baos.flush();
          baos.close();

          // store in the list of maps for sendmail....
          bodyParts.add(
              UtilMisc.<String, Object>toMap(
                  "content",
                  baos.toByteArray(),
                  "type",
                  "application/pdf",
                  "filename",
                  attachmentName));
        } catch (GeneralException ge) {
          Debug.logError(ge, "Error rendering PDF attachment for email: " + ge.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", ge.toString()),
                  locale));
        } catch (IOException ie) {
          Debug.logError(ie, "Error rendering PDF attachment for email: " + ie.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", ie.toString()),
                  locale));
        } catch (FOPException fe) {
          Debug.logError(fe, "Error rendering PDF attachment for email: " + fe.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", fe.toString()),
                  locale));
        } catch (SAXException se) {
          Debug.logError(se, "Error rendering PDF attachment for email: " + se.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", se.toString()),
                  locale));
        } catch (ParserConfigurationException pe) {
          Debug.logError(pe, "Error rendering PDF attachment for email: " + pe.toString(), module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resource,
                  "CommonEmailSendRenderingScreenPdfError",
                  UtilMisc.toMap("errorString", pe.toString()),
                  locale));
        }

        serviceContext.put("bodyParts", bodyParts);
      }
    } else {
      isMultiPart = false;
      // store body and type for single part message in the context.
      if (bodyText != null) {
        bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale);
        serviceContext.put("body", bodyText);
      } else {
        serviceContext.put("body", bodyWriter.toString());
      }

      // Only override the default contentType in case of plaintext, since other contentTypes may be
      // multipart
      //    and would require specific handling.
      if (contentType != null && contentType.equalsIgnoreCase("text/plain")) {
        serviceContext.put("contentType", "text/plain");
      } else {
        serviceContext.put("contentType", "text/html");
      }
    }

    // also expand the subject at this point, just in case it has the FlexibleStringExpander syntax
    // in it...
    String subject = (String) serviceContext.remove("subject");
    subject = FlexibleStringExpander.expandString(subject, screenContext, locale);
    Debug.logInfo("Expanded email subject to: " + subject, module);
    serviceContext.put("subject", subject);
    serviceContext.put("partyId", partyId);
    if (UtilValidate.isNotEmpty(orderId)) {
      serviceContext.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(custRequestId)) {
      serviceContext.put("custRequestId", custRequestId);
    }

    if (Debug.verboseOn())
      Debug.logVerbose("sendMailFromScreen sendMail context: " + serviceContext, module);

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, Object> sendMailResult;
    try {
      if (isMultiPart) {
        sendMailResult = dispatcher.runSync("sendMailMultiPart", serviceContext);
      } else {
        sendMailResult = dispatcher.runSync("sendMail", serviceContext);
      }
    } catch (Exception e) {
      Debug.logError(e, "Error send email:" + e.toString(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendError",
              UtilMisc.toMap("errorString", e.toString()),
              locale));
    }
    if (ServiceUtil.isError(sendMailResult)) {
      return ServiceUtil.returnError(ServiceUtil.getErrorMessage(sendMailResult));
    }

    result.put("messageWrapper", sendMailResult.get("messageWrapper"));
    result.put("body", bodyWriter.toString());
    result.put("subject", subject);
    result.put("communicationEventId", sendMailResult.get("communicationEventId"));
    if (UtilValidate.isNotEmpty(orderId)) {
      result.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(custRequestId)) {
      result.put("custRequestId", custRequestId);
    }
    return result;
  }
예제 #28
0
  @Override
  public void render(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {
    ServletContext context = (ServletContext) request.getAttribute("servletContext");
    boolean verboseOn = Debug.verboseOn();

    if (verboseOn) Debug.logVerbose("Rendering " + this.toString(), module);

    // long viewStartTime = System.currentTimeMillis();
    if (content != null) {
      if ("direct".equals(type)) {
        if (UtilJ2eeCompat.useOutputStreamNotWriter(context)) {
          response.getOutputStream().print(content);
        } else {
          response.getWriter().print(content);
        }
      } else if ("default".equals(type)
          || "region".equals(type)
          || "resource".equals(type)
          || "jpublish".equals(type)) {
        // if type is resource then we won't even look up the region

        // if this is default or region, check to see if the content points to a valid region name
        Region region = null;

        if ("default".equals(type) || "region".equals(type)) {
          region = regionManager.getRegion(content);
        }

        if ("region".equals(type) || region != null) {
          if (region == null) {
            throw new IllegalArgumentException("No region definition found with name: " + content);
          }
          // render the content as a region
          RegionStack.push(request, region);
          region.render(request, response);
          RegionStack.pop(request);
        } else if ("jpublish".equals(type)) {
          // rather then using the view handler use the wrapper directly
          /* NOTE: In order to use the "jpublish" section type the JPublish libraries must be added as described in OPTIONAL_LIBRARIES and then uncomment this section
          ServletContext sctx = (ServletContext) request.getAttribute("servletContext");
          if (sctx != null) {
              JPublishWrapper jp = this.getJPublishWrapper(sctx);
              if (jp != null) {
                  String contentStr = "<!-- " + content + " Not Processed -->";
                  try {
                      contentStr = jp.render(content, request, response);
                  } catch (GeneralException e) {
                      Debug.logError(e, "Problems rendering view from JPublish", module);
                  }
                  if (UtilJ2eeCompat.useOutputStreamNotWriter(context)) {
                      response.getOutputStream().print(contentStr);
                  } else {
                      response.getWriter().print(contentStr);
                  }
              } else {
                  throw new IllegalStateException("No jpublishWrapper found in ServletContext");
              }
          } else {
              throw new IllegalStateException("No servletContext found in request");
          }
           */
        } else {
          // default is the string that the ViewFactory expects for webapp resources
          viewHandlerRender("default", request, response);
        }
      } else {
        viewHandlerRender(type, request, response);
      }
    }
    if (verboseOn) Debug.logVerbose("DONE Rendering " + this.toString(), module);
  }
예제 #29
0
  /**
   * Basic JavaMail Service
   *
   * @param ctx The DispatchContext that this service is operating in
   * @param context Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> sendMail(
      DispatchContext ctx, Map<String, ? extends Object> context) {
    String communicationEventId = (String) context.get("communicationEventId");
    String orderId = (String) context.get("orderId");
    Locale locale = (Locale) context.get("locale");
    if (communicationEventId != null) {
      Debug.logInfo("SendMail Running, for communicationEventId : " + communicationEventId, module);
    }
    Map<String, Object> results = ServiceUtil.returnSuccess();
    String subject = (String) context.get("subject");
    subject = FlexibleStringExpander.expandString(subject, context);

    String partyId = (String) context.get("partyId");
    String body = (String) context.get("body");
    List<Map<String, Object>> bodyParts = UtilGenerics.checkList(context.get("bodyParts"));
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    results.put("communicationEventId", communicationEventId);
    results.put("partyId", partyId);
    results.put("subject", subject);

    if (UtilValidate.isNotEmpty(orderId)) {
      results.put("orderId", orderId);
    }
    if (UtilValidate.isNotEmpty(body)) {
      body = FlexibleStringExpander.expandString(body, context);
      results.put("body", body);
    }
    if (UtilValidate.isNotEmpty(bodyParts)) {
      results.put("bodyParts", bodyParts);
    }
    results.put("userLogin", userLogin);

    String sendTo = (String) context.get("sendTo");
    String sendCc = (String) context.get("sendCc");
    String sendBcc = (String) context.get("sendBcc");

    // check to see if we should redirect all mail for testing
    String redirectAddress =
        UtilProperties.getPropertyValue("general.properties", "mail.notifications.redirectTo");
    if (UtilValidate.isNotEmpty(redirectAddress)) {
      String originalRecipients = " [To: " + sendTo + ", Cc: " + sendCc + ", Bcc: " + sendBcc + "]";
      subject += originalRecipients;
      sendTo = redirectAddress;
      sendCc = null;
      sendBcc = null;
    }

    String sendFrom = (String) context.get("sendFrom");
    String sendType = (String) context.get("sendType");
    String port = (String) context.get("port");
    String socketFactoryClass = (String) context.get("socketFactoryClass");
    String socketFactoryPort = (String) context.get("socketFactoryPort");
    String socketFactoryFallback = (String) context.get("socketFactoryFallback");
    String sendVia = (String) context.get("sendVia");
    String authUser = (String) context.get("authUser");
    String authPass = (String) context.get("authPass");
    String messageId = (String) context.get("messageId");
    String contentType = (String) context.get("contentType");
    Boolean sendPartial = (Boolean) context.get("sendPartial");
    Boolean isStartTLSEnabled = (Boolean) context.get("startTLSEnabled");

    boolean useSmtpAuth = false;

    // define some default
    if (sendType == null || sendType.equals("mail.smtp.host")) {
      sendType = "mail.smtp.host";
      if (UtilValidate.isEmpty(sendVia)) {
        sendVia =
            UtilProperties.getPropertyValue(
                "general.properties", "mail.smtp.relay.host", "localhost");
      }
      if (UtilValidate.isEmpty(authUser)) {
        authUser = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.user");
      }
      if (UtilValidate.isEmpty(authPass)) {
        authPass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.password");
      }
      if (UtilValidate.isNotEmpty(authUser)) {
        useSmtpAuth = true;
      }
      if (UtilValidate.isEmpty(port)) {
        port = UtilProperties.getPropertyValue("general.properties", "mail.smtp.port");
      }
      if (UtilValidate.isEmpty(socketFactoryPort)) {
        socketFactoryPort =
            UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.port");
      }
      if (UtilValidate.isEmpty(socketFactoryClass)) {
        socketFactoryClass =
            UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.class");
      }
      if (UtilValidate.isEmpty(socketFactoryFallback)) {
        socketFactoryFallback =
            UtilProperties.getPropertyValue(
                "general.properties", "mail.smtp.socketFactory.fallback", "false");
      }
      if (sendPartial == null) {
        sendPartial =
            UtilProperties.propertyValueEqualsIgnoreCase(
                    "general.properties", "mail.smtp.sendpartial", "true")
                ? true
                : false;
      }
      if (isStartTLSEnabled == null) {
        isStartTLSEnabled =
            UtilProperties.propertyValueEqualsIgnoreCase(
                "general.properties", "mail.smtp.starttls.enable", "true");
      }
    } else if (sendVia == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "CommonEmailSendMissingParameterSendVia", locale));
    }

    if (contentType == null) {
      contentType = "text/html";
    }

    if (UtilValidate.isNotEmpty(bodyParts)) {
      contentType = "multipart/mixed";
    }
    results.put("contentType", contentType);

    Session session;
    MimeMessage mail;
    try {
      Properties props = System.getProperties();
      props.put(sendType, sendVia);
      if (UtilValidate.isNotEmpty(port)) {
        props.put("mail.smtp.port", port);
      }
      if (UtilValidate.isNotEmpty(socketFactoryPort)) {
        props.put("mail.smtp.socketFactory.port", socketFactoryPort);
      }
      if (UtilValidate.isNotEmpty(socketFactoryClass)) {
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
      }
      if (UtilValidate.isNotEmpty(socketFactoryFallback)) {
        props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);
      }
      if (useSmtpAuth) {
        props.put("mail.smtp.auth", "true");
      }
      if (sendPartial != null) {
        props.put("mail.smtp.sendpartial", sendPartial ? "true" : "false");
      }
      if (isStartTLSEnabled) {
        props.put("mail.smtp.starttls.enable", "true");
      }

      session = Session.getInstance(props);
      boolean debug =
          UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.debug.on", "Y");
      session.setDebug(debug);

      mail = new MimeMessage(session);
      if (messageId != null) {
        mail.setHeader("In-Reply-To", messageId);
        mail.setHeader("References", messageId);
      }
      mail.setFrom(new InternetAddress(sendFrom));
      mail.setSubject(subject, "UTF-8");
      mail.setHeader("X-Mailer", "Apache OFBiz, The Apache Open For Business Project");
      mail.setSentDate(new Date());
      mail.addRecipients(Message.RecipientType.TO, sendTo);

      if (UtilValidate.isNotEmpty(sendCc)) {
        mail.addRecipients(Message.RecipientType.CC, sendCc);
      }
      if (UtilValidate.isNotEmpty(sendBcc)) {
        mail.addRecipients(Message.RecipientType.BCC, sendBcc);
      }

      if (UtilValidate.isNotEmpty(bodyParts)) {
        // check for multipart message (with attachments)
        // BodyParts contain a list of Maps items containing content(String) and type(String) of the
        // attachement
        MimeMultipart mp = new MimeMultipart();
        Debug.logInfo(bodyParts.size() + " multiparts found", module);
        for (Map<String, Object> bodyPart : bodyParts) {
          Object bodyPartContent = bodyPart.get("content");
          MimeBodyPart mbp = new MimeBodyPart();

          if (bodyPartContent instanceof String) {
            Debug.logInfo(
                "part of type: "
                    + bodyPart.get("type")
                    + " and size: "
                    + bodyPart.get("content").toString().length(),
                module);
            mbp.setText(
                (String) bodyPartContent, "UTF-8", ((String) bodyPart.get("type")).substring(5));
          } else if (bodyPartContent instanceof byte[]) {
            ByteArrayDataSource bads =
                new ByteArrayDataSource((byte[]) bodyPartContent, (String) bodyPart.get("type"));
            Debug.logInfo(
                "part of type: "
                    + bodyPart.get("type")
                    + " and size: "
                    + ((byte[]) bodyPartContent).length,
                module);
            mbp.setDataHandler(new DataHandler(bads));
          } else if (bodyPartContent instanceof DataHandler) {
            mbp.setDataHandler((DataHandler) bodyPartContent);
          } else {
            mbp.setDataHandler(new DataHandler(bodyPartContent, (String) bodyPart.get("type")));
          }

          String fileName = (String) bodyPart.get("filename");
          if (fileName != null) {
            mbp.setFileName(fileName);
          }
          mp.addBodyPart(mbp);
        }
        mail.setContent(mp);
        mail.saveChanges();
      } else {
        // create the singelpart message
        if (contentType.startsWith("text")) {
          mail.setText(body, "UTF-8", contentType.substring(5));
        } else {
          mail.setContent(body, contentType);
        }
        mail.saveChanges();
      }
    } catch (MessagingException e) {
      Debug.logError(
          e,
          "MessagingException when creating message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      Debug.logError(
          "Email message that could not be created to [" + sendTo + "] had context: " + context,
          module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendMessagingException",
              UtilMisc.toMap(
                  "sendTo",
                  sendTo,
                  "sendFrom",
                  sendFrom,
                  "sendCc",
                  sendCc,
                  "sendBcc",
                  sendBcc,
                  "subject",
                  subject),
              locale));
    } catch (IOException e) {
      Debug.logError(
          e,
          "IOExcepton when creating message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      Debug.logError(
          "Email message that could not be created to [" + sendTo + "] had context: " + context,
          module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendIOException",
              UtilMisc.toMap(
                  "sendTo",
                  sendTo,
                  "sendFrom",
                  sendFrom,
                  "sendCc",
                  sendCc,
                  "sendBcc",
                  sendBcc,
                  "subject",
                  subject),
              locale));
    }

    // check to see if sending mail is enabled
    String mailEnabled =
        UtilProperties.getPropertyValue("general.properties", "mail.notifications.enabled", "N");
    if (!"Y".equalsIgnoreCase(mailEnabled)) {
      // no error; just return as if we already processed
      Debug.logImportant(
          "Mail notifications disabled in general.properties; mail with subject ["
              + subject
              + "] not sent to addressee ["
              + sendTo
              + "]",
          module);
      Debug.logVerbose(
          "What would have been sent, the addressee: "
              + sendTo
              + " subject: "
              + subject
              + " context: "
              + context,
          module);
      results.put("messageWrapper", new MimeMessageWrapper(session, mail));
      return results;
    }

    Transport trans = null;
    try {
      trans = session.getTransport("smtp");
      if (!useSmtpAuth) {
        trans.connect();
      } else {
        trans.connect(sendVia, authUser, authPass);
      }
      trans.sendMessage(mail, mail.getAllRecipients());
      results.put("messageWrapper", new MimeMessageWrapper(session, mail));
      results.put("messageId", mail.getMessageID());
      trans.close();
    } catch (SendFailedException e) {
      // message code prefix may be used by calling services to determine the cause of the failure
      Debug.logError(
          e,
          "[ADDRERR] Address error when sending message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      List<SMTPAddressFailedException> failedAddresses = FastList.newInstance();
      Exception nestedException = null;
      while ((nestedException = e.getNextException()) != null
          && nestedException instanceof MessagingException) {
        if (nestedException instanceof SMTPAddressFailedException) {
          SMTPAddressFailedException safe = (SMTPAddressFailedException) nestedException;
          Debug.logError(
              "Failed to send message to ["
                  + safe.getAddress()
                  + "], return code ["
                  + safe.getReturnCode()
                  + "], return message ["
                  + safe.getMessage()
                  + "]",
              module);
          failedAddresses.add(safe);
          break;
        }
      }
      Boolean sendFailureNotification = (Boolean) context.get("sendFailureNotification");
      if (sendFailureNotification == null || sendFailureNotification) {
        sendFailureNotification(ctx, context, mail, failedAddresses);
        results.put("messageWrapper", new MimeMessageWrapper(session, mail));
        try {
          results.put("messageId", mail.getMessageID());
          trans.close();
        } catch (MessagingException e1) {
          Debug.logError(e1, module);
        }
      } else {
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resource,
                "CommonEmailSendAddressError",
                UtilMisc.toMap(
                    "sendTo",
                    sendTo,
                    "sendFrom",
                    sendFrom,
                    "sendCc",
                    sendCc,
                    "sendBcc",
                    sendBcc,
                    "subject",
                    subject),
                locale));
      }
    } catch (MessagingException e) {
      // message code prefix may be used by calling services to determine the cause of the failure
      Debug.logError(
          e,
          "[CON] Connection error when sending message to ["
              + sendTo
              + "] from ["
              + sendFrom
              + "] cc ["
              + sendCc
              + "] bcc ["
              + sendBcc
              + "] subject ["
              + subject
              + "]",
          module);
      Debug.logError(
          "Email message that could not be sent to [" + sendTo + "] had context: " + context,
          module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendConnectionError",
              UtilMisc.toMap(
                  "sendTo",
                  sendTo,
                  "sendFrom",
                  sendFrom,
                  "sendCc",
                  sendCc,
                  "sendBcc",
                  sendBcc,
                  "subject",
                  subject),
              locale));
    }
    return results;
  }
예제 #30
0
 @Override
 public boolean exec(MethodContext methodContext) throws MiniLangException {
   if (UtilValidate.isEmpty(this.methodName)) {
     throw new MiniLangRuntimeException("method-name attribute is empty", this);
   }
   SimpleMethod simpleMethodToCall = SimpleMethod.getSimpleMethod(this.xmlURL, this.methodName);
   if (simpleMethodToCall == null) {
     throw new MiniLangRuntimeException(
         "Could not find <simple-method name=\""
             + this.methodName
             + "\"> in XML document "
             + this.xmlResource,
         this);
   }
   MethodContext localContext = methodContext;
   if ("function".equals(this.scope)) {
     Map<String, Object> localEnv = new HashMap<String, Object>();
     localEnv.putAll(methodContext.getEnvMap());
     localEnv.remove(this.simpleMethod.getEventResponseCodeName());
     localEnv.remove(this.simpleMethod.getServiceResponseMessageName());
     localContext =
         new MethodContext(localEnv, methodContext.getLoader(), methodContext.getMethodType());
   }
   String returnVal = simpleMethodToCall.exec(localContext);
   if (Debug.verboseOn())
     Debug.logVerbose(
         "Called simple-method named ["
             + this.methodName
             + "] in resource ["
             + this.xmlResource
             + "], returnVal is ["
             + returnVal
             + "]",
         module);
   if (simpleMethodToCall.getDefaultErrorCode().equals(returnVal)) {
     if (methodContext.getMethodType() == MethodContext.EVENT) {
       methodContext.putEnv(
           simpleMethod.getEventResponseCodeName(), simpleMethod.getDefaultErrorCode());
     } else if (methodContext.getMethodType() == MethodContext.SERVICE) {
       methodContext.putEnv(
           simpleMethod.getServiceResponseMessageName(), simpleMethod.getDefaultErrorCode());
     }
     return false;
   }
   if (methodContext.getMethodType() == MethodContext.EVENT) {
     // FIXME: This doesn't make sense. We are comparing the called method's response code with
     // this method's
     // response code. Since response codes are configurable per method, this code will fail.
     String responseCode =
         (String) localContext.getEnv(this.simpleMethod.getEventResponseCodeName());
     if (this.simpleMethod.getDefaultErrorCode().equals(responseCode)) {
       Debug.logWarning(
           "Got error ["
               + responseCode
               + "] calling inline simple-method named ["
               + this.methodName
               + "] in resource ["
               + this.xmlResource
               + "], message is "
               + methodContext.getEnv(this.simpleMethod.getEventErrorMessageName()),
           module);
       return false;
     }
   } else if (methodContext.getMethodType() == MethodContext.SERVICE) {
     // FIXME: This doesn't make sense. We are comparing the called method's response message with
     // this method's
     // response message. Since response messages are configurable per method, this code will fail.
     String responseMessage =
         (String) localContext.getEnv(this.simpleMethod.getServiceResponseMessageName());
     if (this.simpleMethod.getDefaultErrorCode().equals(responseMessage)) {
       Debug.logWarning(
           "Got error ["
               + responseMessage
               + "] calling inline simple-method named ["
               + this.methodName
               + "] in resource ["
               + this.xmlResource
               + "], message is "
               + methodContext.getEnv(this.simpleMethod.getServiceErrorMessageName())
               + ", and the error message list is: "
               + methodContext.getEnv(this.simpleMethod.getServiceErrorMessageListName()),
           module);
       return false;
     }
   }
   if ("function".equals(this.scope) && this.resultToFieldList != null) {
     Map<String, Object> results = localContext.getResults();
     if (results != null) {
       for (ResultToField resultToField : this.resultToFieldList) {
         resultToField.exec(methodContext.getEnvMap(), results);
       }
     }
   }
   return true;
 }