コード例 #1
0
  /**
   * This adds a special check for exceptions that occured because the session is down. In this
   * case, the error count will not be increased so that the message will be resent when the session
   * comes back up.
   *
   * @param e Exception
   * @param queueMessage QueueMessage
   * @param queue MessageQueue
   * @throws QueueException
   */
  public void handleError(Exception e, QueueMessage queueMessage, MessageQueue queue)
      throws QueueException {

    if (e instanceof ConnectivityDownException) {

      // The session is down. Set the error message, but do not
      // increment the error count.
      NPACMessageType message = (NPACMessageType) queueMessage;
      NPACQueueUtils.updateLastErrorMessage(message.getInvokeID().toString(), e.getMessage());

    } else {

      if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {
        Debug.log(
            Debug.MSG_STATUS,
            "NPACConsumerPolicy, handleError(), Before removing REGION ID...queueMessage.getValues():-"
                + queueMessage.getValues());
      }

      Map queueMessageValues = queueMessage.getValues();

      if (queueMessageValues.containsKey("REGIONID")) {
        queueMessageValues.remove("REGIONID");
        queueMessage.setValues(queueMessageValues);
      }

      if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {
        Debug.log(
            Debug.MSG_STATUS,
            "NPACConsumerPolicy, handleError(), After removing REGION ID...queueMessage.getValues():-"
                + queueMessage.getValues());
      }
      super.handleError(e, queueMessage, queue);
    }
  }
コード例 #2
0
  /** Stops the Poll Comm Servers identified by parameters. */
  public void stop(Map params) {
    if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
      Debug.log(Debug.NORMAL_STATUS, "Stopping Poll Comm Server [" + getType() + "] " + params);

    String id = (String) params.get(ATTR_COMM_SERVER_ID);

    CommServerConf commServerConf = commServerConfMap.get(id);

    if (commServerConf == null) {
      Debug.log(Debug.MSG_WARNING, "No configured poll comm server found with ID[" + id + "]");
      return;
    }

    ComServerBase commServer = commServerConf.getCommServer();

    if (commServer == null) {
      return;
    } else {
      commServer.shutdown();
      commServerConf.setCommServer(null);
      commServerConf.setStarted(false);
    }

    /* update configuration with the latest status. */
    updateXML(ELEM_POLL_COMM_SERVER, ATTR_COMM_SERVER_ID, id, ATTR_COMM_SERVER_START, "false");

    if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
      Debug.log(Debug.NORMAL_STATUS, "done stopping poll comm server [" + getType() + "] " + id);
  }
コード例 #3
0
  /**
   * Get all configuration for a specified server type placed in repository. This would search the
   * servicemgr category inside repository and apply XPath to figure out configuration files
   * belonging to a specific server type.
   *
   * @param type
   * @return List containing file names.
   * @throws ProcessingException
   */
  public static List<String> getConfigCategory(String type) throws ProcessingException {

    NVPair[] pairs = null;
    try {
      pairs =
          RepositoryManager.getInstance()
              .listMetaData(ServerManagerFactory.MGR_CONFIG_CATEGORY, false, XML_FILE_SUFFIX);

      if (pairs == null || pairs.length == 0) {
        Debug.log(
            Debug.NORMAL_STATUS,
            "No XML file found in repository folder ["
                + ServerManagerFactory.MGR_CONFIG_CATEGORY
                + "]");

        return null;
      }
    } catch (Exception e) {
      Debug.error(
          "An exception occured while listing xml files from repository folder ["
              + ServerManagerFactory.MGR_CONFIG_CATEGORY
              + "]");

      Debug.logStackTrace(e);

      throw new ProcessingException(
          "An exception occured while listing xml files from repository folder  ["
              + ServerManagerFactory.MGR_CONFIG_CATEGORY
              + "]");
    }

    List<String> cfgFileLst = new ArrayList<String>();
    String fileNm = null;
    try {
      for (int j = 0; j < pairs.length; j++) {
        fileNm = pairs[j].name;
        Document document = getDocument(fileNm);
        ParsedXPath parseXpath = new ParsedXPath(serverType2Xpath.get(type));

        if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
          Debug.log(Debug.NORMAL_STATUS, " --> Evaluating file :" + fileNm + " for type :" + type);

        if (parseXpath.getBooleanValue(document.getDocumentElement())) cfgFileLst.add(fileNm);
      }

      if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
        Debug.log(
            Debug.NORMAL_STATUS,
            " --> returning list of files for type[" + type + "] : " + cfgFileLst);

      return cfgFileLst;
    } catch (Exception e) {
      Debug.log(
          Debug.NORMAL_STATUS,
          "Failed to parse and evaluate XPath on file :" + fileNm + "\n" + Debug.getStackTrace(e));

      throw new ProcessingException(
          "Failed to parse and evaluate XPath on file :" + fileNm + "\n" + Debug.getStackTrace(e));
    }
  }
コード例 #4
0
  /**
   * Stops all the running Poll Comm Servers.
   *
   * @throws ProcessingException
   */
  public void stopAll() throws ProcessingException {
    if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
      Debug.log(Debug.NORMAL_STATUS, "Stopping all poll comm servers : " + getType());

    Iterator iter = commServerConfMap.keySet().iterator();

    while (iter.hasNext()) {
      String id = (String) iter.next();
      Map map = Collections.singletonMap(ATTR_COMM_SERVER_ID, id);
      Notification notification = null;
      try {
        stop(map);
        notification = new Notification("Stopped poll comm server : " + id);
      } catch (Exception e) {
        Debug.log(
            Debug.MSG_WARNING,
            "Exception while stopping poll comm server " + id + " " + e.getMessage());
        Debug.log(Debug.MSG_WARNING, e.getMessage());
        notification =
            new Notification("Exception occured while stopping Poll Comm Server: " + id, e);
      }
      notificationHandler.handle(notification);
    }
    if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
      Debug.log(Debug.NORMAL_STATUS, "done stopping all services .. ");
  }
コード例 #5
0
  /**
   * Starts all the configured Poll Comm Servers
   *
   * @throws ProcessingException
   */
  public void startAll() throws ProcessingException {
    if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
      Debug.log(Debug.NORMAL_STATUS, "Starting All Comm Server of type = " + getType());

    Iterator iter = commServerConfMap.keySet().iterator();
    while (iter.hasNext()) {
      String id = (String) iter.next();
      CommServerConf conf = commServerConfMap.get(id);
      if (conf.isStarted()) {
        Notification notification = null;
        Map params = Collections.singletonMap(ATTR_COMM_SERVER_ID, id);
        try {
          start(params);
          notification =
              new Notification("Started Comm Server of type = " + getType() + " id : " + id);
        } catch (Exception e) {
          Debug.log(
              Debug.MSG_ERROR,
              "Could not start Comm Server of type = " + getType() + " id : " + id);
          Debug.error(Debug.getStackTrace(e));
          notification =
              new Notification(
                  "Error starting Comm Server of type = " + getType() + " id : " + id, e);
        }
        notificationHandler.handle(notification);
      }
    }
    if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
      Debug.log(Debug.NORMAL_STATUS, "done starting Comm Servers of type = " + getType());
  }
