Esempio n. 1
0
 /** Redirect a VMs output and error streams to System.out and System.err */
 protected void redirectStreams(VirtualMachine vm) {
   MessageSiphon ms = new MessageSiphon(process.getErrorStream(), this);
   errThread = ms.getThread();
   outThread = new StreamRedirectThread("VM output reader", process.getInputStream(), System.out);
   errThread.start();
   outThread.start();
 }
Esempio n. 2
0
 public void start() {
   if (streamReader != null && streamReader.isAlive()) {
     System.out.println("Camera already started");
     return;
   }
   streamReader = new Thread(this, "HTTP Stream reader");
   keepAlive = true;
   streamReader.start();
 }
Esempio n. 3
0
 public void stop() {
   if (streamReader == null || !streamReader.isAlive()) {
     System.out.println("Camera already stopped");
     return;
   }
   keepAlive = false;
   try {
     streamReader.join();
   } catch (InterruptedException e) {
     System.err.println(e.getMessage());
   }
 }
Esempio n. 4
0
  /**
   * Gives the same basic functionality of File.exists but can be used to look for removable media
   * without showing a system dialog if the media is not present. Workaround pulled from the <A
   * HREF="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4089199"> bug report</A> on
   * bugs.sun.com. This bug was fixed in Java 6, and we can remove the workaround when we start
   * requiring Java 6.
   */
  protected static boolean fileExists(File file) {
    try {
      Process process =
          Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", "dir", file.getAbsolutePath()});

      // We need to consume all available output or the process will block.
      boolean haveExitCode = false;
      int exitCode = -1;
      InputStream out = process.getInputStream();
      InputStream err = process.getErrorStream();

      while (!haveExitCode) {
        while (out.read() >= 0) {}
        while (err.read() >= 0) {}

        try {
          exitCode = process.exitValue();
          haveExitCode = true;
        } catch (IllegalThreadStateException e) {
          // Not yet complete.
          Thread.sleep(100);
        }
      }
      // int exitCode = process.waitFor();
      return exitCode == 0;

    } catch (IOException e) {
      System.out.println("Unable to check for file: " + file + " : " + e);
      return false;

    } catch (InterruptedException e) {
      System.out.println("Unable to check for file.  Interrupted: " + file + " : " + e);
      return false;
    }
  }
Esempio n. 5
0
  public Gif(PApplet parent, String filename) {
    // this creates a fake image so that the first time this
    // attempts to draw, something happens that's not an exception
    super(1, 1, ARGB);

    this.parent = parent;

    // create the GifDecoder
    GifDecoder gifDecoder = createDecoder(parent, filename);

    // fill up the PImage and the delay arrays
    frames = extractFrames(gifDecoder);
    delays = extractDelays(gifDecoder);

    // get the GIFs repeat count
    repeatSetting = gifDecoder.getLoopCount();

    // re-init our PImage with the new size
    super.init(frames[0].width, frames[0].height, ARGB);
    jump(0);
    parent.registerMethod("dispose", this);

    // and now, make the magic happen
    runner = new Thread(this);
    runner.start();
  }
Esempio n. 6
0
 public void sleep() {
   try {
     //// release some cpu cycles for the background network thread
     Thread.sleep(100);
   } catch (Exception e) {
   }
 }
Esempio n. 7
0
 public boolean delay(int time) {
   try {
     Thread.sleep(time);
   } catch (Exception e) {
     return false;
   }
   return true;
 }
Esempio n. 8
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) {
      }
    }
  }
Esempio n. 9
0
  /*
   * the thread's run method
   */
  public void run() {
    while (Thread.currentThread() == runner) {
      try {
        Thread.sleep(5);
      } catch (InterruptedException e) {
      }

      if (play) {
        // if playing, check if we need to go to next frame

        if (parent.millis() - lastJumpTime >= delays[currentFrame]) {
          // we need to jump

          if (currentFrame == frames.length - 1) {
            // its the last frame
            if (loop) {
              jump(0); // loop is on, so rewind
            } else if (!ignoreRepeatSetting) {
              // we're not looping, but we need to respect the
              // GIF's repeat setting
              repeatCount++;
              if (repeatSetting == 0) {
                // we need to repeat forever
                jump(0);
              } else if (repeatCount == repeatSetting) {
                // stop repeating, we've reached the repeat
                // setting
                stop();
              }
            } else {
              // no loop & ignoring the repeat setting, so just
              // stop.
              stop();
            }
          } else {
            // go to the next frame
            jump(currentFrame + 1);
          }
        }
      }
    }
  }
  public void setup() {

    size(800, 600);

    background(255);
    color(255);
    size(800, 600);
    frameRate(24);
    smooth();
    pollData.start();
  }
            @Override
            public void run() {
              while (true) {
                // TODO Auto-generated method stub
                // print("start");

                if (serial != null) buffer.add(device.parse(serial.input));
                try {
                  Thread.sleep(1);
                } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
              }
            }
