Пример #1
0
  /**
   * Close all IO connections that were opened during post()
   *
   * @param cs Client socket items to populate.
   */
  private static void cleanUp(ClientSocket cs) throws IOException {

    Debug.log(Debug.MSG_LIFECYCLE, "HTTPUtils: closing IO socket connections");

    if (cs.in != null) {
      try {
        cs.in.close();

        cs.in = null;
      } catch (Exception e) {
        Debug.log(Debug.ALL_WARNINGS, e.toString());
      }
    }

    if (cs.out != null) {
      try {
        cs.out.close();

        cs.out = null;
      } catch (Exception e) {
        Debug.log(Debug.ALL_WARNINGS, e.toString());
      }
    }

    if (cs.s != null) {
      try {
        cs.s.close();

        cs.s = null;
      } catch (Exception e) {
        Debug.log(Debug.ALL_WARNINGS, e.toString());
      }
    }
  }
Пример #2
0
  /**
   * POSTs the given content to the given URL.
   *
   * @param String the url to post to
   * @param content the body of the post
   * @param contentType the content-type of the request
   * @exception IOException if post fails
   */
  public static String post(String urlString, String contentType, String content)
      throws IOException {

    Debug.log(
        Debug.MSG_LIFECYCLE,
        "HTTPUtils: Trying to post " + content + " to web server at [ " + urlString + "]");

    StringBuffer responseBuffer = new StringBuffer();

    URL url = new URL(urlString);

    ClientSocket cs = new ClientSocket();

    HTTPUtils.Response resp = post(cs, url, new Hashtable(), contentType, content);

    while (true) {
      String line = resp.content.readLine();
      if (line == null) break;

      responseBuffer.append(line);
    }

    Debug.log(
        Debug.MSG_LIFECYCLE,
        "HTTPUtils: Obtained response from web server : " + responseBuffer.toString());

    cleanUp(cs);

    return responseBuffer.toString();
  }
Пример #3
0
  /**
   * 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;
  }
Пример #4
0
  /**
   * This function returns the begin offset of the input string where the first matched pattern is
   * found.
   *
   * @param pattern pattern string to match
   * @param input input string
   * @return returns the offset of the beginning of the first matched pattern. if the match not
   *     found, it returns -1.
   * @exception throws a FrameworkException when either pattern/input is null.
   */
  public static int getBeginOffset(String pattern, String input) throws FrameworkException {
    if (input == null || pattern == null) {
      throw new FrameworkException(
          "RegexUtils: getBeginOffset(): input or pattern is null."
              + "input = "
              + input
              + ", "
              + "pattern = "
              + pattern);
    }

    Perl5Util util = new Perl5Util();
    int beginOffset = -1;
    String formatPattern = null;

    formatPattern = makePerl5MatchPattern(pattern);

    if (util.match(formatPattern, input)) {
      beginOffset = util.beginOffset(0);
    } else {
      Debug.log(Debug.MSG_STATUS, "RegexUtils: getBeginOffset(): No match found.");
    }

    return beginOffset;
  }
Пример #5
0
  /**
   * 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();
  }
Пример #6
0
  /**
   * 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);
    }
  }
Пример #7
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());
  }
Пример #8
0
 /** Initializes the board executing a writing test catching the error. */
 public void init() {
   try {
     device.write(0xfe, (byte) 0x04);
   } catch (IOException e) {
     StringWriter sw = new StringWriter();
     e.printStackTrace(new PrintWriter(sw));
     String exceptionDetails = sw.toString();
     debug.log(Debug.SEVERE, exceptionDetails);
     Gopigo.getInstance().halt();
   }
 }
Пример #9
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.");
    }
  }
Пример #10
0
  public static void main(String[] args) {

    Debug.enable(Debug.UNIT_TEST);
    Debug.enable(Debug.BENCHMARK);
    Debug.showLevels();
    if (args.length != 3) {
      Debug.log(
          Debug.ALL_ERRORS,
          "UnBatcher: USAGE:  " + " jdbc:oracle:thin:@192.168.164.238:1521:e911 e911 e911 ");
      return;
    }
    try {

      DBInterface.initialize(args[0], args[1], args[2]);
    } catch (DatabaseException e) {
      Debug.log(
          Debug.MAPPING_ERROR,
          "UnBatcher: " + "Database initialization failure: " + e.getMessage());
    }

    Splitter spl = new Splitter();

    try {
      MessageProcessorContext mpx = new MessageProcessorContext();
      mpx.set("FileName", "MANS9999");

      String s = FileUtils.readFile("D:\\Response\\DECCCORR.txt");
      System.out.println("length----------->>>>>" + s.length());
      MessageObject msob = new MessageObject();
      msob.set(s);
      spl.initialize("E911BATCHER", "FAX_MESSAGE_SPLITTER");
      spl.process(mpx, msob);

    } catch (Exception ex) {
      System.out.println(ex.getMessage());
    }
  }
