コード例 #1
0
  /**
   * 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;
    }
  }
コード例 #2
0
ファイル: InAppServer.java プロジェクト: orph/jujitsu
  /**
   * 'handler' can be of any type that implements 'exportedInterface', but only methods declared by
   * the interface (and its superinterfaces) will be invocable.
   */
  public <T> InAppServer(
      String name,
      String portFilename,
      InetAddress inetAddress,
      Class<T> exportedInterface,
      T handler) {
    this.fullName = name + "Server";
    this.exportedInterface = exportedInterface;
    this.handler = handler;

    // In the absence of authentication, we shouldn't risk starting a server as root.
    if (System.getProperty("user.name").equals("root")) {
      Log.warn(
          "InAppServer: refusing to start unauthenticated server \"" + fullName + "\" as root!");
      return;
    }

    try {
      File portFile = FileUtilities.fileFromString(portFilename);
      secretFile = new File(portFile.getPath() + ".secret");
      Thread serverThread = new Thread(new ConnectionAccepter(portFile, inetAddress), fullName);
      // If there are no other threads left, the InApp server shouldn't keep us alive.
      serverThread.setDaemon(true);
      serverThread.start();
    } catch (Throwable th) {
      Log.warn("InAppServer: couldn't start \"" + fullName + "\".", th);
    }
    writeNewSecret();
  }
コード例 #3
0
ファイル: MainFrame.java プロジェクト: XaoZloHnH/hafen-client
 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();
   }
 }
コード例 #4
0
  public void run() throws IOException {
    ServerSocket server = new ServerSocket(this.portNumber);
    this.socket = server.accept();
    this.socket.setTcpNoDelay(true);
    server.close();

    DataInputStream in = new DataInputStream(this.socket.getInputStream());
    final DataOutputStream out = new DataOutputStream(this.socket.getOutputStream());
    while (true) {
      final String className = in.readUTF();
      Thread thread =
          new Thread() {
            public void run() {
              try {
                loadAndRun(className);
                out.writeBoolean(true);
                System.err.println(VerifyTests.class.getName());
                System.out.println(VerifyTests.class.getName());
              } catch (Throwable e) {
                e.printStackTrace();
                try {
                  System.err.println(VerifyTests.class.getName());
                  System.out.println(VerifyTests.class.getName());
                  out.writeBoolean(false);
                } catch (IOException e1) {
                  // ignore
                }
              }
            }
          };
      thread.start();
    }
  }
コード例 #5
0
ファイル: Utility.java プロジェクト: phan-pivotal/OSS
 /**
  * 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();
   }
 }
コード例 #6
0
    public void run() {
      try {
        if (myPreviousThread != null) myPreviousThread.join();
        Thread.sleep(delay);
        log("> run MouseMoveThread " + x + ", " + y);
        while (!hasFocus()) {
          Thread.sleep(1000);
        }
        int x1 = lastMouseX;
        int x2 = x;
        int y1 = lastMouseY;
        int y2 = y;
        // shrink range by 1 px on both ends
        // manually move this 1px to trip DND code
        if (x1 != x2) {
          int dx = x - lastMouseX;
          if (dx > 0) {
            x1 += 1;
            x2 -= 1;
          } else {
            x1 -= 1;
            x2 += 1;
          }
        }
        if (y1 != y2) {
          int dy = y - lastMouseY;
          if (dy > 0) {
            y1 += 1;
            y2 -= 1;
          } else {
            y1 -= 1;
            y2 += 1;
          }
        }
        robot.setAutoDelay(Math.max(duration / 100, 1));
        robot.mouseMove(x1, y1);
        int d = 100;
        for (int t = 0; t <= d; t++) {
          x1 =
              (int)
                  easeInOutQuad(
                      (double) t, (double) lastMouseX, (double) x2 - lastMouseX, (double) d);
          y1 =
              (int)
                  easeInOutQuad(
                      (double) t, (double) lastMouseY, (double) y2 - lastMouseY, (double) d);
          robot.mouseMove(x1, y1);
        }
        robot.mouseMove(x, y);
        lastMouseX = x;
        lastMouseY = y;
        robot.waitForIdle();
        robot.setAutoDelay(1);
      } catch (Exception e) {
        log("Bad parameters passed to mouseMove");
        e.printStackTrace();
      }

      log("< run MouseMoveThread");
    }
コード例 #7
0
  /**
   * Starts the print operation. This is quite expensive, and is kicked off in a separate thread.
   */
  public void print() {
    final PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintable(this);

    // make a local copy of the object to be printed, for use by the print thread
    // below...

    final Component printMe = getPrintComponent();

    Thread worker =
        new Thread() {
          public void run() {
            if (job.printDialog()) {
              try {
                // need to make sure that no other thread tries to
                // run a print job and set printCompnent at the same
                // time...
                synchronized (this) {
                  printComponent = printMe;
                  job.print();
                  printComponent = null;
                }
              } catch (Exception ex) {
                log.warning("error printing: " + ex);
              }
            }
          }
        };
    worker.start();
  }
