/** Servlet initialization. */
  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    try {
      // Initialize all the internal parameters from the supplied info in the
      // web descriptor file
      System.out.println("Reading parameters specified in the web.xml descriptor file");
      initParams(config);

      // initialize local logger
      logger = MPILogger.getLogger(AuthenticatorServlet.class.getName());

      // load WaitUntilFirstReqeust property
      String wufr =
          (String)
              Config.getConfigReference()
                  .getConfigData(MPIConfigDefinition.WAIT_UNTIL_FIRST_REQUEST);

      if ((wufr != null) && (wufr.equalsIgnoreCase("true"))) {
        logger.debug("CardRangeMonitor initialization waits until first request.");
        AuthenticatorServlet.waitUntilFirstRequest = true;
      } else {
        logger.debug("Start CardRangeMonitor initialization.");
        AuthenticatorServlet.waitUntilFirstRequest = false;
        initCRMonitor();
      }

      /*
       * Then initialize the proper connection parameters
       */
      boolean initialOK = SecurityManager.getInstance().initializeConnection();
      if (!initialOK) {
        this.logger.error("Failed to initialize connection parameters.");
      }

      /*
       * [Jun's Note - Dec 04, 2002]
       * JMX agent initialization
       */
      CoreAgentManager.initAgent();

      /*
       * Indicate that initialization is OK and we are ready to accept requests
       */
      System.out.println(
          "- - - - Verified@ONCE Core Server component is open for e-business - - - -");

    } catch (ConfigurationException ce) {
      logger.error(
          "Failed to load config property. WaitUntilFirstRequest property set to 'true' as default.",
          ce);
      AuthenticatorServlet.waitUntilFirstRequest = true;
    } catch (CoreAgentException cae) {
      logger.error("Jmx Agent Starting Error: ", cae);
    }
  }
Example #2
0
/**
 * Description: This thread is resposible for sending error message back to VisaDir or ACS when MPI
 * receives invalid VERes or PARes message
 *
 * @version 0.1 Oct 18, 2002
 * @author Jerome Mourits
 */
public class ErrorHandlerThread extends Thread {

  private Logger logger = MPILogger.getLogger(ErrorHandlerThread.class.getName());
  private Vector toBeSent = new Vector();

  private static int interval;

  public void run() {

    setInterval(ErrorHandlerThreadManager.getErrorThreadSleepInterval());

    // this is not correct should be changed later
    // - only shut down when the server is shutdown
    while (true) {

      if (ErrorHandlerThreadManager.getErrorVector().size() > 0) {
        synchronized (ErrorHandlerThreadManager.lock) {
          toBeSent = new Vector(ErrorHandlerThreadManager.getErrorVector());
          ErrorHandlerThreadManager.setErrorVector(new Vector());
        }
      }

      if (toBeSent.size() > 0) {
        logger.debug("Process error requests: " + toBeSent.size());
        for (int i = 0; i < toBeSent.size(); i++) {
          logger.debug("process error request " + i + "...");
          ErrorRequest er = (ErrorRequest) toBeSent.get(i);
          send(er.getToUrl(), er.getMsg());
          logger.debug("process error request " + i + " finished.");
        }
        toBeSent = new Vector();
      } else {
        logger.debug("No ErrorRequest to be processed.");
      }

      try {
        sleep(getInterval());
      } catch (InterruptedException e) {
        logger.debug("ErrorHandlerThread interrupted by other thread.", e);
      }
    }
  }

