@Before
 public void setUp() {
   habitat = getHabitat();
   parameters = new ParameterMap();
   cr = habitat.getService(CommandRunner.class);
   assertTrue(cr != null);
   Resources resources = habitat.<Domain>getService(Domain.class).getResources();
   context =
       new AdminCommandContextImpl(
           LogDomains.getLogger(ListJavaMailResourcesTest.class, LogDomains.ADMIN_LOGGER),
           new PropsFileActionReporter());
   for (Resource resource : resources.getResources()) {
     if (resource instanceof MailResource) {
       origNum = origNum + 1;
     }
   }
 }
/** @author Manisha Umbarje */
public class NMRServerConnection implements WebServiceContextDelegate {

  private MessageExchange me;
  private ServiceEngineEndpoint endpt;
  private MessageExchangeTransport meTransport;

  private static Logger logger = LogDomains.getLogger(LogDomains.SERVER_LOGGER);

  /** Creates a new instance of NMRServerConnection */
  public NMRServerConnection(MessageExchange messageExchange, ServiceEngineEndpoint endpt) {
    this.me = messageExchange;
    this.endpt = endpt;
    meTransport = MessageExchangeTransportFactory.getHandler(me);
  }

  public Message receiveRequest() {
    return meTransport.receive(endpt.getEndpointMetaData());
  }

  public void sendResponse(Message abstractMessage) throws Exception {
    meTransport.send(abstractMessage, endpt.getEndpointMetaData());
  }

  public void handleException(Exception e) {
    meTransport.sendError(e);
  }

  // TODO: Implement these methods
  public Principal getUserPrincipal(Packet request) {
    return null;
  }

  public boolean isUserInRole(Packet request, String role) {
    return false;
  }

  public String getEPRAddress(Packet request, WSEndpoint endpoint) {
    return null;
  }

  public String getWSDLAddress(Packet request, WSEndpoint endpoint) {
    return null;
  }
}
/**
 * A class that is used to restore SFSB conversational state
 *
 * @author Mahesh Kannan
 */
public class EJBObjectInputStreamHandler implements GlassFishInputStreamHandler {
  private static final Logger _ejbLogger =
      LogDomains.getLogger(EJBObjectInputStreamHandler.class, LogDomains.EJB_LOGGER);

  @Override
  public Object resolveObject(Object obj) throws IOException {

    // Until we've identified a remote object, we can't assume the orb is
    // available in the container.  If the orb is not present, this will be null.
    ProtocolManager protocolMgr = getProtocolManager();

    try {
      if ((protocolMgr != null) && protocolMgr.isStub(obj)) {
        protocolMgr.connectObject((Remote) obj);
        return obj;
      } else if (obj instanceof SerializableObjectFactory) {
        return ((SerializableObjectFactory) obj).createObject();
      } else {
        return obj;
      }
    } catch (IOException ioEx) {
      _ejbLogger.log(Level.SEVERE, "ejb.resolve_object_exception", ioEx);
      throw ioEx;
    } catch (Exception ex) {
      _ejbLogger.log(Level.SEVERE, "ejb.resolve_object_exception", ex);
      IOException ioe = new IOException();
      ioe.initCause(ex);
      throw ioe;
    }
  }

  /**
   * Do all ProtocolManager access lazily and only request orb if it has already been initialized so
   * that code doesn't make the assumption that an orb is available in this runtime.
   */
  private ProtocolManager getProtocolManager() {
    GlassFishORBHelper orbHelper =
        Globals.getDefaultHabitat().getComponent(GlassFishORBHelper.class);
    return orbHelper.isORBInitialized() ? orbHelper.getProtocolManager() : null;
  }
}
  /**
   * Test of execute method, of class ListJdbcResource. delete-javamail-resource mailresource
   * list-javamail-resources
   */
  @Test
  public void testExecuteSuccessListNoMailResource() {
    createJavaMailResource();

    parameters = new ParameterMap();
    org.glassfish.resources.javamail.admin.cli.ListJavaMailResources listCommand =
        habitat.getService(org.glassfish.resources.javamail.admin.cli.ListJavaMailResources.class);
    cr.getCommandInvocation("list-javamail-resources", context.getActionReport(), adminSubject())
        .parameters(parameters)
        .execute(listCommand);

    List<ActionReport.MessagePart> list =
        context.getActionReport().getTopMessagePart().getChildren();
    assertEquals(origNum + 1, list.size());
    origNum = origNum + 1; // as we newly created a resource after test "setup".

    deleteJavaMailResource();
    parameters = new ParameterMap();
    listCommand =
        habitat.getService(org.glassfish.resources.javamail.admin.cli.ListJavaMailResources.class);
    context =
        new AdminCommandContextImpl(
            LogDomains.getLogger(ListJavaMailResourcesTest.class, LogDomains.ADMIN_LOGGER),
            new PropsFileActionReporter());
    cr.getCommandInvocation("list-javamail-resources", context.getActionReport(), adminSubject())
        .parameters(parameters)
        .execute(listCommand);
    list = context.getActionReport().getTopMessagePart().getChildren();
    if ((origNum - 1) == 0) {
      // Nothing to list.
    } else {
      assertEquals(origNum - 1, list.size());
    }
    List<String> listStr = new ArrayList<String>();
    for (MessagePart mp : list) {
      listStr.add(mp.getMessage());
    }
    assertFalse(listStr.contains("mailresource"));
    assertEquals(ActionReport.ExitCode.SUCCESS, context.getActionReport().getActionExitCode());
  }
/**
 * A Factory class for creating EJBObject input/output Stream
 *
 * @author Mahesh Kannan
 */
public class J2EEObjectStreamFactoryImpl implements J2EEObjectStreamFactory {

  private static final Logger _ejbLogger = LogDomains.getLogger(LogDomains.EJB_LOGGER);

  public J2EEObjectStreamFactoryImpl() {}

  /**
   * Obtain an ObjectOutputStream that allows serialization of a graph of objects. The objects can
   * be plain Serializable objects or can be converted into Serializable objects using the handler
   *
   * @throws IOException when the serialziation fails
   * @return an ObjectOutputStream that can be used to serialize objects
   */
  public ObjectOutputStream createObjectOutputStream(
      final OutputStream os,
      final boolean replaceObject,
      final NonSerializableObjectHandler handler)
      throws IOException {
    // Need privileged block here because EJBObjectOutputStream
    // does enableReplaceObject
    ObjectOutputStream oos = null;
    if (System.getSecurityManager() == null) {
      oos = new EJBObjectOutputStream(os, replaceObject, handler);
    } else {
      try {
        oos =
            (ObjectOutputStream)
                AccessController.doPrivileged(
                    new PrivilegedExceptionAction() {
                      public java.lang.Object run() throws Exception {
                        return new EJBObjectOutputStream(os, replaceObject, handler);
                      }
                    });
      } catch (PrivilegedActionException ex) {
        throw (IOException) ex.getException();
      }
    }
    return oos;
  }

  /**
   * Obtain an ObjectInputStream that allows de-serialization of a graph of objects.
   *
   * @throws IOException when the de-serialziation fails
   * @return an ObjectInputStream that can be used to deserialize objects
   */
  public ObjectInputStream createObjectInputStream(
      final InputStream is, final boolean resolveObject, final ClassLoader loader)
      throws Exception {
    ObjectInputStream ois = null;
    if (loader != null) {
      // Need privileged block here because EJBObjectInputStream
      // does enableResolveObject
      if (System.getSecurityManager() == null) {
        ois = new EJBObjectInputStream(is, loader, resolveObject);
      } else {
        try {
          ois =
              (ObjectInputStream)
                  AccessController.doPrivileged(
                      new PrivilegedExceptionAction() {
                        public java.lang.Object run() throws Exception {
                          return new EJBObjectInputStream(is, loader, resolveObject);
                        }
                      });
        } catch (PrivilegedActionException ex) {
          throw (IOException) ex.getException();
        }
      }
    } else {
      ois = new ObjectInputStream(is);
    }

    return ois;
  }
}
/**
 * If web service client is JBI enabled, transport factory is set to NMR, otherwise ususal JAXWS
 * stack is used.
 *
 * <p><b>Not thread-safe</b>
 *
 * @author Manisha Umbarje
 */
public class ServiceEngineUtil {

  public static final String JBI_ENABLED = "jbi-enabled";
  private static final String seDisablePropertyValue =
      System.getProperty("com.sun.enterprise.jbi.se.disable");
  private static final boolean seEnabledFlag = !("true".equals(seDisablePropertyValue));
  private static final ApplicationLoaderEventListenerImpl listener =
      new ApplicationLoaderEventListenerImpl();

  private static final Logger logger = LogDomains.getLogger(LogDomains.SERVER_LOGGER);

  public static ApplicationLoaderEventListenerImpl getListener() {
    return listener;
  }

  public static boolean isServiceJBIEnabled(ServiceReferenceDescriptor desc) {
    if (isServiceEngineEnabled()) {
      java.util.Set portsInfo = desc.getPortsInfo();
      java.util.Iterator ports = portsInfo.iterator();
      while (ports.hasNext()) {
        ServiceRefPortInfo portDesc = (ServiceRefPortInfo) ports.next();
        if (isPortJbiEnabled(portDesc)) return true;
      }
    }
    return false;
  }

  public static void setJBITransportFactory(
      ServiceRefPortInfo portInfo, Object stubObj, boolean jbiEnabled) {
    if (isServiceEngineEnabled()) {
      ServiceReferenceDescriptor serviceRef = portInfo.getServiceReference();
      if (serviceRef != null && stubObj != null) {
        if (isServiceEngineEnabled() && jbiEnabled && serviceRef.getMappingFileUri() != null) {
          setTransportFactory((com.sun.xml.rpc.spi.runtime.StubBase) stubObj, portInfo);
        }
      }
    } else {
      logger.log(Level.INFO, "Java EE Service Engine's functionality is disabled");
    }
  }

  public static boolean isServiceEngineEnabled() {
    return seEnabledFlag;
  }

  public static ServiceRefPortInfo getPortInfo(WSClientContainer container, QName portName) {
    return container.svcRef.getPortInfoByPort(portName);
  }

  public static boolean isJBIRequest(String delegateClassName) {
    return delegateClassName.equals(
        "com.sun.enterprise.jbi.serviceengine." + "bridge.transport.NMRServerConnection");
  }

  private static boolean isPortJbiEnabled(ServiceRefPortInfo portInfo) {
    if (portInfo != null) {
      String value = portInfo.getStubPropertyValue(JBI_ENABLED);
      logger.log(Level.FINEST, "JBI_ENABLED flag value is : " + value);
      return "true".equals(value);
    } else {
      // This means the deployer did not resolve the port to
      // which this SEI is mapped, return false;
    }
    return false;
  }

  private static void setTransportFactory(
      com.sun.xml.rpc.spi.runtime.StubBase stubObj, ServiceRefPortInfo portInfo) {
    try {
      // This is done to avoide classloader issues.
      // Check out ServiceEngineRtObjectFactory for more details.
      com.sun.xml.rpc.spi.runtime.ClientTransportFactory factory =
          (com.sun.xml.rpc.spi.runtime.ClientTransportFactory)
              ServiceEngineRtObjectFactory.getInstance()
                  .getFacade()
                  .getTransportFactory(portInfo, true);
      if (factory == null) return;

      logger.log(Level.INFO, "Before setting setTransportFactory to NMR");
      // Set JBI transport factory
      stubObj._setTransportFactory(factory);

    } catch (Exception e) {
      // Do nothing.
      if (logger.isLoggable(Level.WARNING)) {
        logger.log(Level.WARNING, "Error during setting of transport factory" + e.getMessage());
      }
    }
  }
}
 static {
   _logger = LogDomains.getLogger(LogDomains.CORBA_LOGGER);
 }
Exemple #8
0
/** Handy class full of static functions. */
public final class Utility {

  static Logger _logger = LogDomains.getLogger(Utility.class, LogDomains.UTIL_LOGGER);

  private static LocalStringManagerImpl localStrings = new LocalStringManagerImpl(Utility.class);

  public static void checkJVMVersion() {
    // do not perform any JVM version checking
  }

  public static Properties getPropertiesFromFile(String file) throws IOException {
    InputStream is = ClassLoader.getSystemResourceAsStream(file);
    if (is != null) {
      Properties config = new Properties();
      config.load(is);
      return config;
    } else {
      String remoteclient = "/" + file;
      InputStream is2 = Utility.class.getResourceAsStream(remoteclient);
      Properties config = new Properties();
      config.load(is2);
      return config;
    }
  }