Esempio n. 12
0
  /**
   * @param parent typically use "this"
   * @param port port used to transfer data
   * @param host when multiple NICs are in use, the ip (or name) to bind from
   */
  public MyServer(PApplet parent, int port, String host) {
    this.parent = parent;
    this.port = port;

    try {
      if (host == null) {
        server = new ServerSocket(this.port);
      } else {
        server = new ServerSocket(this.port, 10, InetAddress.getByName(host));
      }
      // clients = new Vector();
      clients = new Client[10];

      thread = new Thread(this);
      thread.start();

      parent.registerMethod("dispose", this);

      // reflection to check whether host applet has a call for
      // public void serverEvent(MyServer s, Client c);
      // which is called when a new guy connects
      try {
        serverEventMethod =
            parent.getClass().getMethod("serverEvent", new Class[] {MyServer.class, Client.class});
      } catch (Exception e) {
        // no such method, or an error.. which is fine, just ignore
        serverEventMethod = null;
      }

      try {
        clientValidationMethod =
            parent
                .getClass()
                .getMethod("clientValidation", new Class[] {MyServer.class, Client.class});
      } catch (Exception e) {
        // no such method, or an error.. which is fine, just ignore
        clientValidationMethod = null;
      }

    } catch (IOException e) {
      // e.printStackTrace();
      thread = null;
      throw new RuntimeException(e);
      // errorMessage("<init>", e);
    }
  }
Esempio n. 13
0
  private void startManualUpdate() {
    dOut = new DataOut(pApplet, pachubePOSTurl, pachubeAuthenticationKey);

    running = true;
    try {
      postThread = new Thread(this);
      postThread.start();
      System.out.println(
          "Pachuino POST enabled, to: "
              + pachubePOSTurl
              + ", updating every "
              + POST_RATE
              + " milliseconds");
      System.out.println("Using API key: " + pachubeAuthenticationKey);
    } catch (Exception e) {
      System.out.println("There was a problem starting a POST thread.");
    }
  }
Esempio n. 14
0
  /**
   * Generate the trace. Enable events, start thread to display events, start threads to forward
   * remote error and output streams, resume the remote VM, wait for the final event, and shutdown.
   */
  protected void generateTrace() {
    // vm.setDebugTraceMode(debugTraceMode);
    //    vm.setDebugTraceMode(VirtualMachine.TRACE_ALL);
    //    vm.setDebugTraceMode(VirtualMachine.TRACE_NONE);  // formerly, seems to have no effect

    // For internal debugging
    PrintWriter writer = null;

    // Calling this seems to set something internally to make the
    // Eclipse JDI wake up. Without it, an ObjectCollectedException
    // is thrown on excReq.enable(). No idea why this works,
    // but at least exception handling has returned. (Suspect that it may
    // block until all or at least some threads are available, meaning
    // that the app has launched and we have legit objects to talk to).
    vm.allThreads();
    // The bug may not have been noticed because the test suite waits for
    // a thread to be available, and queries it by calling allThreads().
    // See org.eclipse.debug.jdi.tests.AbstractJDITest for the example.

    EventRequestManager mgr = vm.eventRequestManager();
    // get only the uncaught exceptions
    ExceptionRequest excReq = mgr.createExceptionRequest(null, false, true);
    //    System.out.println(excReq);
    // this version reports all exceptions, caught or uncaught
    //  ExceptionRequest excReq = mgr.createExceptionRequest(null, true, true);
    // suspend so we can step
    excReq.setSuspendPolicy(EventRequest.SUSPEND_ALL);
    //    excReq.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD);
    //    excReq.setSuspendPolicy(EventRequest.SUSPEND_NONE);  // another option?
    excReq.enable();

    Thread eventThread =
        new Thread() {
          public void run() {
            try {
              boolean connected = true;
              while (connected) {
                EventQueue eventQueue = vm.eventQueue();
                // remove() blocks until event(s) available
                EventSet eventSet = eventQueue.remove();
                //            listener.vmEvent(eventSet);

                for (Event event : eventSet) {
                  //              System.out.println("EventThread.handleEvent -> " + event);
                  if (event instanceof VMStartEvent) {
                    vm.resume();
                  } else if (event instanceof ExceptionEvent) {
                    //                for (ThreadReference thread : vm.allThreads()) {
                    //                  System.out.println("thread : " + thread);
                    ////                  thread.suspend();
                    //                }
                    exceptionEvent((ExceptionEvent) event);
                  } else if (event instanceof VMDisconnectEvent) {
                    connected = false;
                  }
                }
              }
              //        } catch (VMDisconnectedException e) {
              //          Logger.getLogger(VMEventReader.class.getName()).log(Level.INFO,
              // "VMEventReader quit on VM disconnect");
            } catch (Exception e) {
              System.err.println("crashed in event thread due to " + e.getMessage());
              //          Logger.getLogger(VMEventReader.class.getName()).log(Level.SEVERE,
              // "VMEventReader quit", e);
              e.printStackTrace();
            }
          }
        };
    eventThread.start();

    errThread = new MessageSiphon(process.getErrorStream(), this).getThread();

    outThread = new StreamRedirectThread("JVM stdout Reader", process.getInputStream(), System.out);
    errThread.start();
    outThread.start();

    // Shutdown begins when event thread terminates
    try {
      if (eventThread != null) eventThread.join(); // is this the problem?

      //      System.out.println("in here");
      // Bug #852 tracked to this next line in the code.
      // http://dev.processing.org/bugs/show_bug.cgi?id=852
      errThread.join(); // Make sure output is forwarded
      //      System.out.println("and then");
      outThread.join(); // before we exit
      //      System.out.println("finished join for errThread and outThread");

      // At this point, disable the run button.
      // This happens when the sketch is exited by hitting ESC,
      // or the user manually closes the sketch window.
      // TODO this should be handled better, should it not?
      if (editor != null) {
        editor.deactivateRun();
      }
    } catch (InterruptedException exc) {
      // we don't interrupt
    }
    // System.out.println("and leaving");
    if (writer != null) writer.close();
  }