Пример #11
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;
  }
Пример #12
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;
  }
Пример #13
0
  /**
   * This function substitues ALL occurence of the pattern in the input passed in. This function can
   * take a single input, a perl5 match pattern, an array of replacement strings, begin token, and
   * end token.
   *
   * @param perl5Regex perl5 regular expression for pattern match i.e.) &(?!amp) - this regular
   *     expression matches every occurence of '&' which is not followed by "amp". For example, it
   *     will match '&' or "&anystring" but "&amp".
   * @param input input string
   * @param replacement array of replacement strings
   * @param beginToken begin boundary token
   * @param endToken end boundary token
   * @return result returns processed string
   * @exception throws FrameworkException when either pattern/input/replacement is null.
   */
  public static String replaceAll(
      String perl5Regex, String input, String replacement[], String beginToken, String endToken)
      throws FrameworkException {
    if (input == null) {
      throw new FrameworkException("RegexUtil: replaceAll(): input is null.");
    }

    if ((perl5Regex == null) && (replacement.length <= 0)) {
      Debug.log(Debug.ALL_ERRORS, "RegexUtils.replaceAll()): No patterns and tokens specified.");
      throw new FrameworkException("RegexUtils: replaceAll(): No patterns and tokens specified.");
    }

    for (int i = 0; i < replacement.length; i++) {
      input = replaceAll(perl5Regex, input, replacement[i], beginToken, endToken);
    }

    return input;
  }
Пример #14
0
  /**
   * This function checks in the input if there is other tokens in the begingTokens array than
   * begin. This utility function is used on a string which is between a valid begin token and all
   * possible other begin tokens. If there is another begin token of different kind is found, the
   * substitution shouldn't occur. Consider this situation:
   *
   * <p>i.e.) <beginToken_0> "some string <beginToken_1> here to do the substitution on"
   * <endToken_0> <beginToken_0> "another some string" <endToken_1>
   *
   * <p>In this case, the replaceAll() function finds the matched pair <beginToken_0> and
   * <endToken_0> and attempt to perform the substitution. However, since there is another boundary
   * _1 is overlapped with _0 boundary, we do not want to perform a string substitution.
   *
   * @param replacement replacement string to replace with
   * @param beginToken begin boundary token
   * @param endToken end boundary token
   * @return true if any of other beginTokens in the beginToken[] than begin is found in the input
   *     string, false otherwise
   */
  private static final boolean isOtherBeginTokenThere(
      String begin, String input, String beginTokens[]) throws FrameworkException {
    Perl5Util util = new Perl5Util();

    for (int i = 0; i < beginTokens.length; i++) {
      // look for the other token
      if (!beginTokens[i].equals(begin)) {
        String perl5Pattern = makePerl5MatchPattern(beginTokens[i]);
        // if the input contains at least one beginToken which differs from the begin
        if (util.match(perl5Pattern, input)) {
          Debug.log(
              Debug.MSG_STATUS, "RegexUtils: isOtherBeginTokenThere: token = " + perl5Pattern);
          return true;
        }
      }
    }

    return false;
  }
Пример #15
0
  /**
   * This function substitues ALL occurence of the pattern in the input with the replacement passed
   * in. This function can handle such situation as when some characters in the replacement is also
   * used in the pattern.
   *
   * <p>i.e.) pattern - & or &/[option] replacement - &amp or &amp/[option]
   *
   * @param pattern pattern string to match
   * @param input input string
   * @param replacement replacement string to be replaced with
   * @return returns processed string. Default return value is the original input string.
   * @exception throws FrameworkException when either pattern/input/replacement is null.
   */
  public static String replaceAll(String pattern, String input, String replacement)
      throws FrameworkException {
    if ((pattern == null) || (replacement == null) || (input == null)) {
      Debug.log(
          Debug.ALL_ERRORS,
          "RegexUtils.replaceAll(): pattern or replacement or input" + "is null.");

      throw new FrameworkException(
          "ERROR: RegexUtils: replaceAll(): pattern or replacement or input is null.");
    }

    Perl5Util util = new Perl5Util();

    String negativeLookAheadPattern = makePerl5MatchPatternNegativeLookAhead(pattern, replacement);
    String substitutionPattern =
        makePerl5SubstitutionPattern(negativeLookAheadPattern, replacement);

    String result = util.substitute(substitutionPattern, input);

    return result;
  }