  /** Return the hostname of the local machine. */
  public static String getLocalHost() {
    String hostname = null;
    try {
      InetAddress ia = InetAddress.getLocalHost();
      hostname = ia.getHostName();
    } catch (UnknownHostException e) {
      return "localhost";
    }
    return hostname;
  }

  /** Return the hostname of the local machine. */
  public static String getLocalAddress() {
    String address = null;
    try {
      InetAddress ia = InetAddress.getLocalHost();
      address = ia.getHostAddress();
    } catch (UnknownHostException e) {
      return "127.0.0.1";
    }
    return address;
  }

  /**
   * This is a convenience method to lookup a remote object by name within the naming context.
   *
   * @exception javax.naming.NamingException if the object with that name could not be found.
   */
  public static java.rmi.Remote lookupObject(String publishedName, java.lang.Class anInterface)
      throws javax.naming.NamingException {

    Context ic = new InitialContext();
    java.lang.Object objRef = ic.lookup(publishedName);
    return (java.rmi.Remote) PortableRemoteObject.narrow(objRef, anInterface);
  }

  /**
   * Unmarshal a byte array to an integer. Assume the bytes are in BIGENDIAN order. i.e.
   * array[offset] is the most-significant-byte and array[offset+3] is the least-significant-byte.
   *
   * @param array The array of bytes.
   * @param offset The offset from which to start unmarshalling.
   */
  public static int bytesToInt(byte[] array, int offset) {
    int b1, b2, b3, b4;

    b1 = (array[offset++] << 24) & 0xFF000000;
    b2 = (array[offset++] << 16) & 0x00FF0000;
    b3 = (array[offset++] << 8) & 0x0000FF00;
    b4 = (array[offset++] << 0) & 0x000000FF;

    return (b1 | b2 | b3 | b4);
  }

  /**
   * Marshal an integer to a byte array. The bytes are in BIGENDIAN order. i.e. array[offset] is the
   * most-significant-byte and array[offset+3] is the least-significant-byte.
   *
   * @param array The array of bytes.
   * @param offset The offset from which to start marshalling.
   */
  public static void intToBytes(int value, byte[] array, int offset) {
    array[offset++] = (byte) ((value >>> 24) & 0xFF);
    array[offset++] = (byte) ((value >>> 16) & 0xFF);
    array[offset++] = (byte) ((value >>> 8) & 0xFF);
    array[offset++] = (byte) ((value >>> 0) & 0xFF);
  }

  /**
   * Unmarshal a byte array to an long. Assume the bytes are in BIGENDIAN order. i.e. array[offset]
   * is the most-significant-byte and array[offset+7] is the least-significant-byte.
   *
   * @param array The array of bytes.
   * @param offset The offset from which to start unmarshalling.
   */
  public static long bytesToLong(byte[] array, int offset) {
    long l1, l2;

    l1 = (long) bytesToInt(array, offset) << 32;
    l2 = (long) bytesToInt(array, offset + 4) & 0xFFFFFFFFL;

    return (l1 | l2);
  }

  /**
   * Marshal an long to a byte array. The bytes are in BIGENDIAN order. i.e. array[offset] is the
   * most-significant-byte and array[offset+7] is the least-significant-byte.
   *
   * @param array The array of bytes.
   * @param offset The offset from which to start marshalling.
   */
  public static void longToBytes(long value, byte[] array, int offset) {
    array[offset++] = (byte) ((value >>> 56) & 0xFF);
    array[offset++] = (byte) ((value >>> 48) & 0xFF);
    array[offset++] = (byte) ((value >>> 40) & 0xFF);
    array[offset++] = (byte) ((value >>> 32) & 0xFF);
    array[offset++] = (byte) ((value >>> 24) & 0xFF);
    array[offset++] = (byte) ((value >>> 16) & 0xFF);
    array[offset++] = (byte) ((value >>> 8) & 0xFF);
    array[offset++] = (byte) ((value >>> 0) & 0xFF);
  }

  /** Verify and invoke main if present in the specified class. */
  public static void invokeApplicationMain(Class mainClass, String[] args)
      throws InvocationTargetException, IllegalAccessException, ClassNotFoundException {
    String err = localStrings.getLocalString("utility.no.main", "", new Object[] {mainClass});

    // determine the main method using reflection
    // verify that it is public static void and takes
    // String[] as the only argument
    Method mainMethod = null;
    try {
      mainMethod = mainClass.getMethod("main", new Class[] {String[].class});
    } catch (NoSuchMethodException msme) {
      _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility", msme);
      throw new ClassNotFoundException(err);
    }

    // check modifiers: public static
    int modifiers = mainMethod.getModifiers();
    if (!Modifier.isPublic(modifiers) || !Modifier.isStatic(modifiers)) {
      err =
          localStrings.getLocalString(
              "utility.main.notpublicorstatic",
              "The main method is either not public or not static");
      _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notpublicorstatic");
      throw new ClassNotFoundException(err);
    }

    // check return type and exceptions
    if (!mainMethod.getReturnType().equals(Void.TYPE)) {
      err =
          localStrings.getLocalString(
              "utility.main.notvoid", "The main method's return type is not void ");
      _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notvoid");
      throw new ClassNotFoundException(err);
    }

    // build args to the main and call it
    Object params[] = new Object[1];
    params[0] = args;
    mainMethod.invoke(null, params);
  }

  public static void invokeSetMethod(Object obj, String prop, String value)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Class cl = obj.getClass();
    // change first letter to uppercase
    String setMeth = "set" + prop.substring(0, 1).toUpperCase() + prop.substring(1);

    // try string method
    try {
      Class[] cldef = {String.class};
      Method meth = cl.getMethod(setMeth, cldef);
      Object[] params = {value};
      meth.invoke(obj, params);
      return;
    } catch (NoSuchMethodException ex) {
      try {
        // try int method
        Class[] cldef = {Integer.TYPE};
        Method meth = cl.getMethod(setMeth, cldef);
        Object[] params = {Integer.valueOf(value)};
        meth.invoke(obj, params);
        return;
      } catch (NoSuchMethodException nsmex) {
        // try boolean method
        Class[] cldef = {Boolean.TYPE};
        Method meth = cl.getMethod(setMeth, cldef);
        Object[] params = {Boolean.valueOf(value)};
        meth.invoke(obj, params);
        return;
      }
    }
  }

  public static void invokeSetMethodCaseInsensitive(Object obj, String prop, String value)
      throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    String alternateMethodName = null;
    Class cl = obj.getClass();

    String setMeth = "set" + prop;

    Method[] methodsList = cl.getMethods();
    boolean methodFound = false;
    int i = 0;
    for (i = 0; i < methodsList.length; ++i) {
      if (methodsList[i].getName().equalsIgnoreCase(setMeth) == true) {
        Class[] parameterTypes = methodsList[i].getParameterTypes();
        if (parameterTypes.length == 1) {
          if (parameterTypes[0].getName().equals("java.lang.String")) {
            methodFound = true;
            break;
          } else alternateMethodName = methodsList[i].getName();
        }
      }
    }
    if (methodFound == true) {
      Object[] params = {value};
      methodsList[i].invoke(obj, params);
      return;
    }
    if (alternateMethodName != null) {
      try {
        // try int method
        Class[] cldef = {Integer.TYPE};
        Method meth = cl.getMethod(alternateMethodName, cldef);
        Object[] params = {Integer.valueOf(value)};
        meth.invoke(obj, params);
        return;
      } catch (NoSuchMethodException nsmex) {
        // try boolean method
        Class[] cldef = {Boolean.TYPE};
        Method meth = cl.getMethod(alternateMethodName, cldef);
        Object[] params = {Boolean.valueOf(value)};
        meth.invoke(obj, params);
        return;
      }

    } else throw new NoSuchMethodException(setMeth);
  }

  // Ports are marshalled as shorts on the wire.  The IDL
  // type is unsigned short, which lacks a convenient representation
  // in Java in the 32768-65536 range.  So, we treat ports as
  // ints throught this code, except that marshalling requires a
  // scaling conversion.  intToShort and shortToInt are provided
  // for this purpose.

  public static short intToShort(int value) {
    if (value > 32767) return (short) (value - 65536);
    return (short) value;
  }

  public static int shortToInt(short value) {
    if (value < 0) return value + 65536;
    return value;
  }

  /**
   * Get the current thread's context class loader which is set to the CommonClassLoader by
   * ApplicationServer
   *
   * @return the thread's context classloader if it exists; else the system class loader.
   */
  public static ClassLoader getClassLoader() {
    if (Thread.currentThread().getContextClassLoader() != null) {
      return Thread.currentThread().getContextClassLoader();
    } else {
      return ClassLoader.getSystemClassLoader();
    }
  }

  /**
   * Loads the class with the common class loader.
   *
   * @param className the class name
   * @return the loaded class
   * @exception if the class is not found.
   */
  public static Class loadClass(String className) throws ClassNotFoundException {
    return getClassLoader().loadClass(className);
  }

  /** Utility routine for setting the context class loader. Returns previous class loader. */
  public static ClassLoader setContextClassLoader(ClassLoader newClassLoader) {

    // Can only reference final local variables from dopriveleged block
    final ClassLoader classLoaderToSet = newClassLoader;

    final Thread currentThread = Thread.currentThread();
    ClassLoader originalClassLoader = currentThread.getContextClassLoader();

    if (classLoaderToSet != originalClassLoader) {
      if (System.getSecurityManager() == null) {
        currentThread.setContextClassLoader(classLoaderToSet);
      } else {
        java.security.AccessController.doPrivileged(
            new java.security.PrivilegedAction() {
              public java.lang.Object run() {
                currentThread.setContextClassLoader(classLoaderToSet);
                return null;
              }
            });
      }
    }
    return originalClassLoader;
  }

  public static void setEnvironment() {
    Environment.obtain().activateEnvironment();
  }
  /**
   * Return the value for a given name from the System Properties or the Environmental Variables.
   * The former overrides the latter.
   *
   * @param name - the name of the System Property or Environmental Variable
   * @return the value of the variable or null if it was not found
   */
  public static String getEnvOrProp(String name) {
    // System properties override env. variables
    String envVal = System.getenv(name);
    String sysPropVal = System.getProperty(name);

    if (sysPropVal != null) return sysPropVal;

    return envVal;
  }

  /**
   * Convert the byte array to char array with respect to given charset.
   *
   * @param byteArray
   * @param charset null or "" means default charset
   * @exception CharacterCodingException
   */
  public static char[] convertByteArrayToCharArray(byte[] byteArray, String charset)
      throws CharacterCodingException {

    if (byteArray == null) {
      return null;
    }

    byte[] bArray = (byte[]) byteArray.clone();
    ByteBuffer byteBuffer = ByteBuffer.wrap(bArray);
    Charset charSet;
    if (charset == null || "".equals(charset)) {
      charSet = Charset.defaultCharset();
    } else if (Charset.isSupported(charset)) {
      charSet = Charset.forName(charset);
    } else {
      CharacterCodingException e = new CharacterCodingException();
      e.initCause(new UnsupportedCharsetException(charset));
      throw e;
    }

    CharsetDecoder decoder = charSet.newDecoder();
    CharBuffer charBuffer = null;
    try {
      charBuffer = decoder.decode(byteBuffer);
    } catch (CharacterCodingException cce) {
      throw cce;
    } catch (Throwable t) {
      CharacterCodingException e = new CharacterCodingException();
      e.initCause(t);
      throw e;
    }
    char[] result = (char[]) charBuffer.array().clone();
    clear(byteBuffer);
    clear(charBuffer);

    return result;
  }

  /**
   * Convert the char array to byte array with respect to given charset.
   *
   * @param charArray
   * @param strCharset null or "" means default charset
   * @exception CharacterCodingException
   */
  public static byte[] convertCharArrayToByteArray(char[] charArray, String strCharset)
      throws CharacterCodingException {

    if (charArray == null) {
      return null;
    }

    char[] cArray = (char[]) charArray.clone();
    CharBuffer charBuffer = CharBuffer.wrap(cArray);
    Charset charSet;
    if (strCharset == null || "".equals(strCharset)) {
      charSet = Charset.defaultCharset();
    } else if (Charset.isSupported(strCharset)) {
      charSet = Charset.forName(strCharset);
    } else {
      CharacterCodingException e = new CharacterCodingException();
      e.initCause(new UnsupportedCharsetException(strCharset));
      throw e;
    }

    CharsetEncoder encoder = charSet.newEncoder();
    ByteBuffer byteBuffer = null;
    try {
      byteBuffer = encoder.encode(charBuffer);
    } catch (CharacterCodingException cce) {
      throw cce;
    } catch (Throwable t) {
      CharacterCodingException e = new CharacterCodingException();
      e.initCause(t);
      throw e;
    }

    byte[] result = new byte[byteBuffer.remaining()];
    byteBuffer.get(result);
    clear(byteBuffer);
    clear(charBuffer);

    return result.clone();
  }

  private static void clear(ByteBuffer byteBuffer) {
    byte[] bytes = byteBuffer.array();
    for (int i = 0; i < bytes.length; i++) {
      bytes[i] = 0;
    }
  }

  private static void clear(CharBuffer charBuffer) {
    char[] chars = charBuffer.array();
    for (int i = 0; i < chars.length; i++) {
      chars[i] = '0';
    }
  }
}
public class FlashlightProbe implements ProbeHandle, ProbeInfo {