Esempio n. 15
0
  public boolean launchVirtualMachine(boolean presenting) {
    String[] vmParams = getMachineParams();
    String[] sketchParams = getSketchParams(presenting);
    int port = 8000 + (int) (Math.random() * 1000);
    String portStr = String.valueOf(port);

    // Older (Java 1.5 and earlier) version, go figure
    //    String jdwpArg = "-Xrunjdwp:transport=dt_socket,address=" + portStr +
    // ",server=y,suspend=y";
    //    String debugArg = "-Xdebug";
    // Newer (Java 1.5+) version that uses JVMTI
    String jdwpArg =
        "-agentlib:jdwp=transport=dt_socket,address=" + portStr + ",server=y,suspend=y";

    // Everyone works the same under Java 7 (also on OS X)
    String[] commandArgs = new String[] {Base.getJavaPath(), jdwpArg};

    /*
        String[] commandArgs = null;
        if (!Base.isMacOS()) {
          commandArgs = new String[] {
            Base.getJavaPath(),
            jdwpArg
          };
        } else {
          // Decided to just set this to 1.6 only, because otherwise it's gonna
          // be a shitshow if folks are getting Apple's 1.6 with 32-bit and
          // Oracle's 1.7 when run in 64-bit mode. ("Why does my sketch suck in
          // 64-bit? Why is retina broken?)
          // The --request flag will prompt to install Apple's 1.6 JVM if none is
          // available. We're specifying 1.6 so that we can get support for both
          // 32- and 64-bit, because Oracle won't be releasing Java 1.7 in 32-bit.
          // Helpfully, the --request flag is not present on Mac OS X 10.6
          // (luckily it is also not needed, because 1.6 is installed by default)
          // but it requires an additional workaround to not use that flag,
          // otherwise will see an error about an unsupported option. The flag is
          // available with 10.7 and 10.8, the only other supported versions of
          // OS X at this point, because we require 10.6.8 and higher. That also
          // means we don't need to check for any other OS versions, the user is
          // a douchebag and modifies Info.plist to get around the restriction.
          if (false) {
            if (System.getProperty("os.version").startsWith("10.6")) {
              commandArgs = new String[] {
                "/usr/libexec/java_home",
                "--version", "1.6",
                "--exec", "java",
                "-d" + Base.getNativeBits(),
                jdwpArg
              };
            } else {  // for 10.7, 10.8, etc
              commandArgs = new String[] {
                "/usr/libexec/java_home",
                "--request",  // install on-demand
                "--version", "1.6",
                "--exec", "java",
                "-d" + Base.getNativeBits(),
    //          debugArg,
                jdwpArg
              };
            }
          } else {
            // testing jdk-7u40
            commandArgs = new String[] {
              //"/Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home/bin/java",
              Base.getJavaPath(),
              jdwpArg
            };
          }
        }
        */

    commandArgs = PApplet.concat(commandArgs, vmParams);
    commandArgs = PApplet.concat(commandArgs, sketchParams);
    //  PApplet.println(commandArgs);
    //  commandArg.setValue(commandArgs);
    launchJava(commandArgs);

    AttachingConnector connector = (AttachingConnector) findConnector("com.sun.jdi.SocketAttach");
    // PApplet.println(connector);  // gets the defaults

    Map arguments = connector.defaultArguments();

    //  Connector.Argument addressArg =
    //    (Connector.Argument)arguments.get("address");
    //  addressArg.setValue(addr);
    Connector.Argument portArg = (Connector.Argument) arguments.get("port");
    portArg.setValue(portStr);

    //    Connector.Argument timeoutArg =
    //      (Connector.Argument)arguments.get("timeout");
    //    timeoutArg.setValue("10000");

    // PApplet.println(connector);  // prints the current
    // com.sun.tools.jdi.AbstractLauncher al;
    // com.sun.tools.jdi.RawCommandLineLauncher rcll;

    // System.out.println(PApplet.javaVersion);
    // http://java.sun.com/j2se/1.5.0/docs/guide/jpda/conninv.html#sunlaunch

    try {
      //      boolean available = false;
      //      while (!available) {
      while (true) {
        try {
          vm = connector.attach(arguments);
          //          vm = connector.attach(arguments);
          if (vm != null) {
            //            generateTrace();
            //            available = true;
            return true;
          }
        } catch (IOException e) {
          //          System.out.println("waiting");
          //          e.printStackTrace();
          try {
            Thread.sleep(100);
          } catch (InterruptedException e1) {
            e1.printStackTrace();
          }
        }
      }
      //    } catch (IOException exc) {
      //      throw new Error("Unable to launch target VM: " + exc);
    } catch (IllegalConnectorArgumentsException exc) {
      throw new Error("Internal error: " + exc);
    }
  }