コード例 #6
0
ファイル: RegexUtils.java プロジェクト: harishgupta111/SOA
  /**
   * This function takes a perl5 regular expression as the pattern to perform pattern matching and
   * string substitution.
   *
   * <p>"s/pattern/replacement/[g][i][m][o][s][x]"
   *
   * <p>g - substitute globally (all occurence) i - case insensitive m - treat the input as
   * consisting of multiple lines o - interpolate once s - treat the input as consisting of a single
   * line x - enable extended expression syntax incorporating whitespace and comments
   *
   * <p>to perform string substitution. Unless the [g] option is specified, the dafault is to
   * replace only the first occurrence.
   *
   * @param perl5Pattern - Perl5 regular expression
   * @param input - input string
   * @return result - processed string. The original input is returned when there is no match
   * @exception - FrameworkException is thrown when either pattern or input is null
   */
  public static String substitute(String perl5Pattern, String input) throws FrameworkException {
    if ((perl5Pattern == null) || (input == null)) {
      throw new FrameworkException(
          "RegexUtil: replaceAll(): Either input or pattern is null."
              + "input = "
              + input
              + ", "
              + "pattern = "
              + perl5Pattern);
    }

    if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {
      Debug.log(
          Debug.MSG_STATUS,
          "RegexUtils: replaceAll: perl5Pattern = " + perl5Pattern + " input = " + input);
    }

    Perl5Util util = new Perl5Util();
    String result = input;

    try {
      result = util.substitute(perl5Pattern, input);
    } catch (RuntimeException e) {
      throw new FrameworkException("RegexUtils: substitute: " + e.getMessage());
    }

    return result;
  }
コード例 #7
0
  public static HashMap<String, String> getNancValueMapping() {
    if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {
      Debug.log(Debug.MSG_STATUS, className + " : Returning Hash map...");
    }

    return map;
  }
コード例 #8
0
ファイル: RegexUtils.java プロジェクト: harishgupta111/SOA
  /**
   * This function composes the perl regular expression to perform pattern matching with negative
   * look ahead. This becomes handy when a replacement string includes some string that is also a
   * pattern.
   *
   * <p>i.e.) pattern - & replacement - &quot, &amp
   *
   * @param pattern - pattern string to match
   * @param replacements - an array of replacement strings
   * @return returns the format pattern for perl5 negative look-ahead
   * @exception throws a FrameworkException when the pattern/replacement is null.
   */
  private static String makePerl5MatchPatternNegativeLookAhead(
      String pattern, String replacements[]) throws FrameworkException {
    if (pattern == null || replacements.length < 0) {
      throw new FrameworkException(
          "RegexUtils: makePerl5MatchPatternNegativeLookAhead: pattern or replacement is null."
              + "\npattern = "
              + pattern
              + "\nreplacements.length = "
              + replacements.length);
    }

    String result = null;
    StringBuffer patternBuffer = new StringBuffer();

    Perl5Util util = new Perl5Util();
    String formatPattern = makePerl5MatchPattern(pattern);

    for (int i = 0; i < replacements.length; i++) {
      if (util.match(formatPattern, replacements[i])) {
        if (replacements[i].startsWith(pattern)) {
          result = util.postMatch();

          // very first one
          if (i == 0) {
            patternBuffer.append(pattern);
            patternBuffer.append("(?!");
          }
          patternBuffer.append(result);

          // the last one
          if (i == (replacements.length - 1)) {
            patternBuffer.append(")");
          } else // not the last one, cat the perl5 separater
          {
            patternBuffer.append("|");
          }

        } else {
          throw new FrameworkException(
              "ERROR: RegexUtils: makePerl5MatchPatternNegativeLookAhead: The pattern in the "
                  + "replacement string should be at the beginning.");
        }
      } else // no match found meaning invalid use of this function
      {
        throw new FrameworkException(
            "ERROR: RegexUtils: makePerl5MatchPatternNegativeLookAhead: "
                + "Invalid use of the function.");
      }
    }

    if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {
      Debug.log(
          Debug.MSG_STATUS,
          "RegexUtils: makePerl5MatchPatternNegativeLookAhead: patternBuffer.toString() = "
              + patternBuffer.toString());
    }

    return patternBuffer.toString();
  }
コード例 #9
0
ファイル: Splitter.java プロジェクト: harishgupta111/SOA
  /**
   * Initializes the Splitter.
   *
   * @param key Property-key to use for locating initialization properties.
   * @param type Property-type to use for locating initialization properties.
   * @exception ProcessingException when initialization fails
   */
  public void initialize(String key, String type) throws ProcessingException {

    // Call the abstract super class's initialize method. This initializes
    // the adapterProperties hashtable defined in the super class and
    // retrieves the name and toProcessorNames values from the properties.
    super.initialize(key, type);

    if (Debug.isLevelEnabled(Debug.OBJECT_LIFECYCLE))
      Debug.log(Debug.OBJECT_LIFECYCLE, "Splitter: Initializing.....");

    StringBuffer errorBuffer = new StringBuffer();
    truncHeaderFooter = getRequiredPropertyValue(TRUNCATE_HEADER_FOOTER_PROP, errorBuffer);

    if (Debug.isLevelEnabled(Debug.MSG_DATA))
      Debug.log(Debug.MSG_DATA, "Splitter: truncHeaderFooter? ---->" + truncHeaderFooter);

    String temp = getPropertyValue(FILE_SEPARATOR_PROP);
    if (StringUtils.hasValue(temp)) {
      fileSeparator = StringUtils.replaceSubstrings(temp, "\\r", "\r");
      fileSeparator = StringUtils.replaceSubstrings(fileSeparator, "\\n", "\n");
      if (Debug.isLevelEnabled(Debug.MSG_DATA))
        Debug.log(Debug.MSG_DATA, "Splitter: fileSeparator---->" + fileSeparator);
    }

    try {
      splitLength = Integer.parseInt(getRequiredPropertyValue(SPLIT_LENGTH_PROP, errorBuffer));

      if (Debug.isLevelEnabled(Debug.MSG_DATA))
        Debug.log(Debug.MSG_DATA, "Splitter: splitLength---->" + splitLength);
    } catch (NumberFormatException nx) {
      throw new ProcessingException("ERROR: Splitter: The SPLIT_LENGTH " + "must be a number.");
    }

    if (splitLength <= 0) {
      throw new ProcessingException(
          "ERROR: Splitter: The SPLIT_LENGTH " + "must be greater than zero.");
    }

    if (errorBuffer.length() > 0) {
      String errMsg = errorBuffer.toString();

      Debug.log(Debug.ALL_ERRORS, errMsg);

      throw new ProcessingException(errMsg);
    }
  }
コード例 #10
0
  /** Constructor. */
  public DatabaseEventQueue() {
    if (Debug.isLevelEnabled(Debug.OBJECT_LIFECYCLE))
      Debug.log(
          Debug.OBJECT_LIFECYCLE,
          "QUEUE OPERATION: Creating event queue of type ["
              + StringUtils.getClassName(this)
              + "] ...");

    queue = Collections.synchronizedList(new LinkedList());
  }
コード例 #11
0
  public void flushCache() throws FrameworkException {

    if (Debug.isLevelEnabled(Debug.OBJECT_LIFECYCLE)) {

      Debug.log(Debug.OBJECT_LIFECYCLE, className + " : Flushing disabled-rules cache ...");
    }

    synchronized (map) {
      map.clear();
    }
  }
コード例 #12
0
  /*
   * This boolen method is used to check whether Hash map is cached or not.
   */
  public static boolean isNancMapCached() {
    if (map.size() > 0) {

      if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {

        Debug.log(Debug.MSG_STATUS, className + " : Hash map for NANC mapping is in cache");
      }

      return true;

    } else {

      if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {

        Debug.log(Debug.MSG_STATUS, className + " : Hash map for NANC mapping is NOT in cache");
      }

      return false;
    }
  }
コード例 #13
0
  /*
   * A single private instance of this class will be created to assist in cache flushing.
   */
  private NancValueMapping() {

    if (Debug.isLevelEnabled(Debug.SYSTEM_CONFIG))
      Debug.log(Debug.SYSTEM_CONFIG, className + " : Initializing...");

    try {
      CacheManager.getRegistrar().register(this);

    } catch (Exception e) {
      Debug.warning(e.toString());
    }
  }