Пример #16
0
  /**
   * POST something to the given URL. The headers are put in as HTTP headers, the content length is
   * calculated and the content is sent as content. Duh.
   *
   * @param cs Client socket items.
   * @param url the url to post to
   * @param headers additional headers to send as HTTP headers
   * @param contentType type of the content
   * @param content the body of the post
   * @exception IOException if post fails
   */
  private static Response post(
      ClientSocket cs, URL url, Hashtable headers, String contentType, String content)
      throws IOException {

    // If the port is not specified in the URL, use the default http port.
    int port = url.getPort();
    if (port == -1) port = 80;

    cs.s = new Socket(url.getHost(), +port);
    cs.out = new PrintWriter(cs.s.getOutputStream());
    cs.in = new BufferedReader(new InputStreamReader(cs.s.getInputStream()));

    // Create the HTTP header
    cs.out.print(HTTP_POST + " " + url.getFile() + " HTTP/" + HTTP_VERSION + "\r\n");
    cs.out.print(HEADER_HOST + ": " + url.getHost() + ':' + port + "\r\n");
    cs.out.print(HEADER_CONTENT_TYPE + ": " + contentType + "\r\n");
    cs.out.print(HEADER_CONTENT_LENGTH + ": " + content.length() + "\r\n");

    for (Enumeration e = headers.keys(); e.hasMoreElements(); ) {
      Object key = e.nextElement();
      cs.out.print(key + ": " + headers.get(key) + "\r\n");
    }

    // According to HTTP1.1 need another CRLF after the header
    cs.out.print("\r\n");

    Debug.log(Debug.MSG_LIFECYCLE, "HTTPUtils: Writing content to the socket... " + content);

    cs.out.println(content);

    cs.out.flush();

    /* read the status line */
    int statusCode = 0;
    String statusString = null;
    StringTokenizer st = new StringTokenizer(cs.in.readLine());
    st.nextToken(); // ignore version part
    statusCode = Integer.parseInt(st.nextToken());

    StringBuffer sb = new StringBuffer();

    while (st.hasMoreTokens()) {
      sb.append(st.nextToken());
      if (st.hasMoreTokens()) sb.append(" ");
    }

    statusString = sb.toString();

    /* get the headers */
    Hashtable respHeaders = new Hashtable();
    int respContentLength = -1;
    String respContentType = null;
    String line = null;

    while ((line = cs.in.readLine()) != null) {

      if (line.length() == 0) break;

      int colonIndex = line.indexOf(':');
      String fieldName = line.substring(0, colonIndex);
      String fieldValue = line.substring(colonIndex + 1).trim();

      if (fieldName.equals(HEADER_CONTENT_LENGTH)) respContentLength = Integer.parseInt(fieldValue);
      else if (fieldName.equals(HEADER_CONTENT_TYPE)) respContentType = fieldValue;
      else respHeaders.put(fieldName, fieldValue);
    }

    Response response =
        new Response(
            statusCode, statusString, respHeaders, respContentLength, respContentType, cs.in);

    return response;
  }