  public FlashlightProbe(
      int id,
      Class providerClazz,
      String moduleProviderName,
      String moduleName,
      String probeProviderName,
      String probeName,
      String[] probeParamNames,
      Class[] paramTypes,
      boolean self,
      boolean hidden) {
    this.id = id;
    this.providerClazz = providerClazz;
    this.moduleProviderName = moduleProviderName;
    this.moduleName = moduleName;
    this.probeProviderName = probeProviderName;
    this.probeName = probeName;
    this.probeDesc =
        moduleProviderName + ":" + moduleName + ":" + probeProviderName + ":" + probeName;
    this.hasSelf = self;
    this.hidden = hidden;

    if (self) {
      if (isMethodStatic()) {
        String errStr =
            localStrings.getLocalString(
                "cannotDefineSelfOnStatic",
                "Cannot define \"self\" on a static method - ",
                probeDesc);
        throw new RuntimeException(errStr);
      }
      // Fill in the first slot of ParamNames with @Self and paramTypes with the providerClass type
      this.probeParamNames = new String[probeParamNames.length + 1];
      this.paramTypes = new Class[paramTypes.length + 1];
      this.probeParamNames[0] = SELF;
      this.paramTypes[0] = providerClazz;
      for (int index = 0; index < probeParamNames.length; index++) {
        this.probeParamNames[index + 1] = probeParamNames[index];
        this.paramTypes[index + 1] = paramTypes[index];
      }
    } else {
      this.probeParamNames = probeParamNames;
      this.paramTypes = paramTypes;
    }
  }

  public Method getProbeMethod() {
    return probeMethod;
  }

  public void setProbeMethod(Method probeMethod) {
    this.probeMethod = probeMethod;
  }

  private boolean isMethodStatic() {
    try {
      int modifier =
          getProviderClazz()
              .getDeclaredMethod(getProviderJavaMethodName(), getParamTypes())
              .getModifiers();
      return Modifier.isStatic(modifier);
    } catch (Exception e) {
      return false;
    }
  }

  public synchronized boolean addInvoker(ProbeClientInvoker invoker) {
    boolean isFirst = (invokers.isEmpty() && firstTransform);

    if (invokers.putIfAbsent(invoker.getId(), invoker) != null) {
      if (logger.isLoggable(Level.FINE))
        logger.fine("Adding an invoker that already exists: " + invoker.getId() + "  &&&&&&&&&&");
    } else {
      if (logger.isLoggable(Level.FINE))
        logger.fine("Adding an Invoker that does not exist: " + invoker.getId() + " $$$$$$$$$$$$$");
    }
    if (logger.isLoggable(Level.FINE)) {
      logger.fine("Total invokers = " + invokers.size());
    }
    listenerEnabled.set(true);
    firstTransform = false;

    initInvokerList();
    return isFirst;
  }

  public synchronized boolean removeInvoker(ProbeClientInvoker invoker) {
    ProbeClientInvoker pci = invokers.remove(invoker.getId());

    if (pci != null) {
      if (logger.isLoggable(Level.FINE))
        logger.fine("Removing an invoker that already exists: " + pci.getId() + "  ##########");
    } else {
      if (logger.isLoggable(Level.FINE))
        logger.fine(
            "Failed to remove an invoker that does not exist: " + invoker.getId() + "  %%%%%%%%%");
    }
    if (logger.isLoggable(Level.FINE)) {
      logger.fine("Total invokers = " + invokers.size());
    }

    listenerEnabled.set(!invokers.isEmpty());

    initInvokerList();
    return listenerEnabled.get();
  }

  public void fireProbe(Object[] params) {
    if (!listenerEnabled.get()) {
      return;
    }

    if (parent != null) {
      parent.fireProbe(params);
    }

    int sz = invokerList.size();

    for (int i = 0; i < sz; i++) {
      ProbeClientInvoker invoker = invokerList.get(i);
      if (invoker != null) {
        invoker.invoke(params);
      }
    }
  }

  public boolean isEnabled() {
    return listenerEnabled.get();
  }

  public int getId() {
    return id;
  }

  public String getModuleProviderName() {
    return moduleProviderName;
  }

  public String getModuleName() {
    return moduleProviderName;
  }

  public String getProbeProviderName() {
    return probeProviderName;
  }

  public String getProbeName() {
    return probeName;
  }

  public String[] getProbeParamNames() {
    return probeParamNames;
  }

  public Class[] getParamTypes() {
    return paramTypes;
  }

  public String getProviderJavaMethodName() {
    return providerJavaMethodName;
  }

  public void setProviderJavaMethodName(String providerJavaMethodName) {
    this.providerJavaMethodName = providerJavaMethodName;
  }

  public String getProbeDesc() {
    return probeDesc;
  }

  public static String getProbeDesc(
      String moduleProviderName, String moduleName, String probeProviderName, String probeName) {
    return (moduleProviderName + ":" + moduleName + ":" + probeProviderName + ":" + probeName);
  }

  public Class getProviderClazz() {
    return providerClazz;
  }

  public String toString() {
    StringBuilder sbldr =
        new StringBuilder(
            moduleProviderName + ":" + moduleName + ":" + probeProviderName + ":" + probeName);
    String delim = " (";
    for (int i = 0; i < paramTypes.length; i++) {
      sbldr.append(delim).append((paramTypes[i] == null) ? " " : paramTypes[i].getName());
      sbldr.append(" ").append((probeParamNames[i] == null) ? " " : probeParamNames[i]);
      delim = ", ";
    }
    if (paramTypes.length == 0) sbldr.append(" (");
    sbldr.append(")");

    return sbldr.toString();
  }

  public void setDTraceProviderImpl(Object impl) {
    dtraceProviderImpl = impl;
  }

  public Object getDTraceProviderImpl() {
    return dtraceProviderImpl;
  }

  public Method getDTraceMethod() {
    return dtraceMethod;
  }

  public void setDTraceMethod(Method m) {
    dtraceMethod = m;
  }

  public boolean hasSelf() {
    return hasSelf;
  }

  public boolean isHidden() {
    return hidden;
  }

  public void setParent(FlashlightProbe parent) {
    this.parent = parent;
  }

  private void initInvokerList() {
    Set<Map.Entry<Integer, ProbeClientInvoker>> entries = invokers.entrySet();

    List<ProbeClientInvoker> invList = new ArrayList(2);
    for (Map.Entry<Integer, ProbeClientInvoker> entry : entries) {
      ProbeClientInvoker invoker = entry.getValue();
      invList.add(invoker);
    }

    invokerList = invList;
  }

  private Method probeMethod;
  public static final String SELF = "@SELF";
  private int id;
  private Class providerClazz;
  private String moduleProviderName;
  private String moduleName;
  private String probeName;
  private String probeProviderName;
  private String[] probeParamNames;
  private Class[] paramTypes;
  private volatile List<ProbeClientInvoker> invokerList = new ArrayList(2);
  private String providerJavaMethodName;
  private AtomicBoolean listenerEnabled = new AtomicBoolean(false);
  private String probeDesc;
  private Object dtraceProviderImpl;
  private Method dtraceMethod;
  private boolean hasSelf;
  private boolean hidden;
  private boolean firstTransform = true;
  private ConcurrentMap<Integer, ProbeClientInvoker> invokers =
      new ConcurrentHashMap<Integer, ProbeClientInvoker>();
  private static final Logger logger =
      LogDomains.getLogger(FlashlightProbe.class, LogDomains.MONITORING_LOGGER);
  public static final LocalStringManagerImpl localStrings =
      new LocalStringManagerImpl(FlashlightProbe.class);
  private FlashlightProbe parent = null;
}
Exemple #10
0
/**
 * Logs a message when it detects that a SQL query is slow.
 *
 * @author steve
 */
public class SlowSQLLogger implements SQLTraceListener {

  private static final Logger logger =
      LogDomains.getLogger(SQLTraceLogger.class, LogDomains.SQL_TRACE_LOGGER);
  private static ThreadLocal<SQLQuery> currentQuery = new ThreadLocal<>();
  private long threshold = 10000; // 10 second default threshold

  public SlowSQLLogger(long threshold) {
    this.threshold = threshold;
  }

  public SlowSQLLogger() {}

  public long getThreshold() {
    return threshold;
  }

  public void setThreshold(long threshold) {
    this.threshold = threshold;
  }

  @Override
  public void sqlTrace(SQLTraceRecord record) {
    if (record != null) {
      switch (record.getMethodName()) {

          // these calls capture a query string
        case "nativeSQL":
        case "prepareCall":
        case "prepareStatement":
        case "addBatch":
          {
            // acquire the SQL
            SQLQuery query = currentQuery.get();
            if (query == null) {
              query = new SQLQuery();
              currentQuery.set(query);
            }
            if (record.getParams() != null && record.getParams().length > 0)
              query.addSQL((String) record.getParams()[0]);
            break;
          }
        case "execute":
        case "executeQuery":
        case "executeUpdate":
          {
            // acquire the SQL
            SQLQuery query = currentQuery.get();
            if (query == null) {
              query = new SQLQuery();
              currentQuery.set(query);
            } // these can all run the SQL and contain SQL
            long executionTime = record.getExecutionTime();
            // see if we have more SQL
            if (record.getParams() != null && record.getParams().length > 0) {
              // gather the SQL
              query.addSQL((String) record.getParams()[0]);
            }

            // check the execution time

            if (executionTime > threshold) {
              StringBuilder messageBuilder =
                  new StringBuilder("SQL Query Exceeded Threshold Time: ");
              messageBuilder
                  .append(threshold)
                  .append("(ms): Time Taken: ")
                  .append(executionTime)
                  .append("(ms)\n")
                  .append("Query was ")
                  .append(query.getSQL());
              logger.log(
                  Level.WARNING,
                  messageBuilder.toString(),
                  new Exception("Stack Trace shows code path to SQL"));
            }
            // clean the thread local
            currentQuery.set(null);
            break;
          }
      }
    }
  }
}
/** @author lwhite */
public class FailureSuspectedNotificationEventHandler implements CallBack {

  private static final Logger _logger = LogDomains.getLogger(LogDomains.WEB_LOGGER);

  private static HashMap suspectedFailures = new HashMap();

  /** Creates a new instance of SuspectedFailureNotificationEventHandler */
  public FailureSuspectedNotificationEventHandler() {}

  public void processNotification(Signal notification) {
    String failedPartnerInstance = notification.getMemberToken();
    if (_logger.isLoggable(Level.FINEST)) {
      _logger.finest("Received Suspected Failure Notification: " + failedPartnerInstance);
    }
    // check and if 2nd suspected failure in 6 second window
    // then process the failure
    checkSuspectedFailureFor(failedPartnerInstance);
    // was this
    // if(!ReplicationHealthChecker.isStopping()
    //    && !ReplicationHealthChecker.isReplicationCommunicationOperational()) {
    /*
    if(!ReplicationHealthChecker.isStopping()) {
        JxtaReplicationReceiver jxtaReplicationReceiver
            = (JxtaReplicationReceiver) ReplicationHealthChecker.getReplicationReceiver();
        if (_logger.isLoggable(Level.FINEST)) {
            _logger.finest("suspected failure notification causing call to respondToFailure");
        }
        jxtaReplicationReceiver.respondToFailure(failedPartnerInstance);
    }
     */
  }