コード例 #14
0
  /**
   * Initialize the event queue.
   *
   * @param props A container of configuration properties.
   * @exception FrameworkException Thrown if configuration is invalid.
   */
  public void initialize(Map props) throws FrameworkException {
    String temp = (String) props.get(LOAD_EVENT_BATCH_SIZE_PROP);

    if (StringUtils.hasValue(temp)) {
      maxDatabaseEventLoadSize = StringUtils.getInteger(temp);

      if (Debug.isLevelEnabled(Debug.SYSTEM_CONFIG))
        Debug.log(
            Debug.SYSTEM_CONFIG,
            "QUEUE OPERATION: Initializing: Maximum-database-event-batch-load-size is ["
                + maxDatabaseEventLoadSize
                + "] rows.");
    }
  }
コード例 #15
0
  /**
   * Get the next queued item. Must be called after hasNext().
   *
   * @return The next item in the queue to process.
   * @exception FrameworkException Thrown on errors.
   */
  public Event next() throws FrameworkException {
    if (queue.size() == 0) {
      throw new FrameworkException("ERROR: Attempt was made to retrieve event from empty queue.");
    }

    Event event = (Event) queue.get(0);

    if (Debug.isLevelEnabled(Debug.MSG_STATUS))
      Debug.log(
          Debug.MSG_STATUS,
          "QUEUE OPERATION: Retrieving the following event from the database queue:\n"
              + event.describe());

    return event;
  }
コード例 #16
0
  @Override
  public NVPair[] process(MessageProcessorContext mpContext, MessageObject inputObject)
      throws MessageException, ProcessingException {
    if (inputObject == null) return null;
    /*
     * Load the value of configured properties
     */
    for (PPDataHolder holder : ppData) {
      String propertyValue = null;
      try {
        boolean useCustomerId = StringUtils.getBoolean(holder.getUseCustomerId());

        if (useCustomerId)
          propertyValue =
              PersistentProperty.get(
                  holder.getKey(), holder.getPropertyType(), holder.getPropertyName());
        else {
          String customerId = CustomerContext.getInstance().getCustomerID();
          CustomerContext.getInstance().setCustomerID(CustomerContext.DEFAULT_CUSTOMER_ID);
          propertyValue =
              PersistentProperty.get(
                  holder.getKey(), holder.getPropertyType(), holder.getPropertyName());
          CustomerContext.getInstance().setCustomerID(customerId);
        }

      } catch (Exception ex) {
        Debug.warning(
            "Unable to get configured property from persistent property :" + holder.toString());
      }

      /*
       * set the value into message processor context
       */
      if (StringUtils.hasValue(propertyValue)) {
        if (Debug.isLevelEnabled(Debug.DB_DATA))
          Debug.log(
              Debug.DB_DATA,
              " setting value :" + propertyValue + " on location :" + holder.getOutputLoc());

        mpContext.set(holder.getOutputLoc(), propertyValue);
      }
    }

    /* Always return input value to provide pass-through semantics. */
    return (formatNVPair(inputObject));
  }
コード例 #17
0
  /**
   * Returns 'true' if the queue has more items to process.
   *
   * @param criteria An event containing the event-selection criteria.
   * @return 'true' if queue has more items to process, otherwise 'false'.
   * @exception FrameworkException Thrown on errors.
   */
  public boolean hasNext(Event criteria) throws FrameworkException {
    boolean available = (queue.size() > 0);

    // If no events are available in memory, attempt to get more from the database.
    if (!available) {
      loadFromDatabase(criteria);

      available = (queue.size() > 0);
    }

    if (Debug.isLevelEnabled(Debug.MSG_STATUS))
      Debug.log(
          Debug.MSG_STATUS,
          "QUEUE OPERATION: Events available in database queue? [" + available + "].");

    return available;
  }
コード例 #18
0
  @Override
  public void initialize(String key, String type) throws ProcessingException {

    super.initialize(key, type);

    for (int Ix = 0; true; Ix++) {
      String propKey = getPropertyValue(PersistentProperty.getPropNameIteration(KEY_PROP, Ix));

      if (!StringUtils.hasValue(propKey)) break;

      PPDataHolder holder =
          new PPDataHolder(
              propKey,
              getPropertyValue(PersistentProperty.getPropNameIteration(PROPERTY_TYPE_PROP, Ix)),
              getPropertyValue(PersistentProperty.getPropNameIteration(PROPERTY_NAME_PROP, Ix)),
              getPropertyValue(PersistentProperty.getPropNameIteration(OUTPUT_LOCATION_PROP, Ix)),
              getPropertyValue(PersistentProperty.getPropNameIteration(USE_CUSTOMER_ID_PROP, Ix)));

      ppData.add(holder);

      if (Debug.isLevelEnabled(Debug.SYSTEM_CONFIG))
        Debug.log(Debug.SYSTEM_CONFIG, " Found configured property :" + holder);
    }
  }
コード例 #19
0
ファイル: Splitter.java プロジェクト: harishgupta111/SOA
  /**
   * This gets a String to be split in the message object.It splits the string into substrings and
   * then stores them in the message object to be apssed to the next processors individually. This
   * class expects at least a single next processor hence it return a null if there are no next
   * processors.
   *
   * @param msgObj The MesageObject containg the string.
   * @return NVPair[] Name-Value pair array of next processor name and the MessageObject
   * @exception ProcessingException Thrown if processing fails
   */
  public NVPair[] process(MessageProcessorContext context, MessageObject msgObj)
      throws MessageException, ProcessingException {

    if (Debug.isLevelEnabled(Debug.BENCHMARK))
      Debug.log(Debug.BENCHMARK, "Reached Splitter process method..");

    // Debug.log(null, Debug.UNIT_TEST,"MESSAGE OBJECT RECEIVED:--->"+msgObj.describe());

    if (msgObj == null) {
      return null;
    } else if (toProcessorNames == null) {
      Debug.log(Debug.ALL_WARNINGS, "Splitter: No next processors available. Hence exiting.");
    } else if (!(msgObj.get() instanceof String)) {
      if (Debug.isLevelEnabled(Debug.UNIT_TEST))
        Debug.log(Debug.UNIT_TEST, "SPLITTER : UNIT_TEST: " + ((msgObj.get()).getClass()));

      throw new ProcessingException("ERROR: Splitter: " + "The msg Object must be a String.");
    }

    if (Debug.isLevelEnabled(Debug.UNIT_TEST))
      Debug.log(Debug.UNIT_TEST, "MESSAGE OBJECT RECEIVED:--->" + msgObj.describe());

    String batchedRecords = msgObj.getString();

    List singleRecord;
    String subStr = "";
    // to take care empty batch files that are valid files in some cases
    if (!StringUtils.hasValue(batchedRecords)) {
      Debug.log(Debug.ALL_WARNINGS, "MESSAGE CONTENT IS NULL");
      return null;
    }

    if (!StringUtils.hasValue(fileSeparator)) // if fileseparator is false...
    {
      if (batchedRecords.length() < splitLength) {
        throw new MessageException(
            "ERROR: Splitter: " + "Batched String length is less than " + splitLength + "bytes.");
      }

      float tempSize = (float) (batchedRecords.length()) / splitLength;
      int size = (batchedRecords.length()) / splitLength;

      // check for length of string
      if (size != tempSize) {
        throw new MessageException(
            "ERROR: Splitter: " + "Record received is not of correct length");
      }
      singleRecord = new Vector(size);
      int i = 0;
      for (i = 0; i < size; i++) {

        subStr = batchedRecords.substring(i * splitLength, (i + 1) * splitLength);
        singleRecord.add(i, subStr);
      }
    } else // if fileseparator is true...
    {
      singleRecord = new Vector();
      StringTokenizer st = new StringTokenizer(batchedRecords, fileSeparator);
      while (st.hasMoreTokens()) {
        subStr = st.nextToken();
        if (subStr.length() != splitLength) {
          throw new MessageException(
              "ERROR: Splitter: Record "
                  + "received after removing the fileseparator is not of correct length .");
        }
        singleRecord.add(subStr);

        if (Debug.isLevelEnabled(Debug.UNIT_TEST))
          Debug.log(
              Debug.UNIT_TEST,
              "\nDATA\n" + "********************************************" + subStr);
      }
    }

    if (getBoolean(truncHeaderFooter)) // if truncHeaderFooter is true...
    {
      singleRecord.remove((singleRecord.size() - 1));
      singleRecord.remove(0);
    }
    // else continue...
    int batchedSize = singleRecord.size();

    if (Debug.isLevelEnabled(Debug.UNIT_TEST))
      Debug.log(Debug.UNIT_TEST, "BATCHED SIZE--->" + batchedSize);

    int processorsNo = toProcessorNames.length;
    NVPair[] contents = new NVPair[batchedSize * processorsNo];
    int i = 0;

    for (i = 0; i < batchedSize; i++) {
      MessageObject mObj = new MessageObject();
      mObj.set(singleRecord.get(i));

      // Sending the message objects to the next processors.
      for (int j = 0; j < processorsNo; j++) {

        contents[(i * (processorsNo)) + j] = new NVPair(toProcessorNames[j], mObj);

        if (Debug.isLevelEnabled(Debug.UNIT_TEST))
          Debug.log(
              Debug.UNIT_TEST,
              "NEXT PROCESSOR-->"
                  + toProcessorNames[j]
                  + "\n"
                  + "MESSAGE OBJECT CONTENT------------>"
                  + mObj.describe());
      }
    }

    if (Debug.isLevelEnabled(Debug.UNIT_TEST))
      Debug.log(Debug.UNIT_TEST, "SPLITTER : CONTEXT---->" + context.describe());

    return contents;
  }