Пример #17
0
  /**
   * This function substitues ALL the occurence of the pattern in the input with the replacement
   * passed in. The substitution is done only in the range bound by the begin token and the end
   * token.
   *
   * @param pattern pattern string to match
   * @param input input string
   * @param replacement replacement string to replace with
   * @param beginToken begin boundary token
   * @param endToken end boundary token
   * @param beginTokens[] an array of beginTokens - this is used for negative look ahead where there
   *     are other begin tokens to be recognized.
   * @return returns processed string if both beginToken and the endToken are successfully found,
   *     returns the unproessed original input otherwise.
   * @exception throws a FrameworkException when either pattern/input/replacement is null.
   */
  public static String replaceAll(
      String pattern,
      String input,
      String replacement,
      String beginToken,
      String endToken,
      String beginTokens[])
      throws FrameworkException {
    if ((pattern == null) || (replacement == null) || (input == null)) {
      Debug.log(
          Debug.ALL_ERRORS,
          "RegexUtils: replaceAll(): pattern or replacement or input is null. "
              + "\npattern = "
              + pattern
              + "\ninput = "
              + input
              + "\nreplacement = "
              + replacement);
      throw new FrameworkException(
          "RegexUtils: replaceAll(): pattern or replacement or input is null.");
    }

    Perl5Util util = new Perl5Util();
    StringBuffer resultBuffer = new StringBuffer();

    if ((beginToken == null) || (endToken == null)) {
      // either beginToken or endToken cannot be null, however both can be null.
      throw new FrameworkException(
          "RegexUtils: replaceAll(): Either begin or end token is null. BeginToken = "
              + beginToken
              + ", "
              + "endToken = "
              + endToken);
    } else // do pattern match
    {
      // making the Perl5 regular expression format pattern
      String begin = makePerl5MatchPattern(beginToken);
      String end = makePerl5MatchPattern(endToken);
      boolean beginTokenMatch = true;

      // if begin token found
      while (beginTokenMatch) {

        // check the input for each iteration. when there is no input, break out of the loop.
        if (input == null) break;

        beginTokenMatch = util.match(begin, input);

        if (beginTokenMatch) {
          String negativeLookAheadPattern =
              makePerl5MatchPatternNegativeLookAhead(pattern, replacement);
          int beginOffsetForBeginToken = util.beginOffset(0);
          int endOffsetForBeginToken = util.endOffset(0);

          // the input after the begin token
          String subInput = input.substring(endOffsetForBeginToken);

          // if end token passed in was an empty string
          if (endToken.equals("")) {
            String result = null;
            try {
              result = replaceAllWithBeginToken(pattern, input, replacement, beginToken);
            } catch (FrameworkException e) {
              Debug.log(Debug.ALL_ERRORS, "RegexUtils: replaceAll() failed." + e.getMessage());
            }
            return result;
          } else if (util.match(end, subInput)) // endToken found
          {

            // begin offset for the end token relative to the input not subInput
            int beginOffsetForEndToken = endOffsetForBeginToken + util.beginOffset(0);
            int endOffsetForEndToken = endOffsetForBeginToken + util.endOffset(0);

            // pre is the string before the beginToken and the beginToken
            String pre = input.substring(0, endOffsetForBeginToken);
            resultBuffer.append(pre);

            // current is the string between the beginToken and the endToken
            String current = input.substring(endOffsetForBeginToken, beginOffsetForEndToken);

            // theRest is the rest of the input string after the endToken
            String theRest = input.substring(endOffsetForEndToken);

            // current is the string between begin token and the endtoken
            current = skipOrphanedBeginToken(begin, current, resultBuffer);

            if (isOtherBeginTokenThere(beginToken, current, beginTokens) == false) {
              current = replaceAll(pattern, current, replacement);
            } // isOtherBeginTokenThere

            resultBuffer.append(current);
            resultBuffer.append(input.substring(beginOffsetForEndToken, endOffsetForEndToken));
            input = theRest;
          } else // endToken not found
          {
            resultBuffer.append(input);
            break;
          }
        } // if beginToken found
        else // beginToken not found
        {
          resultBuffer.append(input);
          break;
        }
      } // while begin token found
    } // else do pattern match

    return resultBuffer.toString();
  }
Пример #18
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.");
      }
    }
  }
