Пример #1
0
 /**
  * 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();
   }
 }
Пример #2
0
 private void handleRequest() throws IOException {
   String line = in.readLine();
   if (line == null || line.length() == 0) {
     Log.warn(Thread.currentThread().getName() + ": ignoring empty request.");
     return;
   }
   if (handleCommand(line, out) == false) {
     out.println(
         Thread.currentThread().getName() + ": didn't understand request \"" + line + "\".");
   }
 }
  /**
   * Closes given {@link #transportManagers} of this <tt>Conference</tt> and removes corresponding
   * channel bundle.
   */
  void closeTransportManager(TransportManager transportManager) {
    synchronized (transportManagers) {
      for (Iterator<IceUdpTransportManager> i = transportManagers.values().iterator();
          i.hasNext(); ) {
        if (i.next() == transportManager) {
          i.remove();
          // Presumably, we have a single association for
          // transportManager.
          break;
        }
      }

      // Close manager
      try {
        transportManager.close();
      } catch (Throwable t) {
        logger.warn(
            "Failed to close an IceUdpTransportManager of" + " conference " + getID() + "!", t);
        // The whole point of explicitly closing the
        // transportManagers of this Conference is to prevent memory
        // leaks. Hence, it does not make sense to possibly leave
        // TransportManagers open because a TransportManager has
        // failed to close.
        if (t instanceof InterruptedException) Thread.currentThread().interrupt();
        else if (t instanceof ThreadDeath) throw (ThreadDeath) t;
      }
    }
  }
Пример #4
0
 private void closeClientSocket() {
   try {
     client.close();
   } catch (IOException ex) {
     Log.warn(Thread.currentThread().getName() + ": failed to close client socket.", ex);
   }
 }
  /**
   * Returns the clone of <code>o_</code>. It calls <code>o_.clone()</code>, if possible, and either
   * raises an exception or returns null if fails.
   *
   * @param raiseException_ set to true if one wishes to get exception instead of receiving null
   *     when this method fails to call <code>o_.clone()</code>.
   */
  public static Object clone(Object o_, boolean raiseException_) {
    if (o_ == null) return null;
    if (o_ instanceof String) return o_;

    try {
      if (o_ instanceof drcl.ObjectCloneable) return ((drcl.ObjectCloneable) o_).clone();
      if (o_.getClass().isArray()) {
        int length_ = Array.getLength(o_);
        Class componentType_ = o_.getClass().getComponentType();
        Object that_ = Array.newInstance(componentType_, length_);
        if (componentType_.isPrimitive()) System.arraycopy(o_, 0, that_, 0, length_);
        else {
          for (int i = 0; i < length_; i++)
            Array.set(that_, i, clone(Array.get(o_, i), raiseException_));
        }
        return that_;
      }
      Method m_ = o_.getClass().getMethod("clone", null);
      return m_.invoke(o_, null);
    } catch (Exception e_) {
      if (raiseException_) {
        Thread t_ = Thread.currentThread();
        t_.getThreadGroup().uncaughtException(t_, e_);
      }
      return null;
    }
  }
Пример #6
0
  /** JNDI object factory so the proxy can be used as a resource. */
  public Object getObjectInstance(
      Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
    Reference ref = (Reference) obj;

    String api = null;
    String url = null;
    String user = null;
    String password = null;

    for (int i = 0; i < ref.size(); i++) {
      RefAddr addr = ref.get(i);

      String type = addr.getType();
      String value = (String) addr.getContent();

      if (type.equals("type")) api = value;
      else if (type.equals("url")) url = value;
      else if (type.equals("user")) setUser(value);
      else if (type.equals("password")) setPassword(value);
    }

    if (url == null) throw new NamingException("`url' must be configured for HessianProxyFactory.");
    // XXX: could use meta protocol to grab this
    if (api == null)
      throw new NamingException("`type' must be configured for HessianProxyFactory.");

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class apiClass = Class.forName(api, false, loader);

    return create(apiClass, url);
  }
Пример #7
0
 public void run() {
   if (Thread.currentThread() != this.mt)
     throw (new RuntimeException("MainFrame is being run from an invalid context"));
   Thread ui = new HackThread(p, "Haven UI thread");
   ui.start();
   try {
     try {
       Session sess = null;
       while (true) {
         UI.Runner fun;
         if (sess == null) {
           Bootstrap bill = new Bootstrap(Config.defserv, Config.mainport);
           if ((Config.authuser != null) && (Config.authck != null)) {
             bill.setinitcookie(Config.authuser, Config.authck);
             Config.authck = null;
           }
           fun = bill;
           setTitle(String.format("Amish Paradise %s", version));
         } else {
           fun = new RemoteUI(sess);
           setTitle(String.format("Amish Paradise %s \u2013 %s", version, sess.username));
         }
         sess = fun.run(p.newui(sess));
       }
     } catch (InterruptedException e) {
     }
     savewndstate();
   } finally {
     ui.interrupt();
     dispose();
   }
 }