コード例 #20
0
  /*
   * (non-Javadoc)
   *
   * @see com.nightfire.comms.servicemgr.ServerManagerBase#initialize()
   */
  @Override
  public void initialize() throws ProcessingException {

    if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
      Debug.log(Debug.NORMAL_STATUS, "initializing poll comm server : " + getType());

    // read configuration from repository
    // String categoryConfig =
    // ServerManagerFactory.getInstance().getConfigCategory(getType());
    String categoryConfig = ServerManagerFactory.MGR_CONFIG_CATEGORY;
    // String metaConfig =
    // ServerManagerFactory.getInstance().getConfigMeta(getType());

    List<String> configCategory = ServerManagerFactory.getInstance().getConfigCategory(getType());
    XMLMessageParser fileParser = null;

    Document aggregatedDoc;
    try {
      aggregatedDoc = XMLLibraryPortabilityLayer.getNewDocument(getType(), null);
    } catch (MessageException me) {
      Debug.logStackTrace(me);
      throw new ProcessingException(me);
    }

    ServiceIdFilter idFilter = new ServiceIdFilter();
    for (String fileNm : configCategory) {

      String xmlDescription;
      try {
        xmlDescription = RepositoryManager.getInstance().getMetaData(categoryConfig, fileNm);
        fileParser = new XMLMessageParser(xmlDescription);
        fileParser = idFilter.getFilteredDOM(fileParser, ServiceMgrConsts.POLL_COMM_SERVER_CONFIG);
        Element document = fileParser.getDocument().getDocumentElement();
        Node node = aggregatedDoc.importNode(document, true);
        aggregatedDoc.getDocumentElement().appendChild(node);

      } catch (Exception e) {
        Debug.error(
            "Unable to load and parse configuration from repository "
                + categoryConfig
                + " "
                + fileNm);
        throw new ProcessingException(e);
      }

      NodeList list = fileParser.getDocument().getElementsByTagName(ELEM_POLL_COMM_SERVER);
      for (int Ix = 0; Ix < list.getLength(); Ix++) {
        if (list.item(Ix) != null) {
          Element pollCommServerElement = (Element) list.item(Ix);

          String id, key, value, start, pollCommServerType;

          id =
              getConfigurationValue(
                  pollCommServerElement, ConfigType.ATTRIBUTE, ATTR_COMM_SERVER_ID, null);
          key =
              getConfigurationValue(
                  pollCommServerElement, ConfigType.ELEMENT, ELEM_COMM_SERVER_KEY, null);
          value =
              getConfigurationValue(
                  pollCommServerElement, ConfigType.ELEMENT, ELEM_COMM_SERVER_TYPE, null);
          start =
              getConfigurationValue(
                  pollCommServerElement, ConfigType.ATTRIBUTE, ATTR_COMM_SERVER_START, "true");
          pollCommServerType =
              getConfigurationValue(pollCommServerElement, ConfigType.ATTRIBUTE, "type", null);

          if (!StringUtils.hasValue(id)
              || !StringUtils.hasValue(key)
              || !StringUtils.hasValue(value)) {
            Debug.log(
                Debug.XML_ERROR,
                "Could not configure Poll Comm Server since mandatory property are not configured");
            Debug.log(Debug.DB_ERROR, ELEM_POLL_COMM_SERVER + "=" + getType());
            Debug.log(Debug.DB_ERROR, ATTR_COMM_SERVER_ID + "=" + id);
            Debug.log(Debug.DB_ERROR, ELEM_COMM_SERVER_KEY + "=" + key);
            Debug.log(Debug.DB_ERROR, ELEM_COMM_SERVER_TYPE + "=" + value);

            // skip to initialize FTP Poller server if not
            // configured correctly.
            continue;
          }

          boolean startFlag = "false".equalsIgnoreCase(start) ? false : true;

          CommServerConf commServerConf = new CommServerConf(key, value, pollCommServerType);
          commServerConf.setStarted(startFlag);

          NodeList paramList = pollCommServerElement.getElementsByTagName(ELEM_PARAM);
          if (paramList != null) {
            for (int i = 0; i < paramList.getLength(); i++) {
              Element paramElement = (Element) paramList.item(i);

              String paramNm =
                  getConfigurationValue(paramElement, ConfigType.ATTRIBUTE, "name", null);

              String paramVal =
                  getConfigurationValue(paramElement, ConfigType.ATTRIBUTE, "value", null);

              commServerConf.setParamValue(paramNm, paramVal);

              if (Debug.isLevelEnabled(Debug.OBJECT_LIFECYCLE))
                Debug.log(
                    Debug.OBJECT_LIFECYCLE,
                    "Setting param [" + paramNm + "] value [" + paramVal + "]");
            }
          }

          if (id == null)
            Debug.log(
                Debug.MSG_ERROR, "Could not initialize poll comm server with id [" + id + "].");
          else commServerConfMap.put(id, commServerConf);
        }
      }
    }

    try {
      parser = new XMLMessageParser(aggregatedDoc);
    } catch (Exception e) {
      throw new ProcessingException("Unable to create XMLMessageParser object " + e.getMessage());
    }

    if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
      Debug.log(
          Debug.NORMAL_STATUS,
          "done initializing poll comm servers of type [" + getType() + "].. ");
  }
コード例 #21
0
  /** Constructor */
  public AsyncTimerServer(String key, String type) throws ProcessingException {
    super(key, type);

    if (Debug.isLevelEnabled(Debug.OBJECT_LIFECYCLE))
      Debug.log(Debug.OBJECT_LIFECYCLE, "Done initializing AsyncTimerServer .");
  }