  static boolean isSuspectedFailureCredible(String instanceName) {
    long timeNow = System.currentTimeMillis();
    Long suspectedFailureTimeMillis = (Long) suspectedFailures.get((String) instanceName);
    if (suspectedFailureTimeMillis != null) {
      removeSuspectedFailure(instanceName);
      if ((timeNow - suspectedFailureTimeMillis.longValue()) < 6000) {
        System.out.println("credible suspected failure of " + instanceName);
        return true;
      } else {
        System.out.println("suspected failure is not pending or more than 6 sec old");
        // add the new suspected failure
        addSuspectedFailure(instanceName);
        return false;
      }
    } else {
      // this is the first suspected failure - adding it
      System.out.println(
          "Received Suspected Failure Notification: adding suspected failure for" + instanceName);
      addSuspectedFailure(instanceName);
      return false;
    }
  }

  static void addSuspectedFailure(String instanceName) {
    suspectedFailures.put(instanceName, new Long(System.currentTimeMillis()));
  }

  static void removeSuspectedFailure(String instanceName) {
    suspectedFailures.remove(instanceName);
  }

  // check and if 2nd suspected failure in 6 second window
  // then process the failure
  static void checkSuspectedFailureFor(String instanceName) {
    if (!isSuspectedFailureCredible(instanceName)) {
      return;
    }
    if (!ReplicationHealthChecker.isStopping()) {
      JxtaReplicationReceiver jxtaReplicationReceiver =
          (JxtaReplicationReceiver) ReplicationHealthChecker.getReplicationReceiver();
      if (_logger.isLoggable(Level.FINEST)) {
        _logger.finest("suspected failure notification causing call to respondToFailure");
      }
      jxtaReplicationReceiver.respondToFailure(instanceName);
    }
  }
}
public class S1ASThreadPoolManager implements ThreadPoolManager {

  private static Logger _logger =
      LogDomains.getLogger(S1ASThreadPoolManager.class, LogDomains.UTIL_LOGGER, false);

  private static final int DEFAULT_NUMBER_OF_QUEUES = 0;
  private static final int DEFAULT_MIN_THREAD_COUNT = 10;
  private static final int DEFAULT_MAX_THREAD_COUNT = 200;

  private static HashMap idToIndexTable = new HashMap();
  private static HashMap indexToIdTable = new HashMap();
  private static ArrayList threadpoolList = new ArrayList();
  private static String defaultID;

  private static ThreadPoolManager s1asThreadPoolMgr = new S1ASThreadPoolManager();
  private static IIOPUtils _iiopUtils;

  public static ThreadPoolManager getThreadPoolManager() {
    return s1asThreadPoolMgr;
  }

  static {
    try {
      _iiopUtils = Globals.getDefaultHabitat().getService(IIOPUtils.class);
      Collection<org.glassfish.grizzly.config.dom.ThreadPool> tpCol =
          _iiopUtils.getAllThreadPools();
      org.glassfish.grizzly.config.dom.ThreadPool[] allThreadPools =
          tpCol.toArray(new org.glassfish.grizzly.config.dom.ThreadPool[tpCol.size()]);
      for (int i = 0; i < allThreadPools.length; i++) {
        createThreadPools(allThreadPools[i], i);
      }
      defaultID = (String) indexToIdTable.get(Integer.valueOf(0));
    } catch (NullPointerException npe) {
      _logger.log(Level.FINE, "Server Context is NULL. Ignoring and proceeding.");
    }
  }

  S1ASThreadPoolManager() {}

  private static void createThreadPools(
      org.glassfish.grizzly.config.dom.ThreadPool threadpoolBean, int index) {
    String threadpoolId = null;
    String minThreadsValue, maxThreadsValue, timeoutValue; // , numberOfQueuesValue;
    int minThreads = DEFAULT_MIN_THREAD_COUNT;
    int maxThreads = DEFAULT_MAX_THREAD_COUNT;
    int idleTimeoutInSeconds = 120000;
    //        int numberOfQueues = DEFAULT_NUMBER_OF_QUEUES;

    try {
      threadpoolId = threadpoolBean.getName();
    } catch (NullPointerException npe) {
      if (_logger.isLoggable(Level.WARNING)) {
        _logger.log(Level.WARNING, "ThreadPoolBean may be null ", npe);
      }
    }
    try {
      minThreadsValue = threadpoolBean.getMinThreadPoolSize();
      minThreads = Integer.parseInt(minThreadsValue);
    } catch (NullPointerException npe) {
      if (_logger.isLoggable(Level.WARNING)) {
        _logger.log(Level.WARNING, "ThreadPoolBean may be null ", npe);
        _logger.log(
            Level.WARNING, "Using default value for steady-threadpool-size = " + minThreads);
      }
    } catch (NumberFormatException nfe) {
      if (_logger.isLoggable(Level.WARNING)) {
        _logger.log(Level.WARNING, "enterprise_util.excep_orbmgr_numfmt", nfe);
        _logger.log(Level.WARNING, "Using default value for min-threadpool-size = " + minThreads);
      }
    }
    try {
      maxThreadsValue = threadpoolBean.getMaxThreadPoolSize();
      maxThreads = Integer.parseInt(maxThreadsValue);
    } catch (NullPointerException npe) {
      if (_logger.isLoggable(Level.WARNING)) {
        _logger.log(Level.WARNING, "ThreadPoolBean may be null ", npe);
        _logger.log(Level.WARNING, "Using default value for max-threadpool-size = " + maxThreads);
      }
    } catch (NumberFormatException nfe) {
      if (_logger.isLoggable(Level.WARNING)) {
        _logger.log(Level.WARNING, "enterprise_util.excep_orbmgr_numfmt", nfe);
        _logger.log(Level.WARNING, "Using default value for max-threadpool-size = " + maxThreads);
      }
    }
    try {
      timeoutValue = threadpoolBean.getIdleThreadTimeoutSeconds();
      idleTimeoutInSeconds = Integer.parseInt(timeoutValue);
    } catch (NullPointerException npe) {
      if (_logger.isLoggable(Level.WARNING)) {
        _logger.log(Level.WARNING, "ThreadPoolBean may be null ", npe);
        _logger.log(
            Level.WARNING,
            "Using default value for idle-thread-timeout-in-seconds = " + idleTimeoutInSeconds);
      }
    } catch (NumberFormatException nfe) {
      if (_logger.isLoggable(Level.WARNING)) {
        _logger.log(Level.WARNING, "enterprise_util.excep_orbmgr_numfmt", nfe);
        _logger.log(
            Level.WARNING,
            "Using default value for idle-thread-timeout-in-seconds = " + idleTimeoutInSeconds);
      }
    }

    // Currently this value is not used but when multi-queue threadpools are
    // implemented this could be used to decide which one to instantiate and
    // number of queues in the multi-queue threadpool
    /*
            try {
                numberOfQueuesValue = threadpoolBean.getNumWorkQueues();
                numberOfQueues = Integer.parseInt(numberOfQueuesValue);
            } catch (NullPointerException npe) {
                if (_logger.isLoggable(Level.WARNING)) {
                    _logger.log(Level.WARNING, "ThreadPoolBean may be null ", npe);
                    _logger.log(Level.WARNING,
                            "Using default value for num-work-queues = " +
                                    numberOfQueues);
                }
            } catch (NumberFormatException nfe) {
                if (_logger.isLoggable(Level.WARNING)) {
                    _logger.log(Level.WARNING, "enterprise_util.excep_orbmgr_numfmt", nfe);
                    _logger.log(Level.WARNING,
                            "Using default value for num-work-queues = " +
                                    numberOfQueues);
                }
            }
    */

    // Mutiplied the idleTimeoutInSeconds by 1000 to convert to milliseconds
    ThreadPoolFactory threadPoolFactory = new ThreadPoolFactory();
    ThreadPool threadpool =
        threadPoolFactory.create(
            minThreads,
            maxThreads,
            idleTimeoutInSeconds * 1000L,
            threadpoolId,
            _iiopUtils.getCommonClassLoader());

    // Add the threadpool instance to the threadpoolList
    threadpoolList.add(threadpool);

    // Associate the threadpoolId to the index passed
    idToIndexTable.put(threadpoolId, Integer.valueOf(index));

    // Associate the threadpoolId to the index passed
    indexToIdTable.put(Integer.valueOf(index), threadpoolId);
  }

  /**
   * This method will return an instance of the threadpool given a threadpoolId, that can be used by
   * any component in the app. server.
   *
   * @throws NoSuchThreadPoolException thrown when invalid threadpoolId is passed as a parameter
   */
  public ThreadPool getThreadPool(String id) throws NoSuchThreadPoolException {

    Integer i = (Integer) idToIndexTable.get(id);
    if (i == null) {
      throw new NoSuchThreadPoolException();
    }
    try {
      ThreadPool threadpool = (ThreadPool) threadpoolList.get(i.intValue());
      return threadpool;
    } catch (IndexOutOfBoundsException iobe) {
      throw new NoSuchThreadPoolException();
    }
  }

  /**
   * This method will return an instance of the threadpool given a numeric threadpoolId. This method
   * will be used by the ORB to support the functionality of dedicated threadpool for EJB beans
   *
   * @throws NoSuchThreadPoolException thrown when invalidnumericIdForThreadpool is passed as a
   *     parameter
   */
  public ThreadPool getThreadPool(int numericIdForThreadpool) throws NoSuchThreadPoolException {

    try {
      ThreadPool threadpool = (ThreadPool) threadpoolList.get(numericIdForThreadpool);
      return threadpool;
    } catch (IndexOutOfBoundsException iobe) {
      throw new NoSuchThreadPoolException();
    }
  }

  /**
   * This method is used to return the numeric id of the threadpool, given a String threadpoolId.
   * This is used by the POA interceptors to add the numeric threadpool Id, as a tagged component in
   * the IOR. This is used to provide the functionality of dedicated threadpool for EJB beans
   */
  public int getThreadPoolNumericId(String id) {
    Integer i = (Integer) idToIndexTable.get(id);
    return ((i == null) ? 0 : i.intValue());
  }

  /** Return a String Id for a numericId of a threadpool managed by the threadpool manager */
  public String getThreadPoolStringId(int numericIdForThreadpool) {
    String id = (String) indexToIdTable.get(Integer.valueOf(numericIdForThreadpool));
    return ((id == null) ? defaultID : id);
  }

  /** Returns the first instance of ThreadPool in the ThreadPoolManager */
  public ThreadPool getDefaultThreadPool() {
    try {
      return getThreadPool(0);
    } catch (NoSuchThreadPoolException nstpe) {
      if (_logger.isLoggable(Level.WARNING)) {
        _logger.log(Level.WARNING, "No default ThreadPool defined ", nstpe);
      }
    }
    return null;
  }

  /**
   * Return an instance of ThreadPoolChooser based on the componentId that was passed as argument
   */
  public ThreadPoolChooser getThreadPoolChooser(String componentId) {
    // FIXME: This method is not used, but should be fixed once
    // ORB's nio select starts working and we start using ThreadPoolChooser
    // This will be mostly used by the ORB
    return null;
  }

  /**
   * Return an instance of ThreadPoolChooser based on the componentIndex that was passed as
   * argument. This is added for improved performance so that the caller does not have to pay the
   * cost of computing hashcode for the componentId
   */
  public ThreadPoolChooser getThreadPoolChooser(int componentIndex) {
    // FIXME: This method is not used, but should be fixed once
    // ORB's nio select starts working and we start using ThreadPoolChooser
    // This will be mostly used by the ORB
    return null;
  }

  /**
   * Sets a ThreadPoolChooser for a particular componentId in the ThreadPoolManager. This would
   * enable any component to add a ThreadPoolChooser for their specific use
   */
  public void setThreadPoolChooser(String componentId, ThreadPoolChooser aThreadPoolChooser) {
    // FIXME: This method is not used, but should be fixed once
    // ORB's nio select starts working and we start using ThreadPoolChooser
    // This will be mostly used by the ORB
  }

  /**
   * Gets the numeric index associated with the componentId specified for a ThreadPoolChooser. This
   * method would help the component call the more efficient implementation i.e.
   * getThreadPoolChooser(int componentIndex)
   */
  public int getThreadPoolChooserNumericId(String componentId) {
    // FIXME: This method is not used, but should be fixed once
    // ORB's nio select starts working and we start using ThreadPoolChooser
    // This will be mostly used by the ORB
    return 0;
  }

  public void close() {
    // TODO
  }
}
public class JTSConfigChangeEventListener implements JTSEventListener {
  // Sting Manager for Localization
  private static StringManager sm = StringManager.getManager(JTSConfigChangeEventListener.class);

  // Logger to log transaction messages
  static Logger _logger = LogDomains.getLogger(LogDomains.JTA_LOGGER);
  public String xPath = ServerXPathHelper.XPATH_TRANSACTION_SERVICE;