Пример #8
0
 public ConnectionContext(Exception excp, String ip, String uri, Map<String, String[]> params) {
   this.exception = excp;
   this.params = params;
   this.thread = Thread.currentThread().getName();
   this.uri = uri;
   this.ip = ip;
 }
 /**
  * Builds a new AgentMBeanServerConnectionFactory and returns the underlying
  * MBeanServerConnection
  *
  * @return a new MBeanServerConnection
  */
 public MBeanServerConnection build() {
   final String key = buildKey();
   MBeanServerConnection conn = INSTANCES.get(key);
   if (conn == null) {
     synchronized (INSTANCES) {
       conn = INSTANCES.get(key);
       if (conn == null) {
         conn =
             (MBeanServerConnection)
                 Proxy.newProxyInstance(
                     Thread.currentThread().getContextClassLoader(),
                     new Class[] {MBeanServerConnection.class},
                     new AgentMBeanServerConnectionFactory(this));
         INSTANCES.put(key, conn);
         channel
             .getCloseFuture()
             .addListener(
                 new ChannelFutureListener() {
                   @Override
                   public void operationComplete(ChannelFuture future) throws Exception {
                     INSTANCES.remove(key);
                   }
                 });
       }
     }
   }
   return conn;
 }
 public static void resetThreadLocals() {
   try {
     Field field = Thread.class.getDeclaredField("threadLocals");
     field.setAccessible(true);
     field.set(Thread.currentThread(), null);
   } catch (Throwable e) {
     LOG.info(e);
   }
 }
Пример #11
0
 public static <T> T callWithJarClassLoader(File jarFile, Callable<T> action) throws Exception {
   Thread currentThread = Thread.currentThread();
   ClassLoader contextClassLoader = currentThread.getContextClassLoader();
   try {
     currentThread.setContextClassLoader(createJarClassLoader(jarFile));
     return action.call();
   } finally {
     currentThread.setContextClassLoader(contextClassLoader);
   }
 }
Пример #12
0
 public static void runWithJarClassLoader(File jarFile, Runnable action)
     throws MalformedURLException {
   Thread currentThread = Thread.currentThread();
   ClassLoader contextClassLoader = currentThread.getContextClassLoader();
   try {
     currentThread.setContextClassLoader(createJarClassLoader(jarFile));
     action.run();
   } finally {
     currentThread.setContextClassLoader(contextClassLoader);
   }
 }
Пример #13
0
 /** 关闭连接 */
 public static final void closeConnection() {
   Connection conn = conns.get();
   try {
     if (conn != null && !conn.isClosed()) {
       conn.setAutoCommit(true);
       conn.close();
       connectionContext.remove(Thread.currentThread().getId());
     }
   } catch (SQLException e) {
     log.error("Unabled to close connection!!! ", e);
   }
   conns.set(null);
 }
Пример #14
0
  /**
   * Creates a new proxy with the specified URL. The API class uses the java.api.class value from
   * _hessian_
   *
   * @param url the URL where the client object is located.
   * @return a proxy to the object with the specified interface.
   */
  public Object create(String url) throws MalformedURLException, ClassNotFoundException {
    HessianMetaInfoAPI metaInfo;

    metaInfo = (HessianMetaInfoAPI) create(HessianMetaInfoAPI.class, url);

    String apiClassName = (String) metaInfo._hessian_getAttribute("java.api.class");

    if (apiClassName == null) throw new HessianRuntimeException(url + " has an unknown api.");

    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    Class apiClass = Class.forName(apiClassName, false, loader);

    return create(apiClass, url);
  }
Пример #15
0
 private boolean authenticateClient() throws IOException {
   String line = in.readLine();
   if (line == null || line.equals(secret) == false) {
     Log.warn(
         Thread.currentThread().getName()
             + ": failed authentication attempt with \""
             + line
             + "\".");
     out.println("Authentication failed");
     return false;
   }
   writeNewSecret();
   out.println("Authentication OK");
   return true;
 }