コード例 #22
0
  /**
   * Start the Poll Comm Server identified by parameters.
   *
   * @param parameters identifies the Consumer to be started
   * @throws ProcessingException when unable to start the server.
   */
  public void start(Map parameters) throws ProcessingException {
    if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
      Debug.log(
          Debug.NORMAL_STATUS, "Starting Poll Comm Server [" + getType() + "]: " + parameters);

    String id = (String) parameters.get(ATTR_COMM_SERVER_ID);

    if (id == null) {
      Debug.log(Debug.MSG_WARNING, "Could not start a Poll Comm Server with id [" + id + "].");
      return;
    }

    CommServerConf comServerConf = commServerConfMap.get(id);
    if (comServerConf == null) {
      if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
        Debug.log(
            Debug.NORMAL_STATUS,
            "Could not start a Poll Comm Server with id["
                + id
                + "] since Poll Comm Server "
                + "was not already configured.");
    } else {
      ComServerBase commServer = comServerConf.getCommServer();
      if (commServer == null) {
        if (ServiceMgrConsts.FTP_POLLER.equals(comServerConf.getServerType())) {
          if ("true".equals(comServerConf.getParamVal(SSL_PARAM_NM))) {
            commServer =
                new com.nightfire.comms.ftp.ssl.FTPPoller(
                    comServerConf.getDriverKey(), comServerConf.getDriverType());
          } else {
            commServer =
                new com.nightfire.comms.ftp.java.FTPPoller(
                    comServerConf.getDriverKey(), comServerConf.getDriverType());
          }
        } else if (ServiceMgrConsts.ASYNC_TIMER_SERVER.equals(comServerConf.getServerType())) {
          commServer =
              new AsyncTimerServer(comServerConf.getDriverKey(), comServerConf.getDriverType());
        } else if (ServiceMgrConsts.FILE_SERVER.equals(comServerConf.getServerType())) {
          commServer =
              new AsyncFileServer(comServerConf.getDriverKey(), comServerConf.getDriverType());
        } else if (ServiceMgrConsts.SRM_EVENT_SERVER.equals(comServerConf.getServerType())) {
          commServer =
              new MultiCustomerEventConsumerServer(
                  comServerConf.getDriverKey(), comServerConf.getDriverType());
        } else if (ServiceMgrConsts.SRM_CONFIGURED_QUEUES_JMS_SERVER.equals(
            comServerConf.getServerType())) {
          commServer =
              new JMSQueueEventConsumerServer(
                  comServerConf.getDriverKey(), comServerConf.getDriverType());
        } else if (ServiceMgrConsts.SRM_JMS_SERVER.equals(comServerConf.getServerType())) {
          commServer =
              new MultiCustomerJMSConsumerServer(
                  comServerConf.getDriverKey(), comServerConf.getDriverType());
        } else if (ServiceMgrConsts.IA_SERVER.equals(comServerConf.getServerType())) {
          try {
            commServer = new IAServer(comServerConf.getDriverKey(), comServerConf.getDriverType());
          } catch (FrameworkException e) {
            throw new ProcessingException(e);
          }
        }

        comServerConf.setCommServer(commServer);
        new Thread(commServer).start();
      } else {
        if (Debug.isLevelEnabled(Debug.NORMAL_STATUS))
          Debug.log(Debug.NORMAL_STATUS, "Poll Comm Server is already started [" + getType() + "]");
      }
    }

    // update configuration with the latest status.
    updateXML(ELEM_POLL_COMM_SERVER, ATTR_COMM_SERVER_ID, id, ATTR_COMM_SERVER_START, "true");
  }
コード例 #23
0
  /**
   * Add the event to the end of queue.
   *
   * @param event The event to add to the queue.
   * @exception FrameworkException Thrown on errors.
   */
  public void add(Event event) throws FrameworkException {
    Debug.log(Debug.MSG_STATUS, "QUEUE OPERATION: Adding event to database queue ...");

    Connection dbConn = null;

    PreparedStatement ps = null;

    long startTime = -1;

    if (Debug.isLevelEnabled(Debug.BENCHMARK)) startTime = System.currentTimeMillis();

    try {
      event.id = PersistentSequence.getNextSequenceValue(SEQUENCE_NAME);

      dbConn = DBConnectionPool.getInstance().acquireConnection();

      event.arrivalTime = new java.sql.Timestamp(System.currentTimeMillis());

      if (Debug.isLevelEnabled(Debug.DB_DATA))
        Debug.log(Debug.DB_DATA, "\n" + LINE + "\nExecuting SQL:\n" + INSERT_EVENT_SQL);

      if (Debug.isLevelEnabled(Debug.DB_DATA))
        Debug.log(Debug.DB_DATA, "Event being inserted into database:\n" + event.describe());

      if (Debug.isLevelEnabled(Debug.MSG_DATA))
        Debug.log(Debug.MSG_DATA, "Event contents:\n" + event.message);

      ps = dbConn.prepareStatement(INSERT_EVENT_SQL);

      ps.setString(1, event.channelName);
      ps.setInt(2, event.id);

      DBLOBUtils.setCLOB(ps, 3, event.message);

      ps.setTimestamp(4, event.arrivalTime);

      int numRows = ps.executeUpdate();

      if (numRows != 1) {
        String errMsg =
            "Execution of SQL statement ["
                + INSERT_EVENT_SQL
                + "] affected ["
                + numRows
                + "] rows.";

        Debug.error(errMsg);

        throw new FrameworkException(errMsg);
      }

      DBConnectionPool.getInstance().commit(dbConn);

      if (Debug.isLevelEnabled(Debug.DB_DATA))
        Debug.log(Debug.DB_DATA, "Successfully committed SQL operation.\n" + LINE);

      // NOTE: We don't add the item just inserted into the database into the in-memory
      // queue, as we want it loaded by the separate dequeueing thread.
    } catch (SQLException sqle) {
      throw new DatabaseException(
          "ERROR: Could not execute SQL statement:\n" + DBInterface.getSQLErrorMessage(sqle));
    } catch (Exception e) {
      throw new DatabaseException("ERROR: Could not execute SQL statement:\n" + e.toString());
    } finally {
      releaseDatabaseResources(dbConn, ps);

      if (Debug.isLevelEnabled(Debug.BENCHMARK) && (startTime > 0)) {
        long stopTime = System.currentTimeMillis();

        Debug.log(
            Debug.BENCHMARK,
            "ELAPSED TIME ["
                + (stopTime - startTime)
                + "] msec:  "
                + "SQL: Time to insert event into PersistentEvent database table.");
      }
    }
  }
コード例 #24
0
  /**
   * The message obtained from the queue was successfully processed. The corresponding message in
   * the message table gets updated to have a status of "Sent".
   *
   * <p>The message then gets deleted from the queue.
   *
   * @param message The message being processed.
   * @param queue The queue to which this message belongs.
   * @throws QueueException If processing fails.
   */
  public void handleSuccess(QueueMessage queueMessage, MessageQueue queue) throws QueueException {

    if (!(queueMessage instanceof NPACMessageType)) {

      Debug.error(
          "NPAC consumer policy received a message "
              + "that is not of type: "
              + NPACMessageType.class.getName());

    } else {

      NPACMessageType message = (NPACMessageType) queueMessage;

      // update message status to "Sent"

      // construct update statement
      String update = "UPDATE " + message.getTableName() + UPDATE_CLAUSE;

      try {

        Connection connection = DBInterface.acquireConnection();

        try {

          PreparedStatement stmt = null;

          try {

            stmt = connection.prepareStatement(update);

            int invokeID = message.getInvokeID().intValue();
            Debug.log(
                Debug.DB_STATUS,
                "Updating status of message with invoke ID ["
                    + invokeID
                    + "] to 'Sent' using statement:\n"
                    + update);

            stmt.setInt(1, invokeID);

            stmt.execute();
            connection.commit();

          } catch (Exception ex) {
            Debug.error("Could not update status for message:\n" + message.describe() + "\n" + ex);
          } finally {

            try {
              if (stmt != null) {
                stmt.close();
              }
            } catch (Exception ex) {
              Debug.error("Could not close statement: " + ex);
            }
          }

        } finally {

          try {
            DBInterface.releaseConnection(connection);
          } catch (Exception ex) {
            Debug.error("Could not release database connection: " + ex);
          }
        }

      } catch (DatabaseException dbex) {

        Debug.error(
            "Could not update status for message:\n"
                + message.describe()
                + ". A database connection could not be acquired: "
                + dbex);
      }
    }

    // This is used in the where clause to identify which message
    // should be updated. All we need is the message's ID
    // value to uniquely identify it.
    NPACMessageType whereMessage = new NPACMessageType();
    Map whereValues = new HashMap();
    whereValues.put(ID_COL, queueMessage.getValues().get(ID_COL));
    whereMessage.setValues(whereValues);

    // update the status of the message to "sent"
    NPACMessageType newMessage = new NPACMessageType();

    if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {
      Debug.log(
          Debug.MSG_STATUS,
          "NPACConsumerPolicy, handleSuccess(), Before removing REGION ID... values :-"
              + queueMessage.getValues());
    }

    Map value = queueMessage.getValues();
    if (value.containsKey("REGIONID")) {
      value.remove("REGIONID");
    }
    newMessage.setValues(value);

    if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {
      Debug.log(
          Debug.MSG_STATUS,
          "NPACConsumerPolicy, handleSuccess(), After removing region id, values :-"
              + newMessage.getValues());
    }
    newMessage.setStatus(SOAConstants.SENT_STATUS);
    queue.update(whereMessage, newMessage);
  }