Пример #19
0
  /**
   * 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
  /**
   * 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.");
      }
    }
  }
Пример #21
0
  protected static Element getRootElement(HttpServletRequest request) {
    if (Debug.infoOn()) {
      Debug.log("Applet config file: " + ldapConfig);
    }
    File configFile = new File(ldapConfig);
    FileInputStream configFileIS = null;
    Element rootElement = null;
    try {
      configFileIS = new FileInputStream(configFile);
      Document configDoc =
          UtilXml.readXmlDocument(configFileIS, "LDAP configuration file " + ldapConfig);
      rootElement = configDoc.getDocumentElement();
    } catch (FileNotFoundException e) {
      Debug.logError(e, "Error calling userLogin service", module);
      Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
      String errMsg =
          UtilProperties.getMessage(
              resourceWebapp,
              "loginevents.following_error_occurred_during_login",
              messageMap,
              UtilHttp.getLocale(request));
      request.setAttribute("_ERROR_MESSAGE_", errMsg);
    } catch (SAXException e) {
      Debug.logError(e, "Error calling userLogin service", module);
      Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
      String errMsg =
          UtilProperties.getMessage(
              resourceWebapp,
              "loginevents.following_error_occurred_during_login",
              messageMap,
              UtilHttp.getLocale(request));
      request.setAttribute("_ERROR_MESSAGE_", errMsg);
    } catch (ParserConfigurationException e) {
      Debug.logError(e, "Error calling userLogin service", module);
      Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
      String errMsg =
          UtilProperties.getMessage(
              resourceWebapp,
              "loginevents.following_error_occurred_during_login",
              messageMap,
              UtilHttp.getLocale(request));
      request.setAttribute("_ERROR_MESSAGE_", errMsg);
    } catch (IOException e) {
      Debug.logError(e, "Error calling userLogin service", module);
      Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage());
      String errMsg =
          UtilProperties.getMessage(
              resourceWebapp,
              "loginevents.following_error_occurred_during_login",
              messageMap,
              UtilHttp.getLocale(request));
      request.setAttribute("_ERROR_MESSAGE_", errMsg);
    } finally {
      if (configFileIS != null) {
        try {
          configFileIS.close();
        } catch (IOException e) {
        }
      }
    }

    return rootElement;
  }
Пример #22
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.");
      }
    }
  }
Пример #23
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);
    }
  }
Пример #24
0
 public void detectedCountedLoops() {
   for (LoopEx loop : loops()) {
     InductionVariables ivs = new InductionVariables(loop);
     LoopBeginNode loopBegin = loop.loopBegin();
     FixedNode next = loopBegin.next();
     while (next instanceof FixedGuardNode || next instanceof ValueAnchorNode) {
       next = ((FixedWithNextNode) next).next();
     }
     if (next instanceof IfNode) {
       IfNode ifNode = (IfNode) next;
       boolean negated = false;
       if (!loopBegin.isLoopExit(ifNode.falseSuccessor())) {
         if (!loopBegin.isLoopExit(ifNode.trueSuccessor())) {
           continue;
         }
         negated = true;
       }
       LogicNode ifTest = ifNode.condition();
       if (!(ifTest instanceof IntegerLessThanNode)) {
         if (ifTest instanceof IntegerBelowThanNode) {
           Debug.log("Ignored potential Counted loop at %s with |<|", loopBegin);
         }
         continue;
       }
       IntegerLessThanNode lessThan = (IntegerLessThanNode) ifTest;
       Condition condition = null;
       InductionVariable iv = null;
       ValueNode limit = null;
       if (loop.isOutsideLoop(lessThan.x())) {
         iv = ivs.get(lessThan.y());
         if (iv != null) {
           condition = lessThan.condition().mirror();
           limit = lessThan.x();
         }
       } else if (loop.isOutsideLoop(lessThan.y())) {
         iv = ivs.get(lessThan.x());
         if (iv != null) {
           condition = lessThan.condition();
           limit = lessThan.y();
         }
       }
       if (condition == null) {
         continue;
       }
       if (negated) {
         condition = condition.negate();
       }
       boolean oneOff = false;
       switch (condition) {
         case LE:
           oneOff = true; // fall through
         case LT:
           if (iv.direction() != Direction.Up) {
             continue;
           }
           break;
         case GE:
           oneOff = true; // fall through
         case GT:
           if (iv.direction() != Direction.Down) {
             continue;
           }
           break;
         default:
           throw GraalInternalError.shouldNotReachHere();
       }
       loop.setCounted(
           new CountedLoopInfo(
               loop,
               iv,
               limit,
               oneOff,
               negated ? ifNode.falseSuccessor() : ifNode.trueSuccessor()));
     }
   }
 }
Пример #25
0
 public void d(Object... output) {
   Debug.log(params, output);
 }
Пример #26
0
 public static synchronized void d(Object... output) {
   Debug.log(params, output);
 }
Пример #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
  /**
   * Returns true if the two original variables are related in a way that makes subsequence or
   * subset detection not informative.
   */
  public static boolean isObviousSubSequenceDynamically(
      Invariant inv, VarInfo subvar, VarInfo supervar) {

    VarInfo[] vis = {subvar, supervar};

    ProglangType rep1 = subvar.rep_type;
    ProglangType rep2 = supervar.rep_type;
    if (!(((rep1 == ProglangType.INT_ARRAY) && (rep2 == ProglangType.INT_ARRAY))
        || ((rep1 == ProglangType.DOUBLE_ARRAY) && (rep2 == ProglangType.DOUBLE_ARRAY))
        || ((rep1 == ProglangType.STRING_ARRAY) && (rep2 == ProglangType.STRING_ARRAY))))
      return false;

    if (debug.isLoggable(Level.FINE)) {
      debug.fine(
          "Checking isObviousSubSequenceDynamically " + subvar.name() + " in " + supervar.name());
    }

    Object[] di = isObviousSubSequence(subvar, supervar);
    if (di[1] != null) {
      inv.log("ObvSubSeq- true from isObviousSubSequence: " + di[1]);
      return true;
    }
    debug.fine("  not isObviousSubSequence(statically)");

    PptTopLevel ppt_parent = subvar.ppt;

    // If the elements of supervar are always the same (EltOneOf),
    // we aren't going to learn anything new from this invariant,
    // since each sequence should have an EltOneOf over it.
    if (false) {
      PptSlice1 slice = ppt_parent.findSlice(supervar);
      if (slice == null) {
        System.out.println("No slice: parent =" + ppt_parent);
      } else {
        System.out.println("Slice var =" + slice.var_infos[0]);
        for (Invariant superinv : slice.invs) {
          System.out.println("Inv = " + superinv);
          if (superinv instanceof EltOneOf) {
            EltOneOf eltinv = (EltOneOf) superinv;
            if (eltinv.num_elts() > 0) {
              inv.log(" obvious because of " + eltinv.format());
              return true;
            }
          }
        }
      }
    }

    // Obvious if subvar is always just []
    if (true) {
      PptSlice1 slice = ppt_parent.findSlice(subvar);
      if (slice != null) {
        for (Invariant subinv : slice.invs) {
          if (subinv instanceof OneOfSequence) {
            OneOfSequence seqinv = (OneOfSequence) subinv;
            if (seqinv.num_elts() == 1) {
              Object elt = seqinv.elt();
              if (elt instanceof long[] && ((long[]) elt).length == 0) {
                Debug.log(
                    debug, inv.getClass(), inv.ppt, vis, "ObvSubSeq- True from subvar being []");
                return true;
              }
              if (elt instanceof double[] && ((double[]) elt).length == 0) {
                inv.log("ObvSubSeq- True from subvar being []");
                return true;
              }
            }
          }
        }
      }
    }

    // Check for a[0..i] subseq a[0..j] but i < j.
    VarInfo subvar_super = subvar.isDerivedSubSequenceOf();
    VarInfo supervar_super = supervar.isDerivedSubSequenceOf();

    if (subvar_super != null && subvar_super == supervar_super) {
      // both sequences are derived from the same supersequence
      if ((subvar.derived instanceof SequenceScalarSubsequence
              || subvar.derived instanceof SequenceScalarArbitrarySubsequence)
          && (supervar.derived instanceof SequenceScalarSubsequence
              || supervar.derived instanceof SequenceScalarArbitrarySubsequence)) {
        VarInfo sub_left_var = null,
            sub_right_var = null,
            super_left_var = null,
            super_right_var = null;
        // I'm careful not to access foo_shift unless foo_var has been set
        // to a non-null value, but Java is too stupid to recognize that.
        int sub_left_shift = 42,
            sub_right_shift = 69,
            super_left_shift = 1492,
            super_right_shift = 1776;
        if (subvar.derived instanceof SequenceScalarSubsequence) {
          SequenceScalarSubsequence sub = (SequenceScalarSubsequence) subvar.derived;
          if (sub.from_start) {
            sub_right_var = sub.sclvar();
            sub_right_shift = sub.index_shift;
          } else {
            sub_left_var = sub.sclvar();
            sub_left_shift = sub.index_shift;
          }
        } else if (subvar.derived instanceof SequenceScalarArbitrarySubsequence) {
          SequenceScalarArbitrarySubsequence sub =
              (SequenceScalarArbitrarySubsequence) subvar.derived;
          sub_left_var = sub.startvar();
          sub_left_shift = (sub.left_closed ? 0 : 1);
          sub_right_var = sub.endvar();
          sub_right_shift = (sub.right_closed ? 0 : -1);
        } else {
          Assert.assertTrue(false);
        }
        if (supervar.derived instanceof SequenceScalarSubsequence) {
          SequenceScalarSubsequence super_ = (SequenceScalarSubsequence) supervar.derived;
          if (super_.from_start) {
            super_right_var = super_.sclvar();
            super_right_shift = super_.index_shift;
          } else {
            super_left_var = super_.sclvar();
            super_left_shift = super_.index_shift;
          }
        } else if (supervar.derived instanceof SequenceScalarArbitrarySubsequence) {
          SequenceScalarArbitrarySubsequence super_ =
              (SequenceScalarArbitrarySubsequence) supervar.derived;
          super_left_var = super_.startvar();
          super_left_shift = (super_.left_closed ? 0 : 1);
          super_right_var = super_.endvar();
          super_right_shift = (super_.right_closed ? 0 : -1);
        } else {
          Assert.assertTrue(false);
        }
        boolean left_included, right_included;
        if (super_left_var == null) left_included = true;
        else if (sub_left_var == null) // we know super_left_var != null here
        left_included = false;
        else
          left_included =
              VarInfo.compare_vars(
                  super_left_var, super_left_shift, sub_left_var, sub_left_shift, true /* <= */);
        if (super_right_var == null) right_included = true;
        else if (sub_right_var == null) // we know super_right_var != null here
        right_included = false;
        else
          right_included =
              VarInfo.compare_vars(
                  super_right_var,
                  super_right_shift,
                  sub_right_var,
                  sub_right_shift,
                  false /* >= */);
        //         System.out.println("Is " + subvar.name() + " contained in "
        //                            + supervar.name()
        //                            + "? left: " + left_included + ", right: "
        //                            + right_included);
        if (left_included && right_included) {
          inv.log("ObvSubSeq- True a[0..i] subseq a[0..j] and i < j");
          return true;
        }
      } else if ((subvar.derived instanceof SequenceStringSubsequence)
          && (supervar.derived instanceof SequenceStringSubsequence)) {
        // Copied from just above
        SequenceStringSubsequence sss1 = (SequenceStringSubsequence) subvar.derived;
        SequenceStringSubsequence sss2 = (SequenceStringSubsequence) supervar.derived;
        VarInfo index1 = sss1.sclvar();
        int shift1 = sss1.index_shift;
        boolean start1 = sss1.from_start;
        VarInfo index2 = sss2.sclvar();
        int shift2 = sss2.index_shift;
        boolean start2 = sss2.from_start;
        if (start1 == start2)
          if (VarInfo.compare_vars(index1, shift1, index2, shift2, start1)) {
            inv.log("True from comparing indices");
            return true;
          }
      } else {
        Assert.assertTrue(
            false,
            "how can this happen? "
                + subvar.name()
                + " "
                + subvar.derived.getClass()
                + " "
                + supervar.name()
                + " "
                + supervar.derived.getClass());
      }
    }

    // Also need to check A[0..i] subseq A[0..j] via compare_vars.

    // A subseq B[0..n] => A subseq B

    List<Derivation> derivees = supervar.derivees();
    // For each variable derived from supervar ("B")
    for (Derivation der : derivees) {
      // System.out.println("  ... der = " + der.getVarInfo().name() + " " + der);
      if (der instanceof SequenceScalarSubsequence) {
        // If that variable is "B[0..n]"
        VarInfo supervar_part = der.getVarInfo();
        // Get the canonical version; being equal to it is good enough.
        if (supervar_part.get_equalitySet_leader() == subvar) {
          Debug.log(debug, inv.getClass(), inv.ppt, vis, "ObvSubSeq- True from canonical leader");
          return true;
        }

        if (supervar_part.isCanonical()) {
          if (subvar == supervar_part) {
            System.err.println(
                "Error: variables "
                    + subvar.name()
                    + " and "
                    + supervar_part.name()
                    + " are identical.  Canonical");
            System.err.println(subvar.isCanonical());
            System.err.println(supervar_part.isCanonical());
            throw new Error();
          }

          // Check to see if there is a subsequence over the supervar
          if (ppt_parent.is_subsequence(subvar, supervar_part)) {
            if (Debug.logOn())
              inv.log(
                  "ObvSubSeq- true from A subseq B[0..n] "
                      + subvar.name()
                      + "/"
                      + supervar_part.name());
            return (true);
          }
        }
      }
    }
    return false;
  }
Пример #29
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());
      }
    }
  }