コード例 #8
0
ファイル: HotPotatoes.java プロジェクト: nbronson/snaptree
  private static void testPotato(
      Class<? extends Collection> implClazz, Class<? extends List> argClazz) throws Throwable {
    try {
      System.out.printf("implClazz=%s, argClazz=%s\n", implClazz.getName(), argClazz.getName());
      final int iterations = 100000;
      final List<Integer> list = (List<Integer>) argClazz.newInstance();
      final Integer one = Integer.valueOf(1);
      final List<Integer> oneElementList = Collections.singletonList(one);
      final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class);
      final Thread t =
          new CheckedThread() {
            public void realRun() {
              for (int i = 0; i < iterations; i++) {
                list.add(one);
                list.remove(one);
              }
            }
          };
      t.setDaemon(true);
      t.start();

      for (int i = 0; i < iterations; i++) {
        Collection<?> coll = constr.newInstance(list);
        Object[] elts = coll.toArray();
        check(elts.length == 0 || (elts.length == 1 && elts[0] == one));
      }
    } catch (Throwable t) {
      unexpected(t);
    }
  }
コード例 #9
0
 public void _notified(double sec, final String chars) {
   if (!isSecure(sec)) return;
   // decouple from JavaScript; thread join could hang it
   Thread thread =
       new Thread("_notified") {
         public void run() {
           AccessController.doPrivileged(
               new PrivilegedAction() {
                 public Object run() {
                   try {
                     // wait for release shift/altgraph to resolve
                     if (previousThread != null) {
                       previousThread.join();
                     }
                   } catch (Exception e) {
                   }
                   keystring += chars;
                   if (altgraph && !shift) {
                     shift = false;
                     // Set robot auto delay now that FF/Mac inited all of the keys.
                     // Good for DND.
                     robot.setAutoDelay(1);
                     try {
                       log(keystring);
                       int index = 0;
                       for (int i = 0; (i < vkKeys.size()) && (index < keystring.length()); i++) {
                         char c = keystring.charAt(index++);
                         _mapKey(c, i, false, false);
                       }
                       for (int i = 0; (i < vkKeys.size()) && (index < keystring.length()); i++) {
                         char c = keystring.charAt(index++);
                         _mapKey(c, i, true, false);
                       }
                       for (int i = 0; (i < vkKeys.size()) && (index < keystring.length()); i++) {
                         char c = keystring.charAt(index++);
                         _mapKey(c, i, false, true);
                       }
                       // notify DOH that the applet finished init
                       dohrobot.call("_onKeyboard", new Object[] {});
                     } catch (Exception e) {
                       e.printStackTrace();
                     }
                     return null;
                   } else if (!shift) {
                     shift = true;
                   } else {
                     shift = false;
                     altgraph = true;
                   }
                   pressNext();
                   // }
                   return null;
                 }
               });
         }
       };
   thread.start();
 }
コード例 #10
0
ファイル: BeanUtil.java プロジェクト: gmeurant/benerator
 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);
   }
 }
コード例 #11
0
ファイル: BeanUtil.java プロジェクト: gmeurant/benerator
 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);
   }
 }
コード例 #12
0
ファイル: InAppServer.java プロジェクト: orph/jujitsu
 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 + "\".");
   }
 }