コード例 #25
0
  /**
   * Reset any events meeting the given criteria so that they can be retried.
   *
   * @param criteria An event containing the event-selection criteria.
   * @return The number of events reset.
   * @exception FrameworkException Thrown on errors.
   */
  protected static int reset(Event criteria) throws FrameworkException {
    Debug.log(
        Debug.MSG_STATUS, "QUEUE OPERATION: Resetting events in database for database queue ...");

    if (!StringUtils.hasValue(criteria.channelName)) {
      throw new FrameworkException(
          "ERROR: Event channel name is a required queue search criteria.");
    }

    Connection dbConn = null;

    PreparedStatement ps = null;

    long startTime = -1;

    if (Debug.isLevelEnabled(Debug.BENCHMARK)) startTime = System.currentTimeMillis();

    try {
      dbConn = DBConnectionPool.getInstance().acquireConnection();

      if (Debug.isLevelEnabled(Debug.DB_DATA))
        Debug.log(
            Debug.DB_DATA, "Criteria used to reset events in database:\n" + criteria.describe());

      // If no identifier was given that uniquely identifies a single event ...
      if (criteria.id == 0) {
        // Use last error time and error count, if available.
        if (Debug.isLevelEnabled(Debug.DB_DATA))
          Debug.log(Debug.DB_DATA, "\n" + LINE + "\nExecuting SQL:\n" + UPDATE_EVENT_RETRY_SQL);

        ps = dbConn.prepareStatement(UPDATE_EVENT_RETRY_SQL);

        ps.setString(1, criteria.channelName);

        if (criteria.lastErrorTime == null) ps.setNull(2, Types.DATE);
        else ps.setTimestamp(2, criteria.lastErrorTime);

        if (criteria.errorCount < 1) ps.setNull(3, Types.INTEGER);
        else ps.setInt(3, criteria.errorCount);
      } else {
        // An Id was given which should uniquely identify a single event, so we should
        // skip using any other qualifying criteria, if present.
        if (Debug.isLevelEnabled(Debug.DB_DATA))
          Debug.log(
              Debug.DB_DATA, "\n" + LINE + "\nExecuting SQL:\n" + UPDATE_EVENT_RETRY_BY_ID_SQL);

        ps = dbConn.prepareStatement(UPDATE_EVENT_RETRY_BY_ID_SQL);

        ps.setString(1, criteria.channelName);

        ps.setInt(2, criteria.id);
      }

      int numRows = ps.executeUpdate();

      DBConnectionPool.getInstance().commit(dbConn);

      if (Debug.isLevelEnabled(Debug.DB_DATA))
        Debug.log(
            Debug.DB_DATA, "Committed SQL execution affected [" + numRows + "] rows.\n" + LINE);

      return numRows;
    } catch (SQLException sqle) {
      throw new DatabaseException(
          "ERROR: Could not execute SQL statement:\n" + DBInterface.getSQLErrorMessage(sqle));
    } catch (Exception e) {
      throw new DatabaseException("ERROR: Could not execute SQL statement:\n" + e.toString());
    } finally {
      releaseDatabaseResources(dbConn, ps);

      if (Debug.isLevelEnabled(Debug.BENCHMARK) && (startTime > 0)) {
        long stopTime = System.currentTimeMillis();

        Debug.log(
            Debug.BENCHMARK,
            "ELAPSED TIME ["
                + (stopTime - startTime)
                + "] msec:  "
                + "SQL: Time to reset event(s) in PersistentEvent database table.");
      }
    }
  }
コード例 #26
0
  /**
   * Update the given event as indicated.
   *
   * @param event The event to update.
   * @param eventStatus The event delivery status.
   * @exception FrameworkException Thrown on errors.
   */
  public void update(Event event, EventStatus eventStatus) throws FrameworkException {
    if (Debug.isLevelEnabled(Debug.MSG_STATUS))
      Debug.log(
          Debug.MSG_STATUS,
          "QUEUE OPERATION: Updating database queue using event status ["
              + eventStatus.name
              + "] ...");

    // If no consumers were available, the event delivery wasn't attempted so leave
    // the queue in its current state.
    if (eventStatus == EventStatus.NO_CONSUMERS_AVAILABLE) {
      Debug.log(
          Debug.MSG_STATUS, "Skipping queue update, as no consumers were available to process it.");

      return;
    }

    Connection dbConn = null;

    PreparedStatement ps = null;

    long startTime = -1;

    if (Debug.isLevelEnabled(Debug.BENCHMARK)) startTime = System.currentTimeMillis();

    try {
      dbConn = DBConnectionPool.getInstance().acquireConnection();

      if (eventStatus == EventStatus.DELIVERY_SUCCESSFUL) {
        // If the event was successfully delivered, update status in database to delivered.
        if (Debug.isLevelEnabled(Debug.DB_DATA))
          Debug.log(Debug.DB_DATA, "\n" + LINE + "\nExecuting SQL:\n" + UPDATE_EVENT_SUCCESS_SQL);

        ps = dbConn.prepareStatement(UPDATE_EVENT_SUCCESS_SQL);

        java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis());

        ps.setTimestamp(1, ts);
        ps.setString(2, event.channelName);
        ps.setInt(3, event.id);
      } else if (eventStatus == EventStatus.DELIVERY_FAILED) {
        // If the event delivery failed, we mark it as failed in the database.
        if (Debug.isLevelEnabled(Debug.DB_DATA))
          Debug.log(Debug.DB_DATA, "\n" + LINE + "\nExecuting SQL:\n" + UPDATE_EVENT_ERROR_SQL);

        // Truncate error message if it's larger than database column.
        if ((event.lastErrorMessage != null)
            && (event.lastErrorMessage.length() > MAX_ERROR_MESSAGE_LENGTH))
          event.lastErrorMessage = event.lastErrorMessage.substring(0, MAX_ERROR_MESSAGE_LENGTH);

        event.lastErrorTime = new java.sql.Timestamp(System.currentTimeMillis());

        ps = dbConn.prepareStatement(UPDATE_EVENT_ERROR_SQL);

        ps.setTimestamp(1, event.lastErrorTime);
        ps.setString(2, event.lastErrorMessage);
        ps.setString(3, event.channelName);
        ps.setInt(4, event.id);
      } else {
        throw new FrameworkException(
            "ERROR: Invalid event update type [" + eventStatus.name + "].");
      }

      if (Debug.isLevelEnabled(Debug.DB_DATA))
        Debug.log(Debug.DB_DATA, "Event being operated on in database:\n" + event.describe());

      int numRows = ps.executeUpdate();

      if (numRows > 1) {
        String errMsg = "Execution of update SQL statement affected [" + numRows + "] rows.";

        Debug.error(errMsg);

        throw new FrameworkException(errMsg);
      }

      DBConnectionPool.getInstance().commit(dbConn);

      if (Debug.isLevelEnabled(Debug.DB_DATA))
        Debug.log(Debug.DB_DATA, "Successfully committed SQL operation.\n" + LINE);

      // At this point, the event should be removed from the in-memory buffer of events as well,
      // irrespective of processing outcome.
      if (Debug.isLevelEnabled(Debug.MSG_STATUS))
        Debug.log(
            Debug.MSG_STATUS,
            "Removing event [" + event.describe() + "] from in-memory queue buffer.");

      boolean removed = queue.remove(event);

      if (Debug.isLevelEnabled(Debug.MSG_STATUS))
        Debug.log(
            Debug.MSG_STATUS,
            "Event removed? ["
                + removed
                + "].  In-memory queue buffer size ["
                + queue.size()
                + "].");
    } catch (SQLException sqle) {
      throw new DatabaseException(
          "ERROR: Could not execute SQL statement:\n" + DBInterface.getSQLErrorMessage(sqle));
    } catch (Exception e) {
      throw new DatabaseException("ERROR: Could not execute SQL statement:\n" + e.toString());
    } finally {
      releaseDatabaseResources(dbConn, ps);

      if (Debug.isLevelEnabled(Debug.BENCHMARK) && (startTime > 0)) {
        long stopTime = System.currentTimeMillis();

        Debug.log(
            Debug.BENCHMARK,
            "ELAPSED TIME ["
                + (stopTime - startTime)
                + "] msec:  "
                + "SQL: Time to update event in PersistentEvent database table.");
      }
    }
  }