Пример #16
0
 private void handleClient() {
   try {
     this.in = new BufferedReader(new InputStreamReader(client.getInputStream()));
     this.out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
     if (authenticateClient()) {
       handleRequest();
     }
     out.flush();
     out.close();
     in.close();
   } catch (Exception ex) {
     Log.warn(Thread.currentThread().getName() + ": failure handling client request.", ex);
   } finally {
     closeClientSocket();
   }
 }
  /**
   * Expires this <tt>Conference</tt>, its <tt>Content</tt>s and their respective <tt>Channel</tt>s.
   * Releases the resources acquired by this instance throughout its life time and prepares it to be
   * garbage collected.
   */
  public void expire() {
    synchronized (this) {
      if (expired) return;
      else expired = true;
    }

    EventAdmin eventAdmin = videobridge.getEventAdmin();
    if (eventAdmin != null) eventAdmin.sendEvent(EventFactory.conferenceExpired(this));

    setRecording(false);
    if (recorderEventHandler != null) {
      recorderEventHandler.close();
      recorderEventHandler = null;
    }

    Videobridge videobridge = getVideobridge();

    try {
      videobridge.expireConference(this);
    } finally {
      // Expire the Contents of this Conference.
      for (Content content : getContents()) {
        try {
          content.expire();
        } catch (Throwable t) {
          logger.warn(
              "Failed to expire content " + content.getName() + " of conference " + getID() + "!",
              t);
          if (t instanceof InterruptedException) Thread.currentThread().interrupt();
          else if (t instanceof ThreadDeath) throw (ThreadDeath) t;
        }
      }

      // Close the transportManagers of this Conference. Normally, there
      // will be no TransportManager left to close at this point because
      // all Channels have expired and the last Channel to be removed from
      // a TransportManager closes the TransportManager. However, a
      // Channel may have expired before it has learned of its
      // TransportManager and then the TransportManager will not close.
      closeTransportManagers();

      if (logger.isInfoEnabled()) {
        logger.info(
            "Expired conference " + getID() + ". " + videobridge.getConferenceCountString());
      }
    }
  }
Пример #18
0
    public Object createValue(UIDefaults table) {
      try {
        Class c = Class.forName(className, true, Thread.currentThread().getContextClassLoader());

        if (methodName == null) {
          return c.newInstance();
        }
        Method m = c.getMethod(methodName, (Class[]) null);

        return m.invoke(c, (Object[]) null);
      } catch (ClassNotFoundException cnfe) {
      } catch (IllegalAccessException iae) {
      } catch (InvocationTargetException ite) {
      } catch (NoSuchMethodException nsme) {
      } catch (InstantiationException ie) {
      }
      return null;
    }
Пример #19
0
  public void run() {
    while (Thread.currentThread() == thread) {
      try {
        Socket socket = server.accept();
        Client client = new Client(parent, socket);

        if (clientValidationMethod != null) {
          try {
            clientValidationMethod.invoke(parent, new Object[] {this, client});
          } catch (Exception e) {
            // System.err.println("Disabling serverEvent() for port " + port);
            e.printStackTrace();
          }
        }

        if (client.active()) {
          synchronized (clients) {
            addClient(client);
            if (serverEventMethod != null) {
              try {
                serverEventMethod.invoke(parent, new Object[] {this, client});
              } catch (Exception e) {
                // System.err.println("Disabling serverEvent() for port " + port);
                e.printStackTrace();
              }
            }
          }
        }
      } catch (SocketException e) {
        // thrown when server.close() is called and server is waiting on accept
        System.err.println("Server SocketException: " + e.getMessage());
        thread = null;
      } catch (IOException e) {
        // errorMessage("run", e);
        e.printStackTrace();
        thread = null;
      }
      try {
        Thread.sleep(8);
      } catch (InterruptedException ex) {
      }
    }
  }