Esempio n. 16
0
 // Overriding "start()"
 public void start() {
   running = true;
   super.start();
 }
Esempio n. 17
0
  public boolean launchVirtualMachine(boolean presenting) {
    String[] vmParams = getMachineParams();
    String[] sketchParams = getSketchParams(presenting);
    //    PApplet.printArray(sketchParams);
    int port = 8000 + (int) (Math.random() * 1000);
    String portStr = String.valueOf(port);

    // Older (Java 1.5 and earlier) version, go figure
    //    String jdwpArg = "-Xrunjdwp:transport=dt_socket,address=" + portStr +
    // ",server=y,suspend=y";
    //    String debugArg = "-Xdebug";
    // Newer (Java 1.5+) version that uses JVMTI
    String jdwpArg =
        "-agentlib:jdwp=transport=dt_socket,address=" + portStr + ",server=y,suspend=y";

    // Everyone works the same under Java 7 (also on OS X)
    String[] commandArgs = new String[] {Base.getJavaPath(), jdwpArg};

    commandArgs = PApplet.concat(commandArgs, vmParams);
    commandArgs = PApplet.concat(commandArgs, sketchParams);
    //  PApplet.println(commandArgs);
    //  commandArg.setValue(commandArgs);
    launchJava(commandArgs);

    AttachingConnector connector = (AttachingConnector) findConnector("com.sun.jdi.SocketAttach");
    // PApplet.println(connector);  // gets the defaults

    Map<String, Argument> arguments = connector.defaultArguments();

    //  Connector.Argument addressArg =
    //    (Connector.Argument)arguments.get("address");
    //  addressArg.setValue(addr);
    Connector.Argument portArg = arguments.get("port");
    portArg.setValue(portStr);

    //    Connector.Argument timeoutArg =
    //      (Connector.Argument)arguments.get("timeout");
    //    timeoutArg.setValue("10000");

    // PApplet.println(connector);  // prints the current
    // com.sun.tools.jdi.AbstractLauncher al;
    // com.sun.tools.jdi.RawCommandLineLauncher rcll;

    // System.out.println(PApplet.javaVersion);
    // http://java.sun.com/j2se/1.5.0/docs/guide/jpda/conninv.html#sunlaunch

    try {
      //      boolean available = false;
      //      while (!available) {
      while (true) {
        try {
          vm = connector.attach(arguments);
          //          vm = connector.attach(arguments);
          if (vm != null) {
            //            generateTrace();
            //            available = true;
            return true;
          }
        } catch (IOException e) {
          //          System.out.println("waiting");
          //          e.printStackTrace();
          try {
            Thread.sleep(100);
          } catch (InterruptedException e1) {
            e1.printStackTrace(sketchErr);
          }
        }
      }
      //    } catch (IOException exc) {
      //      throw new Error("Unable to launch target VM: " + exc);
    } catch (IllegalConnectorArgumentsException exc) {
      throw new Error("Internal error: " + exc);
    }
  }
Esempio n. 18
0
 public boolean isAlive() {
   return streamReader.isAlive();
 }