コード例 #27
0
  /**
   * Load any available events from the database up to the configured maximum.
   *
   * @param criteria An event containing the event-selection criteria.
   * @return The next available event on the queue.
   * @exception FrameworkException Thrown on errors.
   */
  private void loadFromDatabase(Event criteria) throws FrameworkException {
    Debug.log(Debug.MSG_STATUS, "QUEUE OPERATION: Loading events from database into queue ...");

    if (!StringUtils.hasValue(criteria.channelName)) {
      throw new FrameworkException(
          "ERROR: Event channel name is a required queue search criteria.");
    }

    Connection dbConn = null;

    PreparedStatement ps = null;

    long startTime = -1;

    if (Debug.isLevelEnabled(Debug.BENCHMARK)) startTime = System.currentTimeMillis();

    try {
      dbConn = DBConnectionPool.getInstance().acquireConnection();

      if (Debug.isLevelEnabled(Debug.DB_DATA))
        Debug.log(Debug.DB_DATA, "\n" + LINE + "\nExecuting SQL:\n" + QUERY_EVENT_SQL);

      if (Debug.isLevelEnabled(Debug.DB_DATA))
        Debug.log(
            Debug.DB_DATA, "Criteria used in query against database:\n" + criteria.describe());

      ps = dbConn.prepareStatement(QUERY_EVENT_SQL);

      ps.setString(1, criteria.channelName);

      ResultSet rs = ps.executeQuery();

      for (int counter = 0; (counter < maxDatabaseEventLoadSize) && rs.next(); counter++) {
        Event event = new Event();

        event.channelName = rs.getString(CHANNEL_NAME_COL);
        event.id = rs.getInt(ID_COL);

        event.message = DBLOBUtils.getCLOB(rs, MESSAGE_COL);

        if (Debug.isLevelEnabled(Debug.MSG_LIFECYCLE))
          Debug.log(Debug.MSG_LIFECYCLE, "Event contents:\n" + event.message);

        event.arrivalTime = rs.getTimestamp(ARRIVAL_TIME_COL);
        event.errorStatus = rs.getString(ERROR_STATUS_COL);
        event.errorCount = rs.getInt(ERROR_COUNT_COL);
        event.lastErrorMessage = rs.getString(LAST_ERROR_MESSAGE_COL);
        event.lastErrorTime = rs.getTimestamp(LAST_ERROR_TIME_COL);

        // Add item to in-memory buffer.
        if (Debug.isLevelEnabled(Debug.MSG_STATUS))
          Debug.log(
              Debug.MSG_STATUS,
              "Adding event [" + event.describe() + "] to in-memory queue buffer.");

        queue.add(event);

        if (Debug.isLevelEnabled(Debug.MSG_STATUS))
          Debug.log(Debug.MSG_STATUS, "In-memory queue buffer size [" + queue.size() + "].");
      }

      if (Debug.isLevelEnabled(Debug.DB_DATA)) Debug.log(Debug.DB_DATA, "\n" + LINE);
    } catch (SQLException sqle) {
      throw new DatabaseException(
          "ERROR: Could not execute SQL statement:\n" + DBInterface.getSQLErrorMessage(sqle));
    } catch (Exception e) {
      throw new DatabaseException("ERROR: Could not execute SQL statement:\n" + e.toString());
    } finally {
      releaseDatabaseResources(dbConn, ps);

      if (Debug.isLevelEnabled(Debug.BENCHMARK) && (startTime > 0)) {
        long stopTime = System.currentTimeMillis();

        Debug.log(
            Debug.BENCHMARK,
            "ELAPSED TIME ["
                + (stopTime - startTime)
                + "] msec:  "
                + "SQL: Time to load event(s) from PersistentEvent database table.");
      }
    }
  }
コード例 #28
0
  /**
   * Make the actual CORBA call.
   *
   * @param serverName Name of the server as known in the COS Naming Service.
   * @param reload Flag indicating whether object reference should be refreshed (true) or any
   *     previously-cached version should be used (false).
   * @param header Header message to send.
   * @param message Body message to send.
   * @return Response that caller should return.
   * @exception Exception Thrown on any errors.
   */
  private String makeClientCall(String serverName, boolean reload, String header, String message)
      throws Exception {
    ORB orb = null;

    // If the alternate ip and port are provided
    if (StringUtils.hasValue(orbAgentAddr) && StringUtils.hasValue(orbAgentPort)) {
      // Key to store the orb in a static map for access the next time around
      String key = orbAgentAddr + ":" + orbAgentPort;

      synchronized (orbStore) {
        orb = (ORB) orbStore.get(key);

        if (orb == null) {
          Properties props = new Properties();
          props.put(ORB_AGENT_ADDR_PROP, orbAgentAddr);
          props.put(ORB_AGENT_PORT_PROP, orbAgentPort);
          orb = new CorbaPortabilityLayer(new String[0], props, null, serverName).getORB();

          orbStore.put(key, orb);
        } else {
          if (Debug.isLevelEnabled(Debug.IO_STATUS))
            Debug.log(
                Debug.IO_STATUS,
                "Using cached orb with properties "
                    + "ORBagentAddr = ["
                    + orbAgentAddr
                    + "] ORBagentPort = ["
                    + orbAgentPort
                    + "]");
        }
      }
    } else {
      if (Debug.isLevelEnabled(Debug.IO_STATUS))
        Debug.log(Debug.IO_STATUS, "Using the default orb ..");

      orb = Supervisor.getSupervisor().getCPL().getORB();
    }

    ObjectLocator ob_loc = new ObjectLocator(orb);

    if (reload) {
      ob_loc.removeFromCache(serverName);
      if (StringUtils.hasValue(orbAgentAddr) && StringUtils.hasValue(orbAgentPort))
        ob_loc.removeFromCache(serverName, orbAgentAddr, orbAgentPort);
    }

    RequestHandler rh = null;
    // The key corresponding to secondary install object references depends on host address and port
    // too.
    if (StringUtils.hasValue(orbAgentAddr) && StringUtils.hasValue(orbAgentPort))
      rh = RequestHandlerHelper.narrow(ob_loc.find(serverName, orbAgentAddr, orbAgentPort));
    else rh = RequestHandlerHelper.narrow(ob_loc.find(serverName));

    if (rh == null) {
      throw new Exception("Object named [" + serverName + "] is not of IDL type RequestHandler.");
    }

    // Make sure that the header contains any available customer context information.
    header = CustomerContext.getInstance().propagate(header);

    if (Debug.isLevelEnabled(Debug.IO_STATUS))
      Debug.log(Debug.IO_STATUS, "Header value:\n" + header);

    ThreadMonitor.ThreadInfo tmti =
        ThreadMonitor.start(
            "Message-processor ["
                + getName()
                + "] making CORBA client call with header:\n"
                + header);

    try {
      if (isAsync) {
        rh.processAsync(header, message);

        return (message);
      } else {
        org.omg.CORBA.StringHolder response = new org.omg.CORBA.StringHolder("");

        rh.processSync(header, message, response);

        return (response.value);
      }
    } finally {
      ThreadMonitor.stop(tmti);
    }
  }