  private static ConfigChangeCategory category =
      new ConfigChangeCategory(
          "jts",
          ServerXPathHelper.REGEX_XPATH_CONFIG
              + ServerXPathHelper.XPATH_SEPARATOR
              + ServerXPathHelper.REGEX_ONE_PLUS
              + ServerTags.TRANSACTION_SERVICE
              + ".*");

  public static ConfigChangeCategory getCategory() {
    return category;
  }

  public void handleCreate(JTSEvent event) throws AdminEventListenerException {
    throw new AdminEventListenerException("handleCreate is not valid for JTSEvent");
  }

  public void handleDelete(JTSEvent event) throws AdminEventListenerException {
    throw new AdminEventListenerException("handleDelete is not valid for JTSEvent");
  }

  public void handleUpdate(JTSEvent event) throws AdminEventListenerException {
    // Bug Id: 4666390 Handle no event in event list case
    if (event == null) {
      // do nothing
      return;
    }
    ArrayList configChangeList = event.getConfigChangeList();
    if (configChangeList == null) {
      // do nothing
      return;
    }
    // Bug Id: 4666390 End

    ConfigUpdate configUpdate = null;
    boolean match = false;
    for (int i = 0; i < configChangeList.size(); i++) {
      configUpdate = (ConfigUpdate) configChangeList.get(i);
      if (configUpdate.getXPath() != null
          && configUpdate.getXPath().endsWith(ServerTags.TRANSACTION_SERVICE)) {
        if (xPath.equals(configUpdate.getXPath())) {
          match = true;
          break;
        }
      }
    }
    if (match) { // TransactionService has been changed
      Set attributeSet = configUpdate.getAttributeSet();
      String next = null;
      for (Iterator iter = attributeSet.iterator(); iter.hasNext(); ) {
        next = (String) iter.next();
        if (next.equals(ServerTags.TIMEOUT_IN_SECONDS)) {
          _logger.log(Level.FINE, " Transaction Timeout interval event occurred");
          String oldTimeout = configUpdate.getOldValue(ServerTags.TIMEOUT_IN_SECONDS);
          String newTimeout = configUpdate.getNewValue(ServerTags.TIMEOUT_IN_SECONDS);
          if (oldTimeout.equals(newTimeout)) {
          } else {
            try {
              Switch.getSwitch()
                  .getTransactionManager()
                  .setDefaultTransactionTimeout(Integer.parseInt(newTimeout, 10));
            } catch (Exception ex) {
              _logger.log(Level.WARNING, "transaction.reconfig_txn_timeout_failed", ex);
            }
          } // timeout-in-seconds
        } else if (next.equals(ServerTags.KEYPOINT_INTERVAL)) {
          _logger.log(Level.FINE, "Keypoint interval event occurred");
          String oldKeyPoint = configUpdate.getOldValue(ServerTags.KEYPOINT_INTERVAL);
          String newKeyPoint = configUpdate.getNewValue(ServerTags.KEYPOINT_INTERVAL);
          if (oldKeyPoint.equals(newKeyPoint)) {
          } else {
            Configuration.setKeypointTrigger(Integer.parseInt(newKeyPoint, 10));
          }
        } else if (next.equals(ServerTags.RETRY_TIMEOUT_IN_SECONDS)) {
          String oldRetryTiemout = configUpdate.getOldValue(ServerTags.RETRY_TIMEOUT_IN_SECONDS);
          String newRetryTiemout = configUpdate.getNewValue(ServerTags.RETRY_TIMEOUT_IN_SECONDS);
          _logger.log(
              Level.FINE, "retry_timeout_in_seconds reconfig event occurred " + newRetryTiemout);
          if (oldRetryTiemout.equals(newRetryTiemout)) {
          } else {
            Configuration.setCommitRetryVar(newRetryTiemout);
          }
        } else {
          // Not handled dynamically. Restart is required.
          AdminEventMulticaster.notifyFailure(event, AdminEventResult.RESTART_NEEDED);
        }

        /*
        //This feature is currently dropped as it's not implemented totally
        else if (next.equals("commit-retries")) {
                          String oldCommitRetries = configUpdate.getOldValue("commit-retries");
                          String newCommitRetries = configUpdate.getNewValue("commit-retries");
                          if (oldCommitRetries.equals(newCommitRetries)) {
                          }
                          else {
                              Configuration.setCommitRetryVar(newCommitRetries);
                          }
                      } // commit-retries
                      */

      }
    }
  }
}
public class HttpServiceTest extends ServerXmlTest implements ServerCheck {

  // Logging
  static Logger _logger = LogDomains.getLogger(LogDomains.APPVERIFY_LOGGER);

  public HttpServiceTest() {}

  // check method called from command line verifier
  public Result check(ConfigContext context) {
    Result result;
    result = super.getInitializedResult();
    /*try {
        Server server = (Server)context.getRootConfigBean();
        HttpService http  = server.getHttpService();
        String qos = http.getQosMetricsIntervalInSeconds();
        String qosRecompute = http.getQosRecomputeTimeIntervalInMillis();
        try {
            // <addition> [email protected] Bug : 4698904
            if(qos!=null)
            // </addition>
                Long.parseLong(qos);
            result.passed("Http Service QOS Metric Interval in Seconds Valid " + qos);
        } catch(NumberFormatException e) {
            result.failed("Http Service QOS Metric Interval in Seconds invalid number - " + qos );
        }
        try {
           // <addition> [email protected] Bug : 4698904
           if(qosRecompute!=null)
           // </addition>
                Long.parseLong(qosRecompute);
           result.passed("Http Service QOS Recompute time interval in millis Valid ");
        } catch(NumberFormatException e) {
            result.failed("Http Service QOS Recompute time Interval in millis Invalid - " + qosRecompute );
        }
        Acl[] aclList = http.getAcl();
        for(int i=0;i<aclList.length;i++){
            String file = aclList[i].getFile();
            File f = new File(file);
            try {
                if(f.exists())
                    result.passed("Acl File Valid - " + file);
                else
                    result.failed("Acl File Invalid - " + file);
            }catch(SecurityException e){
                result.failed("Acl File Not able to access"+ file);
            }
        }
    }
    catch(Exception ex) {
        // Logging
        _logger.log(Level.FINE, "serverxmlverifier.exception", ex);
        result.failed("Exception : " + ex.getMessage());
    }*/
    return result;
  }

  // check method called from iasadmin and admin GUI
  public Result check(ConfigContextEvent ccce) {
    Result result;
    Object value = ccce.getObject();
    result = new Result();
    String beanName = ccce.getBeanName();
    result.passed("Passed***");
    if (beanName != null) {
      String name = ccce.getName();
      result = testSave(name, (String) value);
      return result;
    }
    /*
            HttpService http = (HttpService)value;
            String qos = http.getQosMetricsIntervalInSeconds();
            String qosRecompute = http.getQosRecomputeTimeIntervalInMillis();
            try {
                // <addition> [email protected] Bug : 4698904
                if(qos!=null)
                // </addition>
                    Long.parseLong(qos);
                result.passed("QOS Metric Interval Valid Number : Passed");
            } catch(NumberFormatException e) {
                result.failed("QOS Metric Interval Invalid Number " + qos);
            }
            try {
               // <addition> [email protected] Bug : 4698904
               if(qosRecompute!=null)
               // <addition>
                    Long.parseLong(qosRecompute);
               result.passed("QOS Recompute Interval Valid : Passed");
            } catch(NumberFormatException e) {
                result.failed(" QOS Recompute time Interval Invalid Number " + qosRecompute);
            }
            Acl[] aclList = http.getAcl();
            for(int i=0;i<aclList.length;i++){
                String file = aclList[i].getFile();
                File f = new File(file);
                try {
                    if(f.exists())
                        result.passed("Acl File Valid - " + file + ": Passed");
                    else
                        result.failed("Acl File Invalid - " + file + ": Failed");
                }catch(SecurityException e){
                    result.failed("Acl File Not able to access "+ file + ": Failed");
                }
            }
    */
    return result;
  }

  public Result testSave(String name, String value) {
    Result result = new Result();
    result.passed("passed ** ");
    /*
            if(name.equals(ServerTags.QOS_METRICS_INTERVAL_IN_SECONDS)) {
                try {
                    // <addition> [email protected] Bug : 4698904
                    if(value!=null)
                    // </addition>
                        Long.parseLong(value);
                    result.passed("QOS Metrics Interval Valid Number ");
                } catch(NumberFormatException e) {
                    result.failed("QOS Metrics Interval Invalid Number " + value);
                }
            }
            if(name.equals(ServerTags.QOS_RECOMPUTE_TIME_INTERVAL_IN_MILLIS)){
                try {
                    // <addition> [email protected] Bug : 4698904
                    if(value!=null)
                    // <addition>
                         Long.parseLong(value);
                    result.passed("QOS Recompute Time Interval Valid Number");
                } catch(NumberFormatException e){
                    result.failed("QOS Recompute Time Interval Invalid Number " + value);
                }
            }
    */
    return result;
  }
}
class RecoveryCoordinatorImpl extends RecoveryCoordinatorPOA {

  private static boolean recoverable = false;
  private static POA poa = null;
  private RecoveryCoordinator thisRef = null;
  private int internalSeq = 0;
  /*
  	Logger to log transaction messages
  */
  static Logger _logger = LogDomains.getLogger(LogDomains.TRANSACTION_LOGGER);
  GlobalTID globalTID = null;

  RecoveryCoordinatorImpl() {}

  /**
   * Sets up the RecoveryCoordinator with the global identifier.
   *
   * <p>This is so that it can always find the Coordinator to inform it of the requirement for
   * recovery of the given Resource.
   *
   * <p>An internal sequence number is used to differentiate RecoveryCoordinator objects used for
   * the same Coordinator object within a process. This is so that they each get a unique object
   * identifier.
   *
   * @param globalTID The global transaction identifier.
   * @param sequence An internal sequence number to differentiate objects.
   * @return
   * @see
   */
  RecoveryCoordinatorImpl(GlobalTID globalTID, int sequence) {

    this.globalTID = globalTID;
    internalSeq = sequence;

    // MODIFICATION (Ram Jeyaraman) comment out the code
    // below, as it does nothing.
    /*
    byte[] tidBytes = globalTID.toBytes();
    byte[] id = new byte[tidBytes.length + 4];
    System.arraycopy(tidBytes, 0, id, 4, tidBytes.length);
    id[0] = (byte) internalSeq;
    id[1] = (byte)(internalSeq >> 8);
    id[2] = (byte)(internalSeq >> 16);
    id[3] = (byte)(internalSeq >> 24);
    */
  }

  /**
   * Cleans up the state of the object.
   *
   * @param
   * @return
   * @see
   */
  /*
  public void finalize() {

      globalTID = null;
      internalSeq = 0;
  }
  */

  /**
   * Informs the Transaction Service that the given Resource object has been prepared but has not
   * received a commit or rollback operation.
   *
   * <p>If the transaction outcome is unknown, the Resource object passed on this operation will be
   * called at some later time for commit or rollback.
   *
   * @param res The Resource to be recovered.
   * @return The state of the transaction.
   * @exception NotPrepared The transaction for which the RecoveryCoordinator was created has not
   *     prepared.
   * @see
   */
  public Status replay_completion(Resource res) throws NotPrepared {

    if (_logger.isLoggable(Level.FINE)) {
      _logger.logp(
          Level.FINE,
          "RecoveryCoordinatorImpl",
          "replay_completion()",
          "replay_completion on Resource:" + res);
    }

    Status result = Status.StatusRolledBack;

    CoordinatorImpl coord = RecoveryManager.getCoordinator(globalTID);
    if (coord != null) {
      try {
        result = coord.get_status();
      } catch (SystemException exc) {
      }
    }

    switch (result.value()) {

        /*
         * If the transaction is still active, raise the NotPrepared
         * exception. The Coordinator must be marked rollback-only at
         * this point because we cannot allow the transaction to
         * complete if a participant has failed.
         */

      case Status._StatusActive:
      case Status._StatusMarkedRollback:
        try {
          coord.rollback_only();
        } catch (Throwable exc) {
        }

        throw new NotPrepared();

        /*
         * If the transaction is prepared, the caller must wait for the
         * Coordinator to tell it what to do, so return an unknown status, and
         * do nothing.  Note that if this Coordinator is sitting waiting for
         * its superior, this could take a int time.
         */

      case Status._StatusPrepared:
        result = Status.StatusUnknown;
        break;

        /*
         * If the transaction has been committed, the caller will receive
         * a commit.
         *
         * GDH If the transaction is commiting then we pass this on
         * to the caller. This state (added in OTS 1.1 means that
         * TopCoordinator.recover must now accept the COMMITTING state.
         */

      case Status._StatusCommitting:
        // MODIFICATION (Ram Jeyaraman) commented out the code below,
        // since a StatusCommitting will be upgraded to Committed in
        // the subordinate.
        /*
        // (Ram Jeyaraman) let the subordinate wait, and allow the root
        // finish driving the commit.
        result = Status.StatusUnknown;
        */
        break;

      case Status._StatusCommitted:
        break;

      case Status._StatusRolledBack:

        // If the transaction has been rolled back, and there is
        // no Coordinator for the transaction, we must invoke rollback
        // directly, as it will not be done otherwise.  However for
        // proxies, this rollback cannot be done from this thread as
        // it would cause deadlock in the server requesting resync.

        if (coord == null) {

          if (!Configuration.getProxyChecker().isProxy(res)) {
            rollbackOrphan(res);
          } else {

            // We must pass a duplicate of the proxy to the
            // rollback thread because this proxy will be destroyed
            // when the replay_completion request returns
            // to the remote server.

            try {
              OrphanRollbackThread rollbackThread =
                  new OrphanRollbackThread(this, (Resource) res._duplicate());
              rollbackThread.start();
            } catch (SystemException exc) {
            }
          }
        }

        break;

        /*
         * In any other situation, assume that the transaction has been rolled
         * back. As there is a Coordinator, it will direct the Resource to roll
         * back.
         */

      default:
        result = Status.StatusRolledBack;
    }

    return result;
  }