コード例 #13
0
 /** event driven processing methods */
 public void hPubStartPerformed(HPubStartEvent evt) {
   if (tracing == true) {
     traceArgs[0] = this;
     traceArgs[1] = "OffenceCountTextPostData_Access.hPubStartPerformed()";
     try {
       traceMethod.invoke(o, traceArgs);
     } catch (Exception x) {
     }
   }
   Thread newThread = new Thread(this);
   newThread.start();
 }
 /** event driven processing methods */
 public void hPubStartPerformed(HPubStartEvent evt) {
   if (tracing == true) {
     traceArgs[0] = this;
     traceArgs[1] = "EnforcementAgencyIndexSearch_Access.hPubStartPerformed()";
     try {
       traceMethod.invoke(o, traceArgs);
     } catch (Exception x) {
     }
   }
   Thread newThread = new Thread(this);
   newThread.start();
 }
 /** event driven processing methods */
 public void hPubStartPerformed(HPubStartEvent evt) {
   if (tracing == true) {
     traceArgs[0] = this;
     traceArgs[1] = "CaseCashReceiptsGetOffenderDetails_Access.hPubStartPerformed()";
     try {
       traceMethod.invoke(o, traceArgs);
     } catch (Exception x) {
     }
   }
   Thread newThread = new Thread(this);
   newThread.start();
 }
 /** event driven processing methods */
 public void hPubStartPerformed(HPubStartEvent evt) {
   if (tracing == true) {
     traceArgs[0] = this;
     traceArgs[1] = "WitnessInformationIndexClear_Access.hPubStartPerformed()";
     try {
       traceMethod.invoke(o, traceArgs);
     } catch (Exception x) {
     }
   }
   Thread newThread = new Thread(this);
   newThread.start();
 }
コード例 #17
0
 /** event driven processing methods */
 public void hPubStartPerformed(HPubStartEvent evt) {
   if (tracing == true) {
     traceArgs[0] = this;
     traceArgs[1] = "CrownCounselIndexGetList_Access.hPubStartPerformed()";
     try {
       traceMethod.invoke(o, traceArgs);
     } catch (Exception x) {
     }
   }
   Thread newThread = new Thread(this);
   newThread.start();
 }
コード例 #18
0
 void solve() {
   Thread tcThread = new Thread(tc);
   // System.out.println("starting client thread");
   tcThread.start();
   try {
     tcThread.join();
   } catch (Exception e) {
     e.printStackTrace();
   }
   // System.out.println("joined client thread");
   result = SudokuSolver.solve(tc.testcase);
   success = SudokuSolver.isLegalSolution(result, tc.testcase);
 }
コード例 #19
0
ファイル: DBManager.java プロジェクト: kone/kin
 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;
 }
コード例 #20
0
 public void run() {
   try {
     if (myPreviousThread != null) myPreviousThread.join();
     Thread.sleep(delay);
     log("> run MousePressThread");
     while (!hasFocus()) {
       Thread.sleep(1000);
     }
     robot.mousePress(mask);
     robot.waitForIdle();
   } catch (Exception e) {
     log("Bad parameters passed to mousePress");
     e.printStackTrace();
   }
   log("< run MousePressThread");
 }