コード例 #29
0
  /*
   * This method will load the Hash map by reading the
   * contents from the configuration property file
   */
  public static HashMap<String, String> loadAndGetMappingToHashMap(File path) {

    synchronized (map) {
      String line = null;
      BufferedReader input = null;

      try {
        input = new BufferedReader(new FileReader(path));

        if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {

          Debug.log(
              Debug.MSG_STATUS,
              className
                  + " : Starts loading Hash map from configuration property "
                  + "file - ["
                  + path.getAbsolutePath()
                  + "]");
        }

        while ((line = input.readLine()) != null) {

          if (line.startsWith("#") || line.equals("")) {

            continue;

          } else {
            /*
             * Check for '=' operand is present in mapping string.
             * If '=' is present then,
             * Check for mapping value, and it must be present.
             *
             * Throws exception if mapping file is wrong.
             */
            if (line.contains("=")) {

              if (line.charAt(line.length() - 1) != '=') {
                String[] lineArray = line.split("=");

                if (!((lineArray[0].equals("") || lineArray[0] == null)
                    && (lineArray[1].equals("") || lineArray[1] == null))) {
                  map.put(lineArray[0].trim(), lineArray[1].trim());
                }
              } else {
                if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {

                  Debug.log(
                      Debug.MSG_STATUS,
                      className
                          + " : Mapping string "
                          + line.toString()
                          + " does not contain any mapping value after '=' operand");
                }
              }
            } else {
              if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {

                Debug.log(
                    Debug.MSG_STATUS,
                    className
                        + " : Mapping string "
                        + line.toString()
                        + " does not contain '=' operand, Invalid Mapping line in mapping configuration file.");
              }
            }
          }
        }
        Debug.log(Debug.MSG_STATUS, className + " : Hash map loading is done...");

      } catch (FileNotFoundException fnf) {

        if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {

          Debug.log(
              Debug.MSG_STATUS,
              className
                  + " : Could not find the file on given path ["
                  + path.getAbsolutePath()
                  + "]");
          Debug.log(Debug.MSG_STATUS, className + " : Hash map is NOT loaded...");
          Debug.log(Debug.MSG_STATUS, className + " : " + fnf.getMessage());
        }

      } catch (IOException ioe) {
        if (Debug.isLevelEnabled(Debug.MSG_STATUS)) {

          Debug.log(
              Debug.MSG_STATUS,
              className + " : Could not read the property file contents to load the Hash map");
          Debug.log(Debug.MSG_STATUS, className + " : Hash map is NOT loaded...");
          Debug.log(Debug.MSG_STATUS, className + " : " + ioe.getMessage());
        }

      } finally {
        if (input != null) {
          try {
            input.close();
          } catch (IOException e) {

            if (Debug.isLevelEnabled(Debug.ALL_ERRORS)) {
              Debug.log(
                  Debug.ALL_ERRORS,
                  className
                      + " : Exception occures at the time to close the "
                      + "stream..."
                      + e.getMessage());
            }
          }
        }
      }
    }

    return map;
  }
コード例 #30
0
  /**
   * If NF_HEADER_LOCATION_PROP exists in context use as the header to forward to Gateway. If
   * IS_ASYNCHRONOUS_PROP exists in context then use that value to call either processAsync or
   * processSync
   *
   * @param input MessageObject containing the value to be processed *
   * @param mpcontext The context
   * @return Optional NVPair containing a Destination name and a MessageObject, or null if none.
   * @exception ProcessingException Thrown if processing fails.
   * @exception MessageException Thrown if bad message.
   */
  public NVPair[] process(MessageProcessorContext ctx, MessageObject input)
      throws MessageException, ProcessingException {
    if (input == null) return null;

    try {
      serverName = getRequiredProperty(ctx, input, SERVER_NAME_PROP);
    } catch (MessageException me) {
      throw new ProcessingException(me.getMessage());
    }

    if (StringUtils.hasValue(headerLocation)) {
      try {
        header = getString(headerLocation, ctx, input);
      } catch (MessageException me) {
        throw new ProcessingException(me.getMessage());
      }
    }

    if (StringUtils.hasValue(isAsyncLocation)) {
      try {
        isAsync = StringUtils.getBoolean(getString(isAsyncLocation, ctx, input));
      } catch (FrameworkException fe) {
        throw new ProcessingException(
            "Value of " + IS_ASYNCHRONOUS_LOCATION_PROP + " is not TRUE/FALSE. " + fe.getMessage());
      }
    }

    // Fetch the alternate Orb Address, if one exists at the specified context location
    if (StringUtils.hasValue(orbAgentAddrLocation)) {
      try {
        if (exists(orbAgentAddrLocation, ctx, input, true)) {
          orbAgentAddr = getString(orbAgentAddrLocation, ctx, input);
          if (Debug.isLevelEnabled(Debug.MSG_STATUS))
            Debug.log(
                Debug.MSG_STATUS,
                "RequestHandlerClient:: alternate orb exists with orb agent address ["
                    + orbAgentAddr
                    + "]");
        }
      } catch (MessageException me) {
        throw new ProcessingException(me.getMessage());
      }
    }

    // Fetch the alternate Orb Port, if one exists at the specified context location
    if (StringUtils.hasValue(orbAgentPortLocation)) {
      try {
        if (exists(orbAgentPortLocation, ctx, input, true)) {
          orbAgentPort = getString(orbAgentPortLocation, ctx, input);
          if (Debug.isLevelEnabled(Debug.MSG_STATUS))
            Debug.log(
                Debug.MSG_STATUS,
                "RequestHandlerClient:: alternate orb exists with orb agent port ["
                    + orbAgentPort
                    + "]");
        }
      } catch (MessageException me) {
        throw new ProcessingException(me.getMessage());
      }
    }

    String msg = input.getString();

    try {
      try {
        return (formatNVPair(makeClientCall(serverName, false, header, msg)));
      } catch (Exception e) {
        // Any of the following exceptions indicate that the failure might be due to
        // a CORBA communications issue (stale object reference) that should be retried.
        if ((e instanceof org.omg.CORBA.OBJECT_NOT_EXIST)
            || (e instanceof org.omg.CORBA.TRANSIENT)
            || (e instanceof org.omg.CORBA.COMM_FAILURE)
            || (e instanceof org.omg.CORBA.INV_OBJREF)
            || (e instanceof org.omg.CORBA.UNKNOWN)) {
          Debug.warning(
              "Caught the following CORBA communication error, so retrying:\n"
                  + e.toString()
                  + "\n"
                  + Debug.getStackTrace(e));

          return (formatNVPair(makeClientCall(serverName, true, header, msg)));
        } else {
          // It's not a communication exception indicating that retry is recommended,
          // so just re-throw it.
          throw e;
        }
      }
    } catch (Exception e) {
      if (e instanceof InvalidDataException) {
        Debug.error(e.toString() + "\n" + Debug.getStackTrace(e));

        throw new MessageException(((InvalidDataException) e).errorMessage);
      } else {
        Debug.error(e.toString() + "\n" + Debug.getStackTrace(e));

        throw new ProcessingException(e.toString());
      }
    }
  }