Пример #20
0
  /** 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;
  }
Пример #21
0
  public static <T> T mixin(T target, Class<?>... interfaces) {
    if (target == null) return null;

    // When request is
    final Class<?> targetClass = target.getClass();
    if (Arrays.stream(interfaces).allMatch(i -> i.isAssignableFrom(targetClass))) {
      return target;
    }

    Class[] classes;
    int addedIndex;
    if (Proxy.isProxyClass(targetClass)) {
      MixinProxyHandler<T> handler = ((MixinProxyHandler<T>) Proxy.getInvocationHandler(target));
      target = handler.getOriginal();
      Class[] originalInterfaces = handler.getProxyInterfaces();
      classes = new Class[originalInterfaces.length + interfaces.length];
      System.arraycopy(originalInterfaces, 0, classes, 0, originalInterfaces.length);
      addedIndex = originalInterfaces.length;
    } else {
      Class[] targetInterfaces = getAllInterfaces(targetClass);
      classes = new Class[targetInterfaces.length + interfaces.length];
      System.arraycopy(targetInterfaces, 0, classes, 0, targetInterfaces.length);
      addedIndex = targetInterfaces.length;
    }
    Arrays.asList(interfaces)
        .forEach(
            i ->
                Arrays.asList(i.getMethods())
                    .stream()
                    .filter(Method::isDefault)
                    .forEach(MixinUtils::getMethodHandle));

    System.arraycopy(interfaces, 0, classes, addedIndex, interfaces.length);

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    return (T) Proxy.newProxyInstance(cl, classes, new MixinProxyHandler(target, classes));
  }
Пример #22
0
 private void initWebSocketService() {
   final NodeServer self = this;
   final ResourceFactory regFactory = application.getResourceFactory();
   resourceFactory.register(
       (ResourceFactory rf,
           final Object src,
           final String resourceName,
           Field field,
           Object attachment) -> { // 主要用于单点的服务
         try {
           if (field.getAnnotation(Resource.class) == null) return;
           if (!(src instanceof WebSocketServlet)) return;
           synchronized (regFactory) {
             Service nodeService = (Service) rf.find(resourceName, WebSocketNode.class);
             if (nodeService == null) {
               nodeService =
                   Sncp.createLocalService(
                       resourceName,
                       getExecutor(),
                       application.getResourceFactory(),
                       WebSocketNodeService.class,
                       (InetSocketAddress) null,
                       (Transport) null,
                       (Collection<Transport>) null);
               regFactory.register(resourceName, WebSocketNode.class, nodeService);
               resourceFactory.inject(nodeService, self);
               logger.fine(
                   "[" + Thread.currentThread().getName() + "] Load Service " + nodeService);
             }
             field.set(src, nodeService);
           }
         } catch (Exception e) {
           logger.log(Level.SEVERE, "WebSocketNode inject error", e);
         }
       },
       WebSocketNode.class);
 }
Пример #23
0
 public static ClassLoader getContextClassLoader() {
   ClassLoader result = Thread.currentThread().getContextClassLoader();
   if (result == null) result = BeanUtil.class.getClassLoader();
   return result;
 }
  /** Calculates a MD5 digest of the class. */
  public String getDigest() {
    try {
      if (_className == null || "".equals(_className)) return "";

      DynamicClassLoader loader =
          (DynamicClassLoader) Thread.currentThread().getContextClassLoader();

      ClassLoader tmpLoader = loader.getNewTempClassLoader();

      Class cl = Class.forName(_className, false, tmpLoader);

      if (cl == null) return "";

      MessageDigest digest = MessageDigest.getInstance("MD5");

      addDigest(digest, cl.getName());

      addDigest(digest, cl.getModifiers());

      Class superClass = cl.getSuperclass();
      if (superClass != null) addDigest(digest, superClass.getName());

      Class[] interfaces = cl.getInterfaces();
      for (int i = 0; i < interfaces.length; i++) addDigest(digest, interfaces[i].getName());

      Field[] fields = cl.getDeclaredFields();

      Arrays.sort(fields, new FieldComparator());

      if (_checkFields) {
        for (Field field : fields) {
          if (Modifier.isPrivate(field.getModifiers()) && !_checkPrivate) continue;
          if (Modifier.isProtected(field.getModifiers()) && !_checkProtected) continue;

          addDigest(digest, field.getName());
          addDigest(digest, field.getModifiers());
          addDigest(digest, field.getType().getName());

          addDigest(digest, field.getAnnotations());
        }
      }

      Method[] methods = cl.getDeclaredMethods();
      Arrays.sort(methods, new MethodComparator());

      for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];

        if (Modifier.isPrivate(method.getModifiers()) && !_checkPrivate) continue;
        if (Modifier.isProtected(method.getModifiers()) && !_checkProtected) continue;
        if (Modifier.isStatic(method.getModifiers()) && !_checkStatic) continue;

        addDigest(digest, method.getName());
        addDigest(digest, method.getModifiers());
        addDigest(digest, method.getName());

        Class[] param = method.getParameterTypes();
        for (int j = 0; j < param.length; j++) addDigest(digest, param[j].getName());

        addDigest(digest, method.getReturnType().getName());

        Class[] exn = method.getExceptionTypes();
        for (int j = 0; j < exn.length; j++) addDigest(digest, exn[j].getName());

        addDigest(digest, method.getAnnotations());
      }

      byte[] digestBytes = new byte[256];

      int len = digest.digest(digestBytes, 0, digestBytes.length);

      return digestToBase64(digestBytes, len);
    } catch (Exception e) {
      log.log(Level.FINER, e.toString(), e);

      return "";
    }
  }