コード例 #21
0
  /**
   * 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;
      }
    }
  }
コード例 #22
0
 public boolean checkEvents(BundleEvent[] expevents) {
   boolean res = true;
   for (int i = 0; i < 20; i++) {
     try {
       Thread.sleep(100);
     } catch (InterruptedException ignore) {
     }
     if (events.size() == expevents.length) {
       break;
     }
   }
   if (events.size() == expevents.length) {
     for (int i = 0; i < events.size(); i++) {
       BundleEvent be = (BundleEvent) events.elementAt(i);
       if (!(be.getBundle().equals(expevents[i].getBundle())
           && be.getType() == expevents[i].getType())) {
         res = false;
       }
     }
   } else {
     res = false;
   }
   if (!res) {
     out.println("Real events");
     for (int i = 0; i < events.size(); i++) {
       BundleEvent be = (BundleEvent) events.elementAt(i);
       out.println("Event " + be.getBundle() + ", Type " + be.getType());
     }
     out.println("Expected events");
     for (int i = 0; i < expevents.length; i++) {
       out.println("Event " + expevents[i].getBundle() + ", Type " + expevents[i].getType());
     }
   }
   return res;
 }
コード例 #23
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);
  }
コード例 #24
0
  @Test
  public void testWindowParenting02CreateVisibleDestroy3Odd() throws InterruptedException {
    int x = 0;
    int y = 0;

    NEWTEventFiFo eventFifo = new NEWTEventFiFo();

    GLWindow glWindow1 = GLWindow.create(glCaps);
    GLEventListener demo1 = new RedSquare();
    setDemoFields(demo1, glWindow1, false);
    glWindow1.addGLEventListener(demo1);

    NewtCanvasAWT newtCanvasAWT = new NewtCanvasAWT(glWindow1);

    Frame frame = new Frame("AWT Parent Frame");
    Assert.assertNotNull(frame);
    frame.setSize(width, height);

    // visible test
    frame.setVisible(true);

    frame.add(newtCanvasAWT);

    Animator animator1 = new Animator(glWindow1);
    animator1.start();
    while (animator1.isAnimating() && animator1.getDuration() < durationPerTest) {
      Thread.sleep(100);
    }

    Assert.assertEquals(true, animator1.isAnimating()); // !!!

    frame.dispose();
    glWindow1.destroy(true);
  }
コード例 #25
0
 /**
  * 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;
 }
コード例 #26
0
ファイル: InAppServer.java プロジェクト: orph/jujitsu
 private void closeClientSocket() {
   try {
     client.close();
   } catch (IOException ex) {
     Log.warn(Thread.currentThread().getName() + ": failed to close client socket.", ex);
   }
 }
コード例 #27
0
    public void run() {
      try {
        if (myPreviousThread != null) myPreviousThread.join();
        // in different order so async works
        while (!hasFocus()) {
          Thread.sleep(1000);
        }
        Thread.sleep(delay);
        log("> run KeyPressThread");

        _typeKey(charCode, keyCode, alt, ctrl, shift);
      } catch (Exception e) {
        log("Bad parameters passed to _typeKey");
        e.printStackTrace();
      }
      log("< run KeyPressThread");
    }
コード例 #28
0
  /**
   * This is called when JPM runs in the background to start jobs
   *
   * @throws Exception
   */
  public void daemon() throws Exception {
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread("Daemon shutdown") {
              public void run() {

                for (Service service : startedByDaemon) {
                  try {
                    reporter.error("Stopping " + service);
                    service.stop();
                    reporter.error("Stopped " + service);
                  } catch (Exception e) {
                    // Ignore
                  }
                }
              }
            });
    List<ServiceData> services = getServices();
    Map<String, ServiceData> map = new HashMap<String, ServiceData>();
    for (ServiceData d : services) {
      map.put(d.name, d);
    }
    List<ServiceData> start = new ArrayList<ServiceData>();
    Set<ServiceData> set = new HashSet<ServiceData>();
    for (ServiceData sd : services) {
      checkStartup(map, start, sd, set);
    }

    if (start.isEmpty()) reporter.warning("No services to start");

    for (ServiceData sd : start) {
      try {
        Service service = getService(sd.name);
        reporter.trace("Starting " + service);
        String result = service.start();
        if (result != null) reporter.error("Started error " + result);
        else startedByDaemon.add(service);
        reporter.trace("Started " + service);
      } catch (Exception e) {
        reporter.error("Cannot start daemon %s, due to %s", sd.name, e);
      }
    }

    while (true) {
      for (Service sd : startedByDaemon) {
        try {
          if (!sd.isRunning()) {
            reporter.error("Starting due to failure " + sd);
            String result = sd.start();
            if (result != null) reporter.error("Started error " + result);
          }
        } catch (Exception e) {
          reporter.error("Cannot start daemon %s, due to %s", sd, e);
        }
      }
      Thread.sleep(10000);
    }
  }
コード例 #29
0
 public void _callLoaded(double sec) {
   log("> _callLoaded Robot");
   if (!isSecure(sec)) {
     return;
   }
   Thread thread =
       new Thread() {
         public void run() {
           AccessController.doPrivileged(
               new PrivilegedAction() {
                 public Object run() {
                   Point p = getLocationOnScreen();
                   log("Document root: ~" + p.toString());
                   int x = p.x + 16;
                   int y = p.y + 8;
                   // click the mouse over the text box
                   try {
                     Thread.sleep(100);
                   } catch (Exception e) {
                   }
                   ;
                   robot.mouseMove(x, y);
                   try {
                     Thread.sleep(100);
                   } catch (Exception e) {
                   }
                   ;
                   robot.mousePress(InputEvent.BUTTON1_MASK);
                   try {
                     Thread.sleep(100);
                   } catch (Exception e) {
                   }
                   robot.mouseRelease(InputEvent.BUTTON1_MASK);
                   try {
                     Thread.sleep(100);
                   } catch (Exception e) {
                   }
                   log("< _callLoaded Robot");
                   return null;
                 }
               });
         }
       };
   thread.start();
 }
コード例 #30
0
 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);
   }
 }