  // same as replay_completion(res) : added for delegated recovery support
  public Status replay_completion(Resource res, String logPath) throws NotPrepared {

    if (_logger.isLoggable(Level.FINE)) {
      _logger.logp(
          Level.FINE,
          "RecoveryCoordinatorImpl",
          "replay_completion()",
          "replay_completion on Resource:" + res);
    }

    Status result = Status.StatusRolledBack;

    CoordinatorImpl coord = DelegatedRecoveryManager.getCoordinator(globalTID, logPath);
    if (coord != null) {
      try {
        result = coord.get_status();
      } catch (SystemException exc) {
      }
    }

    switch (result.value()) {

        /*
         * If the transaction is still active, raise the NotPrepared
         * exception. The Coordinator must be marked rollback-only at
         * this point because we cannot allow the transaction to
         * complete if a participant has failed.
         */

      case Status._StatusActive:
      case Status._StatusMarkedRollback:
        try {
          coord.rollback_only();
        } catch (Throwable exc) {
        }

        throw new NotPrepared();

        /*
         * If the transaction is prepared, the caller must wait for the
         * Coordinator to tell it what to do, so return an unknown status, and
         * do nothing.  Note that if this Coordinator is sitting waiting for
         * its superior, this could take a int time.
         */

      case Status._StatusPrepared:
        result = Status.StatusUnknown;
        break;

        /*
         * If the transaction has been committed, the caller will receive
         * a commit.
         *
         * GDH If the transaction is commiting then we pass this on
         * to the caller. This state (added in OTS 1.1 means that
         * TopCoordinator.recover must now accept the COMMITTING state.
         */

      case Status._StatusCommitting:
        // MODIFICATION (Ram Jeyaraman) commented out the code below,
        // since a StatusCommitting will be upgraded to Committed in
        // the subordinate.
        /*
        // (Ram Jeyaraman) let the subordinate wait, and allow the root
        // finish driving the commit.
        result = Status.StatusUnknown;
        */
        break;

      case Status._StatusCommitted:
        break;

      case Status._StatusRolledBack:

        // If the transaction has been rolled back, and there is
        // no Coordinator for the transaction, we must invoke rollback
        // directly, as it will not be done otherwise.  However for
        // proxies, this rollback cannot be done from this thread as
        // it would cause deadlock in the server requesting resync.

        if (coord == null) {

          if (!Configuration.getProxyChecker().isProxy(res)) {
            rollbackOrphan(res);
          } else {

            // We must pass a duplicate of the proxy to the
            // rollback thread because this proxy will be destroyed
            // when the replay_completion request returns
            // to the remote server.

            try {
              OrphanRollbackThread rollbackThread =
                  new OrphanRollbackThread(this, (Resource) res._duplicate());
              rollbackThread.start();
            } catch (SystemException exc) {
            }
          }
        }

        break;

        /*
         * In any other situation, assume that the transaction has been rolled
         * back. As there is a Coordinator, it will direct the Resource to roll
         * back.
         */

      default:
        result = Status.StatusRolledBack;
    }

    return result;
  }

  /**
   * This method invoked rollback on the Resource that is passed as a parameter.
   *
   * <p>This procedure may be called as the main procedure of a new thread, which must be done for
   * remote Resource objects during resync to avoid the possibility of deadlock during resync.
   *
   * <p>It is called directly when the Resource is not a proxy.
   *
   * @param res The Resource to be rolled back.
   * @return
   * @see
   */
  void rollbackOrphan(Resource res) {

    try {
      res.rollback();
    } catch (Throwable exc) {

      // If the rollback raised a heuristic exception, it can
      // only be reported in a message as it will never reach
      // the Coordinator.

      if (exc instanceof HeuristicCommit
          || exc instanceof HeuristicMixed
          || exc instanceof HeuristicHazard) {
        _logger.log(Level.WARNING, "jts.heuristic_exception", exc.toString());
      } else {
      }
    }

    // We must release the proxy now.

    res._release();
  }

  /**
   * Creates the RecoveryCoordinatorImpl with the given key.
   *
   * <p>This is done when the RecoveryCoordinator object is recreated after the server has been
   * restarted.
   *
   * <p>The first four bytes of the key are an internal sequence number used to differentiate
   * RecoveryCoordinator objects created in the same process for the same transaction.
   *
   * <p>The rest of the key is the global transaction identifier.
   *
   * @param key The key for the object.
   * @return
   * @see
   */
  RecoveryCoordinatorImpl(byte[] key) {

    // Get the global transaction identifier from the key.

    byte[] tidBytes = new byte[key.length - 4];

    // BUGFIX (Ram Jeyaraman) changed the order of array copy.
    // previously, an source and destination array was wrong.
    // System.arraycopy(tidBytes, 0, key, 4, tidBytes.length);
    System.arraycopy(key, 4, tidBytes, 0, tidBytes.length);

    globalTID = new GlobalTID(tidBytes);

    // Ensure that recovery has completed so that
    // we can get the Coordinator.

    RecoveryManager.waitForRecovery();

    // Leave other members at the default values.
  }

  /**
   * Returns the CORBA Object which represents this object.
   *
   * @param
   * @return The CORBA object.
   * @see
   */
  final synchronized RecoveryCoordinator object() {

    if (thisRef == null) {
      if (poa == null) {
        poa = Configuration.getPOA("RecoveryCoordinator" /*#Frozen*/);
        recoverable = Configuration.isRecoverable();
      }

      try {

        if (recoverable && globalTID != null) {
          // Create the object id from the global transaction
          // identifier and the internal sequence number.

          byte[] tidBytes = globalTID.toBytes();
          byte[] id = new byte[tidBytes.length + 4];
          System.arraycopy(tidBytes, 0, id, 4, tidBytes.length);
          id[0] = (byte) internalSeq;
          id[1] = (byte) (internalSeq >> 8);
          id[2] = (byte) (internalSeq >> 16);
          id[3] = (byte) (internalSeq >> 24);

          // Activate the object and create the reference.

          poa.activate_object_with_id(id, this);

          org.omg.CORBA.Object obj =
              poa.create_reference_with_id(id, RecoveryCoordinatorHelper.id());
          thisRef = RecoveryCoordinatorHelper.narrow(obj);
          // thisRef = (RecoveryCoordinator) this;
        } else {
          poa.activate_object(this);
          org.omg.CORBA.Object obj = poa.servant_to_reference(this);
          thisRef = RecoveryCoordinatorHelper.narrow(obj);
          // thisRef = (RecoveryCoordinator)this;
        }
      } catch (Exception exc) {
        _logger.log(Level.SEVERE, "jts.create_recoverycoordinator_error");
        String msg =
            LogFormatter.getLocalizedMessage(_logger, "jts.create_recoverycoordinator_error");
        throw new org.omg.CORBA.INTERNAL(msg);
      }
    }

    return thisRef;
  }

  /**
   * Destroys the RecoveryCoordinatorImpl object.
   *
   * @param
   * @return
   * @see
   */
  final synchronized void destroy() {

    try {
      if (poa != null && thisRef != null) {
        poa.deactivate_object(poa.reference_to_id(thisRef));
        thisRef = null;
      } else {
        // BUGFIX(Ram J) It is possible that the
        // RecoveryCoordinator object was activated via the activation
        // daemon. In that case, there is no guarantee
        // that poa and thisRef are set to a meaningful value.
        // So, try to deactivate the RecoveryCoordinator object anyway.

        POA rcPoa = null;
        if (poa == null) {
          rcPoa = Configuration.getPOA("RecoveryCoordinator" /*#Frozen*/);
        } else {
          rcPoa = poa;
        }

        if (thisRef == null) {
          rcPoa.deactivate_object(rcPoa.servant_to_id(this));
        } else {
          rcPoa.deactivate_object(rcPoa.reference_to_id(thisRef));
          thisRef = null;
        }
      }
    } catch (Exception exc) {
      _logger.log(Level.WARNING, "jts.object_destroy_error", "RecoveryCoordinator");
    }

    // finalize();
    globalTID = null;
    internalSeq = 0;
  }
}
/**
 * This implementation runs a thread and does the following: a) Picks a task from the task queue b)
 * Removes one thread from the (thread)Pool. c) notifies the threadPoolThread.
 */
public class FastThreadPool {

  // Bug 4677074 begin
  static Logger _logger = LogDomains.getLogger(LogDomains.UTIL_LOGGER);
  // Bug 4677074 end
  protected boolean bDebug = false;
  private PoolProperties poolProps;
  private TaskQueue taskQueue;
  private int waitCount = 0;
  private int totalThreadCreatedCount = 0; // 4682740
  private int totalThreadDestroyedCount = 0; // 4682740
  private int numMessages = 0;

  public FastThreadPool(
      String threadGroupName,
      int minThreadCount,
      int maxThreadCount,
      long maxIdleTime,
      int queueLimit,
      TaskFactory factory) {
    this(
        new ThreadGroup(threadGroupName),
        minThreadCount,
        maxThreadCount,
        maxIdleTime,
        new TaskQueue(queueLimit, factory));
  }

  public FastThreadPool(
      ThreadGroup threadGroup,
      int minThreadCount,
      int maxThreadCount,
      long maxIdleTime,
      int queueLimit,
      TaskFactory factory) {
    this(
        threadGroup,
        minThreadCount,
        maxThreadCount,
        maxIdleTime,
        new TaskQueue(queueLimit, factory));
  }

  public FastThreadPool(
      ThreadGroup threadGroup,
      int minThreadCount,
      int maxThreadCount,
      long maxIdleTime,
      TaskQueue queue) {
    this.taskQueue = queue;

    poolProps =
        new PoolProperties(minThreadCount, maxThreadCount, maxIdleTime, taskQueue, threadGroup);
  }

  /**
   * Start the threadpool. Needed for scenarios where the queue gets created and set in the
   * threadpool from some other object.
   */
  public void start() {
    // We set createdCount to be the number of threads we are creating
    poolProps.createdCount = poolProps.minThreadCount;
    for (int i = 0; i < poolProps.minThreadCount; i++) {
      // if (bDebug) System.out.println("FastThreadPool creating thread: "
      //         + i + "/" + poolProps.minThreadCount);
      // Bug 4677074 begin
      // if (com.sun.enterprise.util.logging.Debug.enabled) _logger.log(Level.FINE,"FastThreadPool
      // creating thread: "+ i + "/" + poolProps.minThreadCount);
      // Bug 4677074 end
      new ThreadPoolThread(poolProps);
    }
    // START OF IASRI 4682740
    com.sun.enterprise.util.MonitorTask.addORBMonitorable(this);
    // END OF IASRI 4682740
  }

  /** returns the task queue */
  public TaskQueue getTaskQueue() {
    return taskQueue;
  }

  /** sets the task queue. Returns true if successful */
  public boolean setTaskQueue(TaskQueue bq) {
    if (taskQueue != null) return false;
    taskQueue = bq;
    return true;
  }

  /** Add to the head of the queue. Probably a high priority job? */
  public void addFirst(Servicable servicable) throws TooManyTasksException, QueueClosedException {
    taskQueue.addFirst(servicable);
  }