  // start sending to targetUrl ....
  private void send(String targetUrl, Message sentMsg) {
    // do logging
    logger.debug("ErrorHandlerThread is called");

    // Initialize IO stream
    OutputStreamWriter out = null;

    try {
      // Precheck id
      if ((sentMsg.getId() != null) && (sentMsg.getId().equals("UNKNOWN"))) {
        sentMsg.setId(ID_Generator.getUniqueId());
        logger.debug("UNKNOWN id replaced with new id: " + sentMsg.getId());
      }

      logger.debug("Sending message to targetUrl: " + targetUrl);

      /**
       * The following change done by Gang, to change the HttpConnection to directly use SUN
       * implementation
       */
      /**
       * The following old one is replaced //Establish connection to servlet URL url = new
       * URL(targetUrl);
       */
      // Establish connection to servlet
      URL url;
      if (targetUrl != null && targetUrl.trim().toLowerCase().startsWith("https:"))
        url = new URL(null, targetUrl, new Handler());
      else url = new URL(targetUrl);

      URLConnection conn = url.openConnection();
      logger.debug("connection setup finished.");

      // Prepare for both input and output
      conn.setDoInput(true);
      conn.setDoOutput(true);

      // Turn off caching
      conn.setUseCaches(false);

      // Convert inMsg to string
      String msg = sentMsg.toString();
      logger.debug("Content to targetUrl: " + msg);

      // Set content type to MPI message
      conn.setRequestProperty("Content-Type", "application/xml; charset=\"utf-8\"");

      // Set content length
      conn.setRequestProperty("Content-Length", Integer.toString(msg.length()));

      // Create output stream
      out = new OutputStreamWriter(conn.getOutputStream());

      // Write message as POST data
      // out.write(URLEncoder.encode(msg));
      out.write(msg);

      // Flush it
      out.flush();

      // Close output stream
      out.close();
      logger.debug("Sending finished.");

      // prepare for logging
      Date timestamp = Calendar.getInstance().getTime();

      // check the response
      if ((conn instanceof HttpURLConnection) || (conn instanceof HttpsURLConnection)) {

        int i;
        // get Response Code
        if (conn instanceof HttpURLConnection) {
          HttpURLConnection ht = (HttpURLConnection) conn;
          i = ht.getResponseCode();
        } else {
          HttpsURLConnection hts = (HttpsURLConnection) conn;
          i = hts.getResponseCode();
        }

        // logging handling
        if (i == 200) {
          // do logging
          logger.debug(
              "Error Message (id ="
                  + sentMsg.getId()
                  + ") is sent to targetUrl: ["
                  + targetUrl
                  + "] successfully - Time At: ["
                  + timestamp.toString()
                  + "]");
        } else {
          // do logging
          logger.error(
              "Error Message (id ="
                  + sentMsg.getId()
                  + ") cannot be sent back to  targetUrl: ["
                  + targetUrl
                  + "] - Time At: ["
                  + timestamp.toString()
                  + "]");
        }
      } else {
        logger.error("NO HTTP connection was set up");
      }
    } catch (Exception e) {
      logger.error("Failed to send error message to targetUrl, Reason: " + e.getMessage(), e);
    } finally {
      try {
        if (out != null) out.close();
      } catch (Exception e) {
        logger.error("Couldn't close outputstream in ErrorHandlerThread finally block.", e);
      }
    }
  }
  /**
   * Returns the interval.
   *
   * @return int
   */
  public static int getInterval() {
    return interval;
  }

  /**
   * Sets the interval.
   *
   * @param interval The interval to set
   */
  public static void setInterval(int interval) {
    ErrorHandlerThread.interval = interval;
  }
}
Example #3
0
/**
 * This class is a utility class that provides Base64 conversion to several different format,
 * namely: - Binary - Binhex - Asciihex
 *
 * <p>This conversion is used with the PARes.CAVV and the PARes.xid values to accomodate merchant
 * application that must submit those values using a different format than the standard "base64"
 * one.
 *
 * @author Martin Dufort ([email protected])
 */
public class Base64Conversion {
  /** Local Log4J logger */
  private static Logger logger = MPILogger.getLogger(Base64Conversion.class.getName());