Пример #25
0
 public static ClassLoader createJarClassLoader(File jarFile) throws MalformedURLException {
   ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
   if (jarFile != null)
     classLoader = new URLClassLoader(new URL[] {jarFile.toURI().toURL()}, classLoader);
   return classLoader;
 }
Пример #26
0
 /**
  * Creates a new proxy with the specified URL. The returned object is a proxy with the interface
  * specified by api.
  *
  * <pre>
  * String url = "http://localhost:8080/ejb/hello");
  * HelloHome hello = (HelloHome) factory.create(HelloHome.class, url);
  * </pre>
  *
  * @param api the interface the proxy class needs to implement
  * @param url the URL where the client object is located.
  * @return a proxy to the object with the specified interface.
  */
 public Object create(Class api, String urlName) throws MalformedURLException {
   return create(api, urlName, Thread.currentThread().getContextClassLoader());
 }
Пример #27
0
 protected void loadHttpServlet(final AnyValue conf, final ClassFilter<? extends Servlet> filter)
     throws Exception {
   final StringBuilder sb = logger.isLoggable(Level.INFO) ? new StringBuilder() : null;
   final String prefix = conf == null ? "" : conf.getValue("path", "");
   final String threadName = "[" + Thread.currentThread().getName() + "] ";
   List<FilterEntry<? extends Servlet>> list = new ArrayList(filter.getFilterEntrys());
   list.sort(
       (FilterEntry<? extends Servlet> o1,
           FilterEntry<? extends Servlet>
               o2) -> { // 必须保证WebSocketServlet优先加载, 因为要确保其他的HttpServlet可以注入本地模式的WebSocketNode
         boolean ws1 = WebSocketServlet.class.isAssignableFrom(o1.getType());
         boolean ws2 = WebSocketServlet.class.isAssignableFrom(o2.getType());
         if (ws1 == ws2) return o1.getType().getName().compareTo(o2.getType().getName());
         return ws1 ? -1 : 1;
       });
   final List<AbstractMap.SimpleEntry<String, String[]>> ss =
       sb == null ? null : new ArrayList<>();
   for (FilterEntry<? extends Servlet> en : list) {
     Class<HttpServlet> clazz = (Class<HttpServlet>) en.getType();
     if (Modifier.isAbstract(clazz.getModifiers())) continue;
     WebServlet ws = clazz.getAnnotation(WebServlet.class);
     if (ws == null || ws.value().length == 0) continue;
     final HttpServlet servlet = clazz.newInstance();
     resourceFactory.inject(servlet, this);
     final String[] mappings = ws.value();
     String pref = ws.repair() ? prefix : "";
     DefaultAnyValue servletConf = (DefaultAnyValue) en.getProperty();
     WebInitParam[] webparams = ws.initParams();
     if (webparams.length > 0) {
       if (servletConf == null) servletConf = new DefaultAnyValue();
       for (WebInitParam webparam : webparams) {
         servletConf.addValue(webparam.name(), webparam.value());
       }
     }
     this.httpServer.addHttpServlet(servlet, pref, servletConf, mappings);
     if (ss != null) {
       for (int i = 0; i < mappings.length; i++) {
         mappings[i] = pref + mappings[i];
       }
       ss.add(new AbstractMap.SimpleEntry<>(clazz.getName(), mappings));
     }
   }
   if (ss != null) {
     Collections.sort(
         ss,
         (AbstractMap.SimpleEntry<String, String[]> o1,
             AbstractMap.SimpleEntry<String, String[]> o2) -> o1.getKey().compareTo(o2.getKey()));
     int max = 0;
     for (AbstractMap.SimpleEntry<String, String[]> as : ss) {
       if (as.getKey().length() > max) max = as.getKey().length();
     }
     for (AbstractMap.SimpleEntry<String, String[]> as : ss) {
       sb.append(threadName).append(" Loaded ").append(as.getKey());
       for (int i = 0; i < max - as.getKey().length(); i++) {
         sb.append(' ');
       }
       sb.append("  mapping to  ").append(Arrays.toString(as.getValue())).append(LINE_SEPARATOR);
     }
   }
   if (sb != null && sb.length() > 0) logger.log(Level.INFO, sb.toString());
 }
Пример #28
0
 public Site() {
   this(Thread.currentThread().getStackTrace());
 }