  /** Add to the tail of the queue. */
  public void addLast(Servicable servicable) throws TooManyTasksException, QueueClosedException {
    taskQueue.addLast(servicable);
  }

  /** Add the job at the specified position. Probably based on priority? */
  public void add(int index, Servicable servicable)
      throws TooManyTasksException, QueueClosedException {
    taskQueue.add(index, servicable);
  }

  public void shutdown() {
    taskQueue.shutdown();
  }

  public void abort() {
    taskQueue.abort();
  }

  public int getPoolSize() {
    return (poolProps != null) ? (poolProps.createdCount) : -1;
  }

  public int getWaitCount() {
    return waitCount;
  }

  public int[] getMonitoredValues() {
    synchronized (poolProps) {
      // Return the two integer values as an array.
      int[] ret = {(poolProps != null) ? (poolProps.createdCount) : -1, waitCount};
      return ret;
    }
  }

  // Start 4682740 - ORB to support standalone monitoring

  /** Great for monitoring. All methods used here are unsynchronized. */
  public String toString() {
    StringBuffer sb = new StringBuffer();
    sb.append("FastThreadPool [CS=").append(poolProps.createdCount);
    sb.append(", TC=").append(totalThreadCreatedCount);
    sb.append(", TD=").append(totalThreadDestroyedCount);
    sb.append(", Min=").append(poolProps.minThreadCount);
    sb.append(", Max=").append(poolProps.maxThreadCount);
    sb.append(", MaxIdle=").append(poolProps.maxIdleTime);
    sb.append(", Msgs=").append(numMessages);
    sb.append("]");
    return sb.toString();
  }

  // End 4682740 - ORB to support standalone monitoring

  private class PoolProperties {
    int minThreadCount;
    int maxThreadCount;
    long maxIdleTime;
    TaskQueue taskQueue;
    ThreadGroup threadGroup;

    int createdCount;

    PoolProperties(
        int minThreadCount,
        int maxThreadCount,
        long maxIdleTime,
        TaskQueue taskQueue,
        ThreadGroup threadGroup) {
      this.minThreadCount = minThreadCount;
      this.maxThreadCount = maxThreadCount;
      this.maxIdleTime = maxIdleTime;
      this.taskQueue = taskQueue;
      this.threadGroup = threadGroup;

      this.createdCount = 0;
    }
  }

  private class ThreadPoolThread implements Runnable {
    PoolProperties poolProps;

    ThreadPoolThread(PoolProperties poolProps) {
      this.poolProps = poolProps;
      Thread thread = new Thread(poolProps.threadGroup, this);
      if (poolProps.threadGroup != null) {
        if (poolProps.threadGroup.isDaemon()) {
          thread.setDaemon(true);
        }
      }
      thread.start();
      totalThreadCreatedCount++; // 4682740
    }

    public void run() {
      Servicable task = null;
      try {
        while (true) {
          boolean canCreateBuddy = false;

          do {
            synchronized (poolProps) {
              waitCount++;
            }

            task = null; // Bug 4700462 - Intermittent objects hang on to threads blocked on queue

            task = (Servicable) taskQueue.remove(poolProps.maxIdleTime);
            synchronized (poolProps) {
              waitCount--;
              if (task == null) {
                // We timedout!!
                if (poolProps.createdCount > poolProps.minThreadCount) {
                  // there are too many threads and the system is idle.
                  // if (bDebug) System.out.println(Thread.currentThread().getName()
                  //         + " Timedout. (quitting)....");
                  // Bug 4677074 begin
                  // if (com.sun.enterprise.util.logging.Debug.enabled)
                  // _logger.log(Level.FINE,Thread.currentThread().getName()+ " Timedout.
                  // (quitting)....");
                  // Bug 4677074 end
                  // DIE!!!!
                  poolProps.createdCount--;
                  totalThreadDestroyedCount++; // 4682740
                  return;
                }
                // We get to live a little longer!
                continue;
              }
              canCreateBuddy =
                  (waitCount == 0) && (poolProps.createdCount < poolProps.maxThreadCount);
              // Increment createdCount in anticipation of buddy creation
              if (canCreateBuddy) poolProps.createdCount++;
              numMessages++;
            }
            if (canCreateBuddy) {
              // if (bDebug) System.out.println(Thread.currentThread().getName()
              //         + " creating buddy...");
              // Bug 4677074 begin
              // if (com.sun.enterprise.util.logging.Debug.enabled)
              // _logger.log(Level.FINE,Thread.currentThread().getName()+ " creating buddy...");
              // Bug 4677074 end
              new ThreadPoolThread(poolProps);
            }

            // if (bDebug) System.out.println(Thread.currentThread().getName()
            //         + " got a task: " + task);
            // Bug 4677074 begin
            // if (com.sun.enterprise.util.logging.Debug.enabled)
            // _logger.log(Level.FINE,Thread.currentThread().getName() + " got a task: " + task);
            // Bug 4677074 end
            try {
              task.prolog();
              task.service();
              task.epilog();
            } catch (Throwable th) {
              // Bug 4677074                            th.printStackTrace();
              // Bug 4677074 begin
              _logger.log(Level.SEVERE, "iplanet_util.generic_exception", th);
              // Bug 4677074 end
            }
          } while (task != null);
        }
      } catch (com.sun.enterprise.util.collection.QueueClosedException qcEx) {
        // Bug 4677074                System.out.println("Queue closed. Exitting....");
        // Bug 4677074 begin
        _logger.log(Level.FINE, "Queue closed. Exitting....");
        // Bug 4677074 end
        synchronized (poolProps) {
          poolProps.createdCount--;
        }
        totalThreadDestroyedCount++; // 4682740
        return;
      } catch (InterruptedException inEx) {
        // Bug 4677074                System.out.println("Interrupted. Exitting....");
        // Bug 4677074 begin
        _logger.log(Level.SEVERE, "iplanet_util.generic_exception", inEx);
        // Bug 4677074 end
        synchronized (poolProps) {
          poolProps.createdCount--;
        }
        totalThreadDestroyedCount++; // 4682740
        return;
      }
    }
  }
}
/** @author mvatkina */
public class TransactionServiceProperties {

  private static Logger _logger =
      LogDomains.getLogger(TransactionServiceProperties.class, LogDomains.TRANSACTION_LOGGER);

  private static StringManager localStrings =
      StringManager.getManager(TransactionServiceProperties.class);

  private static final String JTS_XA_SERVER_NAME = "com.sun.jts.xa-servername";
  private static final String J2EE_SERVER_ID_PROP = "com.sun.enterprise.J2EEServerId";
  private static final String JTS_SERVER_ID = "com.sun.jts.persistentServerId";
  private static final String HABITAT = "HABITAT";
  private static final int DEFAULT_SERVER_ID = 100;

  private static Properties properties = null;
  private static volatile boolean orbAvailable = false;
  private static volatile boolean recoveryInitialized = false;

  public static synchronized Properties getJTSProperties(
      ServiceLocator serviceLocator, boolean isORBAvailable) {
    if (orbAvailable == isORBAvailable && properties != null) {
      // We will need to update the properties if ORB availability changed
      return properties;
    }

    Properties jtsProperties = new Properties();
    if (serviceLocator != null) {
      jtsProperties.put(HABITAT, serviceLocator);
      ProcessEnvironment processEnv = serviceLocator.getService(ProcessEnvironment.class);
      if (processEnv.getProcessType().isServer()) {
        TransactionService txnService =
            serviceLocator.getService(
                TransactionService.class, ServerEnvironment.DEFAULT_INSTANCE_NAME);

        if (txnService != null) {
          jtsProperties.put(Configuration.HEURISTIC_DIRECTION, txnService.getHeuristicDecision());
          jtsProperties.put(Configuration.KEYPOINT_COUNT, txnService.getKeypointInterval());

          String automaticRecovery = txnService.getAutomaticRecovery();
          boolean isAutomaticRecovery =
              (isValueSet(automaticRecovery) && "true".equals(automaticRecovery));
          if (isAutomaticRecovery) {
            _logger.log(Level.FINE, "Recoverable J2EE Server");
            jtsProperties.put(Configuration.MANUAL_RECOVERY, "true");
          }

          boolean disable_distributed_transaction_logging = false;
          String dbLoggingResource = null;
          for (Property prop : txnService.getProperty()) {
            String name = prop.getName();
            String value = prop.getValue();

            if (name.equals("disable-distributed-transaction-logging")) {
              if (isValueSet(value) && "true".equals(value)) {
                disable_distributed_transaction_logging = true;
              }

            } else if (name.equals("xaresource-txn-timeout")) {
              if (isValueSet(value)) {
                _logger.log(Level.FINE, "XAResource transaction timeout is" + value);
                TransactionManagerImpl.setXAResourceTimeOut(Integer.parseInt(value));
              }

            } else if (name.equals("db-logging-resource")) {
              dbLoggingResource = value;
              _logger.log(Level.FINE, "Transaction DB Logging Resource Name" + dbLoggingResource);
              if (dbLoggingResource != null
                  && (" ".equals(dbLoggingResource) || "".equals(dbLoggingResource))) {
                dbLoggingResource = "jdbc/TxnDS";
              }

            } else if (name.equals("xa-servername")) {
              if (isValueSet(value)) {
                jtsProperties.put(JTS_XA_SERVER_NAME, value);
              }

            } else if (name.equals("pending-txn-cleanup-interval")) {
              if (isValueSet(value)) {
                jtsProperties.put("pending-txn-cleanup-interval", value);
              }

            } else if (name.equals(Configuration.COMMIT_ONE_PHASE_DURING_RECOVERY)) {
              if (isValueSet(value)) {
                jtsProperties.put(Configuration.COMMIT_ONE_PHASE_DURING_RECOVERY, value);
              }
            } else if (name.equals("add-wait-point-during-recovery")) {
              if (isValueSet(value)) {
                try {
                  FailureInducer.setWaitPointRecovery(Integer.parseInt(value));
                } catch (Exception e) {
                  _logger.log(Level.WARNING, e.getMessage());
                }
              }
            }
          }

          if (dbLoggingResource != null) {
            disable_distributed_transaction_logging = true;
            jtsProperties.put(Configuration.DB_LOG_RESOURCE, dbLoggingResource);
          }

          /**
           * JTS_SERVER_ID needs to be unique for each for server instance. This will be used as
           * recovery identifier along with the hostname for example: if the hostname is 'tulsa' and
           * iiop-listener-port is 3700 recovery identifier will be tulsa,P3700
           */
          int jtsServerId = DEFAULT_SERVER_ID; // default value

          if (isORBAvailable) {
            jtsServerId =
                serviceLocator
                    .<GlassFishORBHelper>getService(GlassFishORBHelper.class)
                    .getORBInitialPort();
            if (jtsServerId == 0) {
              // XXX Can this ever happen?
              jtsServerId = DEFAULT_SERVER_ID; // default value
            }
          }
          jtsProperties.put(JTS_SERVER_ID, String.valueOf(jtsServerId));

          /* ServerId is an J2SE persistent server activation
            API.  ServerId is scoped at the ORBD.  Since
            There is no ORBD present in J2EE the value of
            ServerId is meaningless - except it must have
            SOME value if persistent POAs are created.
          */

          // For clusters - all servers in the cluster MUST
          // have the same ServerId so when failover happens
          // and requests are delivered to a new server, the
          // ServerId in the request will match the new server.

          String serverId = String.valueOf(DEFAULT_SERVER_ID);
          System.setProperty(J2EE_SERVER_ID_PROP, serverId);

          ServerContext ctx = serviceLocator.getService(ServerContext.class);
          String instanceName = ctx.getInstanceName();

          /**
           * if the auto recovery is true, always transaction logs will be written irrespective of
           * disable_distributed_transaction_logging. if the auto recovery is false, then
           * disable_distributed_transaction_logging will be used to write transaction logs are
           * not.If disable_distributed_transaction_logging is set to false(by default false) logs
           * will be written, set to true logs won't be written.
           */
          if (!isAutomaticRecovery && disable_distributed_transaction_logging) {
            Configuration.disableFileLogging();
          } else {

            // if (dbLoggingResource == null) {
            Domain domain = serviceLocator.getService(Domain.class);
            Server server = domain.getServerNamed(instanceName);

            // Check if the server system property is set
            String logdir = getTXLogDir(server);

            // if not, check if the cluster system property is set
            if (logdir == null) {
              Cluster cluster = server.getCluster();
              if (cluster != null) {
                logdir = getTXLogDir(cluster);
              }
            }

            // No system properties are set - get tx log dir from transaction service
            if (logdir == null) {
              logdir = txnService.getTxLogDir();
            }

            if (logdir == null) {
              logdir = domain.getLogRoot();
              if (logdir == null) {
                // logdir = FileUtil.getAbsolutePath(".." + File.separator + "logs");
                logdir = ".." + File.separator + "logs";
              }
            } else if (!(new File(logdir)).isAbsolute()) {
              if (_logger.isLoggable(Level.FINE)) {
                _logger.log(
                    Level.FINE,
                    "Relative pathname specified for transaction log directory : " + logdir);
              }
              String logroot = domain.getLogRoot();
              if (logroot != null) {
                logdir = logroot + File.separator + logdir;
              } else {
                // logdir = FileUtil.getAbsolutePath(".." + File.separator + "logs"
                // + File.separator + logdir);
                logdir = ".." + File.separator + "logs" + File.separator + logdir;
              }
            }
            logdir += File.separator + instanceName + File.separator + "tx";

            if (_logger.isLoggable(Level.FINE)) {
              _logger.log(Level.FINE, "JTS log directory: " + logdir);
              _logger.log(Level.FINE, "JTS Server id " + jtsServerId);
            }

            jtsProperties.put(Configuration.LOG_DIRECTORY, logdir);
          }
          jtsProperties.put(Configuration.COMMIT_RETRY, txnService.getRetryTimeoutInSeconds());
          jtsProperties.put(Configuration.INSTANCE_NAME, instanceName);
        }
      }
    }

    properties = jtsProperties;
    orbAvailable = isORBAvailable;

    return properties;
  }