  /* Definition of the available conversion functions */
  public static final String TO_BASE64 = "ToBase64";
  public static final String TO_BINARY = "ToBinary";
  public static final String TO_BINHEX = "ToBinHex";
  public static final String TO_ASCIIHEX = "ToAsciiHex";

  /**
   * Convert a Base64 value into one of the other available formats
   *
   * @param in Value to be converted
   * @param format Format to convert the value to
   * @return Properly converted value
   */
  public static String convert(String in, String format) throws IllegalArgumentException {
    logger.debug("Converting Base64 value: " + in + " to new format: " + format);

    // If the format is unknown or we are requesting a Base64 format, then we
    // return the value as is...
    if ((format == null) || (format.equalsIgnoreCase(TO_BASE64))) {
      return in;
    }

    // Decode value first
    byte[] res = Base64Codec.decode(in);
    if (res == null) {
      // Unable to decode, probabling garbled characters
      return null;
    }

    // Conversion to a binary format ???
    if (format.equalsIgnoreCase(TO_BINARY)) {
      // Binary format is just returning the decoded value as a String
      return toBinary(res);
    }
    //
    // ***** Not Supported for now!!!! *****
    //		else if (format.equalsIgnoreCase(TO_BINHEX)) {
    //			// To Binary hex format
    //			/*
    //			 * [Martin's Note: 21-May-03 11:14:40 AM]
    //			 *
    //			 * not currently supported. return the value as B64
    //			 */
    //			/* return toBinhex(res); */
    //			return in;
    //		}
    else if (format.equalsIgnoreCase(TO_ASCIIHEX)) {
      // To ASCII Hex format
      return toAsciiHex(res);
    } else {
      // Unknown format wanted. we send back as original
      logger.debug(
          "Unknown conversion format "
              + format
              + " specified for Base64 Conversion.\nReturning original value");
      return in;
      // throw new IllegalArgumentException("Unknown conversion format " + format + " specified for
      // Base64 Conversion.");
    }
  }

  /**
   * Return the binary version of the Base64 value. Since the input is already base64 decoded we
   * just create a String with the supplied byte array and return it as our result.
   *
   * @param value Value to be converted
   * @return String represnting the binary representation
   */
  private static String toBinary(byte[] value) {
    return new String(value);
  }

  /**
   * Return the binhex version of the base64 value supplied. This conversion operation is based on
   * the algorithm found in Python 2.2.1 library and is and adaption of it. Please refer to:
   * <href>http://www.python.org/doc/current/lib/module-binascii.html</href> for more information
   *
   * @param value Value to be converted
   * @return String representing the binhex representation
   */
  private static String toBinhex(byte[] value) {
    /*
     * [Martin's Note: 25-Apr-03 9:16:00 AM]
     *
     * The only implementation of the BinHex algorithm I found is related to the
     * Macintosh and published by Peter Lewis. I'm not sure we should support that
     * conversion format because it is not readily available. The implementation is
     * postponed for now.......
     *
     * Come and see me if you have a problem with this....
     */
    return null;
  }

  /**
   * Return the hexadecimal representation of the binary data. Every byte of data is converted into
   * the corresponding 2-digit hex representation. The resulting string is therefore twice as long
   * as the length of data
   *
   * @param value Value to be converted
   * @return String representing the ASCIIHex version of the value
   */
  private static String toAsciiHex(byte[] value) {
    // Define the hexadecimal alphabet here...
    char[] hexAlphabet = {
      '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
    };

    StringBuffer hexResult = new StringBuffer();
    for (int idx = 0; idx < value.length; idx++) {
      // All values are made up of 2 characters, so check both.
      int currentValue = value[idx];
      int bigEndian = currentValue >> 4;
      int smallEndian = currentValue - (bigEndian * 16);

      // Add both hex values to our string
      hexResult.append(hexAlphabet[bigEndian]);
      hexResult.append(hexAlphabet[smallEndian]);
    }

    // Return our string result containing the hex value
    return hexResult.toString();
  }
}