  public static void initRecovery(boolean force) {
    if (_logger.isLoggable(Level.FINE)) {
      _logger.log(Level.FINE, "initRecovery:recoveryInitialized: " + recoveryInitialized);
    }

    if (recoveryInitialized) {
      // Only start initial recovery if it wasn't started before
      return;
    }

    if (_logger.isLoggable(Level.FINE)) {
      _logger.log(Level.FINE, "initRecovery:properties: " + properties);
    }
    if (properties == null) {
      if (force) {
        _logger.log(Level.WARNING, "", new IllegalStateException());
      }
      return;
    }

    // Start if force is true or automatic-recovery is set
    String value = properties.getProperty(Configuration.MANUAL_RECOVERY);
    if (_logger.isLoggable(Level.FINE)) {
      _logger.log(Level.FINE, "initRecovery:Configuration.MANUAL_RECOVERY: " + value);
    }
    if (force || (isValueSet(value) && "true".equals(value))) {
      recoveryInitialized = true;

      ServiceLocator serviceLocator = (ServiceLocator) properties.get(HABITAT);
      if (serviceLocator != null) {
        ProcessEnvironment processEnv = serviceLocator.getService(ProcessEnvironment.class);
        if (processEnv.getProcessType().isServer()) {
          // Start ResourceManager if it hadn't started yet
          serviceLocator.getAllServices(BuilderHelper.createNameFilter("ResourceManager"));
          value = properties.getProperty("pending-txn-cleanup-interval");
          int interval = -1;
          if (isValueSet(value)) {
            interval = Integer.parseInt(value);
          }
          new RecoveryHelperThread(serviceLocator, interval).start();
        }
        // Release all locks
        RecoveryManager.startResyncThread();
        if (_logger.isLoggable(Level.FINE)) _logger.log(Level.FINE, "[JTS] Started ResyncThread");
      }
    }
  }

  private static boolean isValueSet(String value) {
    return (value != null && !value.equals("") && !value.equals(" "));
  }

  private static String getTXLogDir(SystemPropertyBag bag) {
    for (SystemProperty prop : bag.getSystemProperty()) {
      String name = prop.getName();
      if (name.equals("TX-LOG-DIR")) {
        return prop.getValue();
      }
    }

    return null;
  }

  private static class RecoveryHelperThread extends Thread {
    private int interval;
    private ServiceLocator serviceLocator;

    RecoveryHelperThread(ServiceLocator serviceLocator, int interval) {
      setName("Recovery Helper Thread");
      setDaemon(true);
      this.serviceLocator = serviceLocator;
      this.interval = interval;
    }

    public void run() {
      ResourceRecoveryManager recoveryManager =
          serviceLocator.getService(ResourceRecoveryManager.class);
      if (interval <= 0) {
        // Only start the recovery thread if the interval value is set, and set to a positive value
        return;
      }

      if (_logger.isLoggable(Level.INFO)) {
        _logger.log(
            Level.INFO,
            "Asynchronous thread for incomplete " + "tx is enabled with interval " + interval);
      }
      int prevSize = 0;
      try {
        while (true) {
          Thread.sleep(interval * 1000L);
          if (!RecoveryManager.isIncompleteTxRecoveryRequired()) {
            if (_logger.isLoggable(Level.FINE))
              _logger.log(
                  Level.FINE,
                  "Incomplete transaction recovery is "
                      + "not requeired,  waiting for the next interval");
            continue;
          }
          if (RecoveryManager.sizeOfInCompleteTx() <= prevSize) {
            if (_logger.isLoggable(Level.FINE))
              _logger.log(
                  Level.FINE,
                  "Incomplete transaction recovery is "
                      + "not required,  waiting for the next interval SIZE");
            continue;
          }
          prevSize = RecoveryManager.sizeOfInCompleteTx();
          recoveryManager.recoverIncompleteTx(false, null);
        }
      } catch (Exception ex) {
        if (_logger.isLoggable(Level.FINE))
          _logger.log(Level.FINE, " Exception occurred in recoverInCompleteTx ");
      }
    }
  }
}
Exemple #18
0
 public void preDestroy() {
   LogDomains.getLogger(ServerEnvironmentImpl.class, LogDomains.ADMIN_LOGGER)
       .fine("SysLog Logger handler killed");
 }
/**
 * Implements the reload callbacks for standalone web modules.
 *
 * <p>When dynamic reloading is enabled, this object adds the list of enabled standalone web modules
 * to the reload monitor thread, so that web module reload via 'touch .reload' works.
 *
 * <p>This class lives in the com.sun.enterprise.server package and not the com.sun.enterprise.web
 * package because of the scope of the interface/methods in - ReloadMonitor, MonitorableEntry and
 * MonitorListener.
 */
public final class StandaloneWebModulesManager implements MonitorListener {

  ReloadMonitor reloadMonitor;

  // ------------------------------------------------------------ Constructor

  /**
   * Standard constructor.
   *
   * @param id The web container object identifier
   * @param modulesRoot The top level directory under which all standalone modules are deployed at.
   * @param pollInterval The interval at which dynamic reloading is performed
   */
  public StandaloneWebModulesManager(String id, String modulesRoot, long pollInterval) {
    _id = id;
    _modulesRoot = modulesRoot;
    start(pollInterval);
  }

  // ----------------------------------------------------- Instance Variables

  /**
   * The id of this object (this is the same as that of the id of the associated web container
   * object).
   */
  private String _id = null;

  /**
   * Absolute path for location where all the deployed standalone modules are stored for this Server
   * Instance.
   */
  private String _modulesRoot = null;

  /** List of web module ids registered with the reload monitor thread. */
  private ArrayList _reloadables = new ArrayList();

  // --------------------------------------------------------- Public Methods

  /**
   * Enable dynamic reloading (via the .reload file) for all the standalone web-modules that are
   * marked as enabled
   *
   * <p>This method is invoked be WebContainer.start() only when dynamic reloading has been enabled
   * in server.xml.
   */
  public void start(long pollInterval) {

    reloadMonitor = ReloadMonitor.getInstance(pollInterval * 1000);
  }

  /**
   * Remove the modules (that were previously registered by start()) from the reload monitor thread.
   *
   * <p>This method is invoked be WebContainer.stop() only when dynamic reloading has been enabled
   * in server.xml.
   */
  public void stop() {
    ReloadMonitor reloadMonitor = ReloadMonitor.getInstance(1);
    for (int i = 0; i < _reloadables.size(); i++) {
      String id = (String) _reloadables.get(i);
      reloadMonitor.removeMonitoredEntry(id);
    }
    _reloadables.clear();
    _reloadables = null;
  }

  // ------------------------------------------------ MonitorListener Methods

  /**
   * Callback from the reload monitor thread for a web module.
   *
   * <p>This is done when the user updates the $MODULE_ROOT/$MODULE/.reload file indicating the
   * server runtime for a dynamic reload.
   *
   * @param entry entry thats being monitored
   * @return true if application was reloaded successfully
   */
  public boolean reload(MonitorableEntry entry) {
    // The actual reload is done by the NSAPI reconfiguration logic which
    // the reload monitor thread invokes (at the end), so simply return
    // true here.

    InstanceEnvironment ienv = ApplicationServer.getServerContext().getInstanceEnvironment();

    // 4926513 work-around --- use displayname
    // for "foo", the id will be "foo[0]"
    // String moduleName = entry.getId();
    String moduleName = entry.getDisplayName();
    boolean status = false;

    try {
      DeploymentRequest req =
          new DeploymentRequest(ienv, DeployableObjectType.WEB, DeploymentCommand.DEPLOY);

      // monitored file points to $APP_ROOT/.reload
      req.setFileSource(entry.getMonitoredFile().getParentFile());

      // application registration name
      req.setName(moduleName);

      // we are always trying a redeployment
      req.setForced(true);

      AutoDirReDeployer deployer = new AutoDirReDeployer(req);
      status = deployer.redeploy();

    } catch (IASDeploymentException de) {
      _logger.log(Level.WARNING, "core.error_in_reload_war_module", de);
      return false;
    }
    return status;
  }

  /**
   * Callback from the auto deploy monitor when a new archive is detected.
   *
   * @param entry entry thats being monitored
   * @param archive newly detected archive under the auto deploy directory
   * @return true if archive was deployed successfully
   */
  public boolean deploy(MonitorableEntry entry, File archive) {
    // auto-deploy has not been implemented in S1AS7
    return false;
  }

  /**
   * Adds the given WebModule to the list of monitorable entries for dynamic reloading.
   *
   * @param wm The WebModule to add to the list of monitorable entries for dynamic reloading
   */
  public void addWebModule(WebModule wm) {
    if (wm != null && isEnabled(wm.getConfigContext(), wm.getName())) {
      String name = wm.getName();
      String id = name + "[" + _id + "]";
      String fileName = getReloadFilename(wm);
      MonitorableEntry entry = new MonitorableEntry(id, name, new File(fileName), this);
      _reloadables.add(id);
      reloadMonitor.addMonitorableEntry(entry);
    }
  }

  /**
   * Whether or not a component (either an application or a module) should be enabled is defined by
   * the "enable" attribute on both the application/module element and the application-ref element.
   *
   * @param config The dynamic ConfigContext
   * @param moduleName The name of the component
   * @return boolean
   */
  protected boolean isEnabled(ConfigContext config, String moduleName) {
    try {
      if (config == null) {
        config = AdminService.getAdminService().getAdminContext().getAdminConfigContext();
      }
      ConfigBean app = ApplicationHelper.findApplication(config, moduleName);
      Server server = ServerBeansFactory.getServerBean(config);
      ApplicationRef appRef = server.getApplicationRefByRef(moduleName);

      return ((app != null && app.isEnabled()) && (appRef != null && appRef.isEnabled()));
    } catch (ConfigException e) {
      _logger.log(Level.FINE, "Error in finding " + moduleName, e);

      // If there is anything wrong, do not enable the module
      return false;
    }
  }

  /**
   * Adds the given WebModule instances to the list of monitorable entries for dynamic reloading.
   *
   * @param modules The array of WebModule instances to add to the list of monitorable entries for
   *     dynamic reloading
   */
  public void addWebModules(WebModule[] modules) {
    if (modules != null && modules.length > 0) {
      for (int i = 0; i < modules.length; i++) {
        addWebModule(modules[i]);
      }
    }
  }

  /** Returns the absolute pathname to the .reload file in the specified web module's directory. */
  private String getReloadFilename(WebModule wm) {
    String path = wm.getLocation();
    File dir = new File(path);
    if (!dir.isAbsolute()) path = _modulesRoot + "/" + path;
    return path + "/" + ReloadMonitor.RELOAD_FILE;
  }

  /** logger to log core messages */
  static Logger _logger = LogDomains.getLogger(LogDomains.CORE_LOGGER);

  /** local string manager */
  private static StringManager localStrings =
      StringManager.getManager(StandAloneEJBModulesManager.class);
}