/*package*/ void packet(Packet packet) {
    logger.fine(String.format("writing packet %s", packet));
    final Manager self = this;

    if (!self.encoding) {
      self.encoding = true;
      this.encoder.encode(
          packet,
          new Parser.Encoder.Callback() {
            @Override
            public void call(Object[] encodedPackets) {
              for (Object packet : encodedPackets) {
                if (packet instanceof String) {
                  self.engine.write((String) packet);
                } else if (packet instanceof byte[]) {
                  self.engine.write((byte[]) packet);
                }
              }
              self.encoding = false;
              self.processPacketQueue();
            }
          });
    } else {
      self.packetBuffer.add(packet);
    }
  }
Exemple #2
0
  /**
   * Indicates whether this ThrowableSet includes some exception that might be caught by a handler
   * argument of the type <code>catcher</code>.
   *
   * @param catcher type of the handler parameter to be tested.
   * @return <code>true</code> if this set contains an exception type that might be caught by <code>
   *     catcher</code>, false if it does not.
   */
  public boolean catchableAs(RefType catcher) {
    if (INSTRUMENTING) {
      Manager.v().catchableAsQueries++;
    }

    FastHierarchy h = Scene.v().getOrMakeFastHierarchy();

    if (exceptionsExcluded.size() > 0) {
      if (INSTRUMENTING) {
        Manager.v().catchableAsFromSearch++;
      }
      for (Iterator i = exceptionsExcluded.iterator(); i.hasNext(); ) {
        AnySubType exclusion = (AnySubType) i.next();
        if (h.canStoreType(catcher, exclusion.getBase())) {
          return false;
        }
      }
    }

    if (exceptionsIncluded.contains(catcher)) {
      if (INSTRUMENTING) {
        if (exceptionsExcluded.size() == 0) {
          Manager.v().catchableAsFromMap++;
        } else {
          Manager.v().catchableAsFromSearch++;
        }
      }
      return true;
    } else {
      if (INSTRUMENTING) {
        if (exceptionsExcluded.size() == 0) {
          Manager.v().catchableAsFromSearch++;
        }
      }
      for (Iterator i = exceptionsIncluded.iterator(); i.hasNext(); ) {
        RefLikeType thrownType = (RefLikeType) i.next();
        if (thrownType instanceof RefType) {
          if (thrownType == catcher) {
            // assertion failure.
            throw new IllegalStateException(
                "ThrowableSet.catchableAs(RefType): exceptions.contains() failed to match contained RefType "
                    + catcher);
          } else if (h.canStoreType(thrownType, catcher)) {
            return true;
          }
        } else {
          RefType thrownBase = ((AnySubType) thrownType).getBase();
          // At runtime, thrownType might be instantiated by any
          // of thrownBase's subtypes, so:
          if (h.canStoreType(thrownBase, catcher) || h.canStoreType(catcher, thrownBase)) {
            return true;
          }
        }
      }
      return false;
    }
  }
  public void startProcessing() {

    try {
      processor = Manager.createProcessor(getMainCamSource());
    } catch (IOException e) {
      //            JOptionPane.showMessageDialog(parent,
      //               "IO Exception creating processor: " + e.getMessage(), "Error",
      // JOptionPane.WARNING_MESSAGE);
      return;
    } catch (NoProcessorException e) {
      //            JOptionPane.showMessageDialog(parent,
      //               "Exception creating processor: " + e.getMessage(), "Error",
      // JOptionPane.WARNING_MESSAGE);
      return;
    }

    CamStateHelper playhelper = new CamStateHelper(processor);
    if (!playhelper.configure(10000)) {
      JOptionPane.showMessageDialog(
          parent, "cannot configure processor", "Error", JOptionPane.WARNING_MESSAGE);
      return;
    }
    processor.setContentDescriptor(null);
    if (!playhelper.realize(10000)) {
      JOptionPane.showMessageDialog(
          parent, "cannot realize processor", "Error", JOptionPane.WARNING_MESSAGE);
      return;
    }
    // In order for or your clones to start, you must start the original source
    processor.start();
    setProcessing(true);
  }
  public void setMainSource() {
    setProcessing(false);
    VideoFormat vidformat = new VideoFormat(VideoFormat.RGB);
    Vector devices = CaptureDeviceManager.getDeviceList(vidformat);
    CaptureDeviceInfo di = null;

    if (devices.size() > 0) di = (CaptureDeviceInfo) devices.elementAt(0);
    else {
      JOptionPane.showMessageDialog(
          parent, "Your camera is not connected", "No webcam found", JOptionPane.WARNING_MESSAGE);
      return;
    }

    try {
      ml = di.getLocator();
      setMainCamSource(Manager.createDataSource(ml));
    } catch (Exception e) {
      JOptionPane.showMessageDialog(
          parent,
          "Exception locating media: " + e.getMessage(),
          "Error",
          JOptionPane.WARNING_MESSAGE);
      return;
    }
  }
Exemple #5
0
  public static void add() {
    Scanner sc = new Scanner(System.in);
    try {
      System.out.println("Nome: ");
      String name = sc.next();
      System.out.println("CC: ");
      int cc = sc.nextInt();
      System.out.println("Data de nascimento: ");
      System.out.println("Dia: ");
      int day = sc.nextInt();
      System.out.println("M�s: ");
      int month = sc.nextInt();
      System.out.println("Ano: ");
      int year = sc.nextInt();

      if (validateName(name) && validateCC(cc) && validateDate(day, month, year)) {
        Data data = new Data(day, month, year);
        Pessoa nova = new Pessoa(name, cc, data);
        Manager.add(Integer.toString(cc), nova);
      } else {
        System.out.println("Inseriu dados incorretos!");
      }

    } catch (InputMismatchException e) {
      System.err.println("N�o pode inserir letras onde devem constar n�meros!");
    }
  }
Exemple #6
0
  public static void remove() {
    Scanner sc = new Scanner(System.in);
    System.out.println("CC: ");
    String cc = sc.next();

    Manager.delete(cc);
  }
  @Override
  public void update() {
    if (!transmitting) {
      super.update();

      ArrayList deadMonsters = new ArrayList();

      Monster monster = null;

      try {
        for (String key : monsters.keySet()) {
          monster = (Monster) monsters.get(key);
          if (monster != null) {
            monster.update();
            if (monster.getIsDead()) {
              deadMonsters.add(key);
            }
          }
        }

        if (deadMonsters.size() > 0) {
          for (int i = 0; i < deadMonsters.size(); i++) {
            // EIError.debugMsg((String) deadMonsters.get(i));
            monsters.remove((String) deadMonsters.get(i));
          }
        }
      } catch (ConcurrentModificationException concEx) {
        // another thread was trying to modify monsters while iterating
        // we'll continue and the new item can be grabbed on the next update
      }
    }
  }
Exemple #8
0
 @Override
 public void handleCollision(Entity entity, int collisionEnum, int damage) {
   if (collisionEnum == CollisionEnum.DAMAGING) {
     // hitSound.stop();
     // hitSound.play();
   }
   super.handleCollision(entity, collisionEnum, damage);
 }
Exemple #9
0
 /**
  * Shutdown this session instance, only waiting a definite amount of time.
  *
  * <p>This closes all connections used by this sessions. Note that if you want to shutdown the
  * full {@code Cluster} instance this session is part of, you should use {@link Cluster#shutdown}
  * instead (which will call this method for all session but also release some additional
  * resources).
  *
  * <p>Note that this method is not thread safe in the sense that if another shutdown is perform in
  * parallel, it might return {@code true} even if the instance is not yet fully shutdown.
  *
  * @param timeout how long to wait for the session to shutdown.
  * @param unit the unit for the timeout.
  * @return {@code true} if the session has been properly shutdown within the {@code timeout},
  *     {@code false} otherwise.
  */
 public boolean shutdown(long timeout, TimeUnit unit) {
   try {
     return manager.shutdown(timeout, unit);
   } catch (InterruptedException e) {
     Thread.currentThread().interrupt();
     return false;
   }
 }
Exemple #10
0
  public void run() {
    while (true) {
      float timePassed = (System.nanoTime() - lastTimeNanos) / 10000000f;
      lastTimeNanos = System.nanoTime();

      if (!rpgBot.isRunning) return;
      for (Manager m : managers) {
        m.update(timePassed);
      }

      try {
        Thread.sleep(50);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  public List<File> getProjectFiles(Project project) {
    Session session = ((HibernateStorage) Manager.getStorageInstance()).getHibernateSession();
    Query q = session.createQuery("from File f where name.project = :project");
    q.setEntity("project", project);
    List<File> files = q.list();

    return files;
  }
  public BrowseApplication() {
    links = new LinkedList<MenuLink>();

    eventTypes = new LinkedList<String>();
    eventTypes.add("filechangeset");

    updater.setApplication(this);
    Manager.getInstance().addProjectListener(updater);
  }
  public static List<ScmChange> getChanges(Project project, String path) {
    Session session = ((HibernateStorage) Manager.getStorageInstance()).getHibernateSession();

    String prefix = "";
    java.io.File searchDir = Manager.getStorageInstance().getWorkingDirectory(project);
    while (project.getParent() != null) {
      prefix = searchDir.getName() + java.io.File.separatorChar + prefix;
      project = project.getParent();
      searchDir = searchDir.getParentFile();
    }

    Query q =
        session.createQuery(
            "from ScmChange c where c.set.id.project = :project and name = :path order by c.set.date desc");
    q.setEntity("project", project);
    q.setString("path", prefix + path);

    return q.list();
  }
  public static boolean getFileExists(Project project, String fileName) {
    Session session = ((HibernateStorage) Manager.getStorageInstance()).getHibernateSession();

    Query q =
        session.createQuery(
            "select count(*) from File f where f.name.project = :project and f.name.name = :name");
    q.setEntity("project", project);
    q.setString("name", fileName);

    return ((Long) q.uniqueResult()) > 0;
  }
Exemple #15
0
  /**
   * Executes the provided query asynchronously.
   *
   * <p>This method does not block. It returns as soon as the query has been passed to the
   * underlying network stack. In particular, returning from this method does not guarantee that the
   * query is valid or has even been submitted to a live node. Any exception pertaining to the
   * failure of the query will be thrown when accessing the {@link ResultSetFuture}.
   *
   * <p>Note that for queries that doesn't return a result (INSERT, UPDATE and DELETE), you will
   * need to access the ResultSetFuture (that is call one of its get method to make sure the query
   * was successful.
   *
   * @param query the CQL query to execute (that can be either a {@code Statement} or a {@code
   *     BoundStatement}). If it is a {@code BoundStatement}, all variables must have been bound
   *     (the statement must be ready).
   * @return a future on the result of the query.
   * @throws IllegalStateException if {@code query} is a {@code BoundStatement} but {@code
   *     !query.isReady()}.
   */
  public ResultSetFuture executeAsync(Query query) {

    if (query instanceof Statement) {
      return manager.executeQuery(
          new QueryMessage(
              ((Statement) query).getQueryString(),
              ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())),
          query);
    } else {
      assert query instanceof BoundStatement : query;

      BoundStatement bs = (BoundStatement) query;
      return manager.executeQuery(
          new ExecuteMessage(
              bs.statement.id,
              Arrays.asList(bs.values),
              ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())),
          query);
    }
  }
  public static boolean getChangeSetExists(Project project, String changeId) {
    Session session = ((HibernateStorage) Manager.getStorageInstance()).getHibernateSession();

    Query q =
        session.createQuery(
            "select count(*) from ScmChangeSet s where s.id.project = :project and s.revision = :rev");
    q.setEntity("project", project);
    q.setString("rev", changeId);

    return ((Long) q.uniqueResult()) > 0;
  }
  public <T> Request makeManagedRequest(
      final Command cmd, final Manager<T> manager, final Request.Builder<T> builder) {
    final Request request = newRequest(cmd);
    final boolean[] responded = new boolean[] {false};
    request.once(
        Request.OnTimeout.class,
        new Request.OnTimeout() {
          @Override
          public void called(Response args) {
            if (!responded[0] && manager.retryOnUnsuccessful(null)) {
              logRetry(request, "Request timed out");
              request.clearAllListeners();
              queueRetry(50, cmd, manager, builder);
            }
          }
        });
    final OnDisconnected cb =
        new OnDisconnected() {
          @Override
          public void called(Client c) {
            if (!responded[0] && manager.retryOnUnsuccessful(null)) {
              logRetry(request, "Client disconnected");
              request.clearAllListeners();
              queueRetry(50, cmd, manager, builder);
            }
          }
        };
    once(OnDisconnected.class, cb);
    request.once(
        Request.OnResponse.class,
        new Request.OnResponse() {
          @Override
          public void called(final Response response) {
            responded[0] = true;
            Client.this.removeListener(OnDisconnected.class, cb);

            if (response.succeeded) {
              final T t = builder.buildTypedResponse(response);
              manager.cb(response, t);
            } else {
              if (manager.retryOnUnsuccessful(response)) {
                queueRetry(50, cmd, manager, builder);
              } else {
                manager.cb(response, null);
              }
            }
          }
        });
    builder.beforeRequest(request);
    manager.beforeRequest(request);
    request.request();
    return request;
  }
  private InputStream getInputStream(
      String urlStr, Format outputFormat, ContentDescriptor outputContentDescriptor)
      throws Exception {
    final ProcessorModel processorModel =
        new ProcessorModel(
            new MediaLocator(urlStr),
            outputFormat == null ? null : new Format[] {outputFormat},
            outputContentDescriptor);

    final Processor processor = Manager.createRealizedProcessor(processorModel);

    final DataSource ds = processor.getDataOutput();

    final DataSink[] streamDataSinkHolder = new DataSink[] {null};
    // connect the data output of the processor to a StreamDataSink, which
    // will make the data available to PipedInputStream, which we return.
    final PipedInputStream in =
        new PipedInputStream() {
          // override close to clean up everything when the media has been
          // served.
          @Override
          public void close() throws IOException {
            super.close();
            logger.fine("Closed input stream");
            logger.fine("Stopping processor");
            processor.stop();
            logger.fine("Closing processor");
            processor.close();
            logger.fine("Deallocating processor");
            processor.deallocate();
            if (streamDataSinkHolder[0] != null) {
              logger.fine("Closing StreamDataSink");
              streamDataSinkHolder[0].close();
            }
          }
        };
    final PipedOutputStream out = new PipedOutputStream(in);
    final DataSink streamDataSink = new StreamDataSink(out);
    streamDataSinkHolder[0] = streamDataSink;

    streamDataSink.setSource(ds);
    streamDataSink.open();
    streamDataSink.start();

    logger.info("Starting processor");
    processor.start();

    // TODO: if there is an error, make sure we clean up.
    // for example, if the client breaks the connection.
    // we need a controller listener to listen for errors.

    return in;
  }
Exemple #19
0
  /**
   * Restarts the recording for a specific SSRC.
   *
   * @param ssrc the SSRC for which to restart recording. RTP packet of the new recording).
   */
  private void resetRecording(long ssrc, long timestamp) {
    ReceiveStreamDesc receiveStream = findReceiveStream(ssrc);

    // we only restart audio recordings
    if (receiveStream != null && receiveStream.format instanceof AudioFormat) {
      String newFilename = getNextFilename(path + "/" + ssrc, AUDIO_FILENAME_SUFFIX);

      // flush the buffer contained in the MP3 encoder
      String s = "trying to flush ssrc=" + ssrc;
      Processor p = receiveStream.processor;
      if (p != null) {
        s += " p!=null";
        for (TrackControl tc : p.getTrackControls()) {
          Object o = tc.getControl(FlushableControl.class.getName());
          if (o != null) ((FlushableControl) o).flush();
        }
      }

      if (logger.isInfoEnabled()) {
        logger.info("Restarting recording for SSRC=" + ssrc + ". New filename: " + newFilename);
      }

      receiveStream.dataSink.close();
      receiveStream.dataSink = null;

      // flush the FMJ jitter buffer
      // DataSource ds = receiveStream.receiveStream.getDataSource();
      // if (ds instanceof net.sf.fmj.media.protocol.rtp.DataSource)
      //    ((net.sf.fmj.media.protocol.rtp.DataSource)ds).flush();

      receiveStream.filename = newFilename;
      try {
        receiveStream.dataSink =
            Manager.createDataSink(
                receiveStream.dataSource, new MediaLocator("file:" + newFilename));
      } catch (NoDataSinkException ndse) {
        logger.warn("Could not reset recording for SSRC=" + ssrc + ": " + ndse);
        removeReceiveStream(receiveStream, false);
      }

      try {
        receiveStream.dataSink.open();
        receiveStream.dataSink.start();
      } catch (IOException ioe) {
        logger.warn("Could not reset recording for SSRC=" + ssrc + ": " + ioe);
        removeReceiveStream(receiveStream, false);
      }

      audioRecordingStarted(ssrc, timestamp);
    }
  }
Exemple #20
0
 /**
  * Returns a <code>ThrowableSet</code> which contains all the exceptions in <code>s</code> in
  * addition to those in this <code>ThrowableSet</code>.
  *
  * @param s set of exceptions to add to this set.
  * @return the union of this set with <code>s</code>
  * @throws ThrowableSet.AlreadyHasExclusionsException if this <code>ThrowableSet</code> or <code>s
  *     </code> is the result of a {@link #whichCatchableAs(RefType)} operation, so that it is not
  *     possible to represent the addition of <code>s</code> to this <code>ThrowableSet</code>.
  */
 public ThrowableSet add(ThrowableSet s) throws ThrowableSet.AlreadyHasExclusionsException {
   if (INSTRUMENTING) {
     Manager.v().addsOfSet++;
   }
   if (exceptionsExcluded.size() > 0 || s.exceptionsExcluded.size() > 0) {
     throw new AlreadyHasExclusionsException(
         "ThrowableSet.Add(ThrowableSet): attempt to add to ["
             + this.toString()
             + "] after removals recorded.");
   }
   ThrowableSet result = getMemoizedAdds(s);
   if (result == null) {
     if (INSTRUMENTING) {
       Manager.v().addsInclusionFromSearch++;
       Manager.v().addsExclusionWithoutSearch++;
     }
     result = this.add(s.exceptionsIncluded);
     memoizedAdds.put(s, result);
   } else if (INSTRUMENTING) {
     Manager.v().addsInclusionFromMemo++;
     Manager.v().addsExclusionWithoutSearch++;
   }
   return result;
 }
Exemple #21
0
  /**
   * Execute the provided query asynchronously.
   *
   * <p>This method does not block. It returns as soon as the query has been successfully sent to a
   * Cassandra node. In particular, returning from this method does not guarantee that the query is
   * valid. Any exception pertaining to the failure of the query will be thrown by the first access
   * to the {@link ResultSet}.
   *
   * <p>Note that for queries that doesn't return a result (INSERT, UPDATE and DELETE), you will
   * need to access the ResultSet (i.e. call any of its method) to make sure the query was
   * successful.
   *
   * @param query the CQL query to execute (that can be either a {@code Statement} or a {@code
   *     BoundStatement}). If it is a {@code BoundStatement}, all variables must have been bound
   *     (the statement must be ready).
   * @return a future on the result of the query.
   * @throws IllegalStateException if {@code query} is a {@code BoundStatement} but {@code
   *     !query.isReady()}.
   */
  public ResultSetFuture executeAsync(Query query) {

    if (query instanceof Statement) {
      return manager.executeQuery(
          new QueryMessage(
              ((Statement) query).getQueryString(),
              ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())),
          query);
    } else {
      assert query instanceof BoundStatement : query;

      BoundStatement bs = (BoundStatement) query;
      if (!bs.isReady())
        throw new IllegalStateException(
            "Some bind variables haven't been bound in the provided statement");

      return manager.executeQuery(
          new ExecuteMessage(
              bs.statement.id,
              Arrays.asList(bs.values),
              ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())),
          query);
    }
  }
  @Override
  public void setTransient(Registry rg) {
    super.setTransient(rg);

    spawnCoolDowns = new HashMap<String, Integer>();

    try {
      for (String key : monsters.keySet()) {
        Monster monster = (Monster) monsters.get(key);
        monster.setTransient(rg, this);
      }
    } catch (ConcurrentModificationException concEx) {
      // another thread was trying to modify monsters while iterating
      // we'll continue and the new item can be grabbed on the next update
    }
  }
Exemple #23
0
  /* Creates player for file 'source' */
  private void createPlayer(String source) {
    closePlayer();
    try {
      /* What is file extention? */
      String ext = "wav";
      int point = source.lastIndexOf('.');
      if (-1 != point) {
        ext = source.substring(point + 1).toLowerCase();
      }

      InputStream is = getClass().getResourceAsStream(source);
      if (null != is) {
        player = Manager.createPlayer(is, getMimeType(ext));
        player.addPlayerListener(this);
      }
    } catch (Exception e) {
      closePlayer();
    }
  }
  public static void main(String args[]) throws Exception {

    // Take the path of the audio file from command line

    File f = new File("C:\\Users\\Larry\\AppData\\Local\\Temp\\jgoogle_tts-588881786930740869.mp3");
    // Create a Player object that realizes the audio
    final Player p = Manager.createRealizedPlayer(f.toURI().toURL());
    // Start the music
    p.start();
    // Create a Scanner object for taking input from cmd
    Scanner s = new Scanner(System.in);

    // Read a line and store it in st

    String st = s.nextLine();

    // If user types 's', stop the audio

    if (st.equals("s")) {

      p.stop();
    }
  }
Exemple #25
0
  private void playNotification(int notType) {
    final long now = System.currentTimeMillis();
    if (!isCompulsory(playingType) && isCompulsory(notType)) {
      nextPlayTime = 0;
    }
    if (NOTIFY_ALARM == notType) {
      if (!Options.getBoolean(Options.OPTION_ALARM)) return;
      if (now < nextPlayTime) return;
      nextPlayTime = now + 0; // it is changed
      playingType = notType;
      vibrate(1500);
      if (Options.getBoolean(Options.OPTION_SILENT_MODE)) return;
      playNotify(notType, 100);
      return;
    }

    // #sijapp cond.if modules_MAGIC_EYE is "true" #
    // //eye sound
    if (NOTIFY_EYE == notType) { // eye sound
      if (Options.getBoolean(Options.OPTION_SILENT_MODE)) return; // eye sound
      if (Options.getBoolean(Options.OPTION_EYE_NOTIF)) { // eye sound
        if (!_this.play("eye.wav", 60))
          if (!_this.play("eye.amr", 60)) _this.play("eye.mp3", 60); // eye sound
      } // eye sound
    } // eye sound
    // #sijapp cond.end #
    // //eye sound

    int vibraKind = Options.getInt(Options.OPTION_VIBRATOR);
    if (vibraKind == 2) {
      vibraKind = Jimm.isLocked() ? 1 : 0;
    }
    if ((vibraKind > 0) && ((NOTIFY_MESSAGE == notType) || (NOTIFY_MULTIMESSAGE == notType))) {
      vibrate(Util.strToIntDef(Options.getString(Options.OPTION_VIBRATOR_TIME), 150)); // vibra time
    }

    if (Options.getBoolean(Options.OPTION_SILENT_MODE)) return;
    if (now < nextPlayTime) return;
    nextPlayTime = now + 2000;
    playingType = notType;

    // #sijapp cond.if target is "MIDP2" | target is "MOTOROLA" | target is "SIEMENS2"#
    switch (getNotificationMode(notType)) {
      case 1:
        try {
          switch (notType) {
            case NOTIFY_MESSAGE:
              Manager.playTone(ToneControl.C4, 750, Options.getInt(Options.OPTION_MESS_NOTIF_VOL));
              break;
            case NOTIFY_ONLINE:
            case NOTIFY_OFFLINE: // offline sound
            case NOTIFY_TYPING:
            case NOTIFY_OTHER: // other sound
              Manager.playTone(
                  ToneControl.C4 + 7, 750, Options.getInt(Options.OPTION_ONLINE_NOTIF_VOL));
          }

        } catch (Exception e) {
        }
        break;

      case 2:
        int notifyType = NOTIFY_MESSAGE;
        int volume = 0;
        switch (notType) {
          case NOTIFY_MESSAGE:
            volume = Options.getInt(Options.OPTION_MESS_NOTIF_VOL);
            break;

          case NOTIFY_ONLINE:
            volume = Options.getInt(Options.OPTION_ONLINE_NOTIF_VOL);
            break;

          case NOTIFY_OFFLINE: // offline sound
            volume = Options.getInt(Options.OPTION_OFFLINE_NOTIF_VOL); // offline sound
            break; // offline sound

          case NOTIFY_TYPING:
            volume = Options.getInt(Options.OPTION_TYPING_VOL); // typing
            break;

          case NOTIFY_OTHER: // other sound
            volume = Options.getInt(Options.OPTION_OTHER_NOTIF_VOL); // other sound
            break; // other sound
        }
        playNotify(notType, volume);
        break;
    }
  }
Exemple #26
0
  /**
   * Partitions the exceptions in this <code>ThrowableSet</code> into those which would be caught by
   * a handler with the passed <code>catch</code> parameter type and those which would not.
   *
   * @param catcher type of the handler parameter to be tested.
   * @return a pair of <code>ThrowableSet</code>s, one containing the types in this <code>
   *     ThrowableSet</code> which would be be caught as <code>catcher</code> and the other
   *     containing the types in this <code>ThrowableSet</code> which would not be caught as <code>
   *     catcher</code>.
   */
  public Pair whichCatchableAs(RefType catcher) {
    if (INSTRUMENTING) {
      Manager.v().removesOfAnySubType++;
    }

    FastHierarchy h = Scene.v().getOrMakeFastHierarchy();
    Set caughtIncluded = null;
    Set caughtExcluded = null;
    Set uncaughtIncluded = null;
    Set uncaughtExcluded = null;

    if (INSTRUMENTING) {
      Manager.v().removesFromSearch++;
    }

    for (Iterator i = exceptionsExcluded.iterator(); i.hasNext(); ) {
      AnySubType exclusion = (AnySubType) i.next();
      RefType exclusionBase = exclusion.getBase();
      if (h.canStoreType(catcher, exclusionBase)) {
        // Because the add() operations ban additions to sets
        // with exclusions, we can be sure no types in this are
        // caught by catcher.
        return new Pair(ThrowableSet.Manager.v().EMPTY, this);
      } else if (h.canStoreType(exclusionBase, catcher)) {
        // exclusion wouldn't be in exceptionsExcluded if one
        // of its supertypes were not in exceptionsIncluded,
        // so we know the next loop will add either that supertype
        // or catcher to caughtIncluded.  Thus:
        caughtExcluded = addExceptionToSet(exclusion, caughtExcluded);
      } else {
        uncaughtExcluded = addExceptionToSet(exclusion, uncaughtExcluded);
      }
    }

    for (Iterator i = exceptionsIncluded.iterator(); i.hasNext(); ) {
      RefLikeType inclusion = (RefLikeType) i.next();
      if (inclusion instanceof RefType) {
        if (h.canStoreType(inclusion, catcher)) {
          caughtIncluded = addExceptionToSet(inclusion, caughtIncluded);
        } else {
          uncaughtIncluded = addExceptionToSet(inclusion, uncaughtIncluded);
        }
      } else {
        RefType base = ((AnySubType) inclusion).getBase();
        if (h.canStoreType(base, catcher)) {
          // All subtypes of base will be caught.  Any exclusions
          // will already have been copied to caughtExcluded by
          // the preceding loop.
          caughtIncluded = addExceptionToSet(inclusion, caughtIncluded);
        } else if (h.canStoreType(catcher, base)) {
          // Some subtypes of base will be caught, and
          // we know that not all of those catchable subtypes
          // are among exceptionsExcluded, since in that case we
          // would already have returned from within the
          // preceding loop.  So, remove AnySubType(catcher)
          // from the uncaught types.
          uncaughtIncluded = addExceptionToSet(inclusion, uncaughtIncluded);
          uncaughtExcluded = addExceptionToSet(AnySubType.v(catcher), uncaughtExcluded);
          caughtIncluded = addExceptionToSet(AnySubType.v(catcher), caughtIncluded);
          // Any already excluded subtypes of inclusion
          // which are subtypes of catcher will have been
          // added to caughtExcluded by the previous loop.
        } else {
          uncaughtIncluded = addExceptionToSet(inclusion, uncaughtIncluded);
        }
      }
    }
    ThrowableSet caughtSet = Manager.v().registerSetIfNew(caughtIncluded, caughtExcluded);
    ThrowableSet uncaughtSet = Manager.v().registerSetIfNew(uncaughtIncluded, uncaughtExcluded);
    return new Pair(caughtSet, uncaughtSet);
  }
Exemple #27
0
  /**
   * Returns a <code>ThrowableSet</code> which contains all the exceptions in <code>addedExceptions
   * </code> in addition to those in this <code>ThrowableSet</code>.
   *
   * @param addedExceptions a set of {@link RefLikeType} and {@link AnySubType} objects to be added
   *     to the types included in this <code>ThrowableSet</code>.
   * @return a set containing all the <code>addedExceptions</code> as well as the exceptions in this
   *     set.
   */
  private ThrowableSet add(Set addedExceptions) {
    Set resultSet = new HashSet(this.exceptionsIncluded);
    int changes = 0;
    FastHierarchy hierarchy = Scene.v().getOrMakeFastHierarchy();

    // This algorithm is O(n m), where n and m are the sizes of the
    // two sets, so hope that the sets are small.

    for (Iterator i = addedExceptions.iterator(); i.hasNext(); ) {
      RefLikeType newType = (RefLikeType) i.next();
      if (!resultSet.contains(newType)) {
        boolean addNewType = true;
        if (newType instanceof RefType) {
          for (Iterator j = resultSet.iterator(); j.hasNext(); ) {
            RefLikeType incumbentType = (RefLikeType) j.next();
            if (incumbentType instanceof RefType) {
              if (newType == incumbentType) {
                // assertion failure.
                throw new IllegalStateException(
                    "ThrowableSet.add(Set): resultSet.contains() failed to screen duplicate RefType "
                        + newType);
              }
            } else if (incumbentType instanceof AnySubType) {
              RefType incumbentBase = ((AnySubType) incumbentType).getBase();
              if (hierarchy.canStoreType(newType, incumbentBase)) {
                // No need to add this class.
                addNewType = false;
              }
            } else { // assertion failure.
              throw new IllegalStateException(
                  "ThrowableSet.add(Set): incumbent Set element "
                      + incumbentType
                      + " is neither a RefType nor an AnySubType.");
            }
          }
        } else if (newType instanceof AnySubType) {
          RefType newBase = ((AnySubType) newType).getBase();
          for (Iterator j = resultSet.iterator(); j.hasNext(); ) {
            RefLikeType incumbentType = (RefLikeType) j.next();
            if (incumbentType instanceof RefType) {
              RefType incumbentBase = (RefType) incumbentType;
              if (hierarchy.canStoreType(incumbentBase, newBase)) {
                j.remove();
                changes++;
              }
            } else if (incumbentType instanceof AnySubType) {
              RefType incumbentBase = ((AnySubType) incumbentType).getBase();
              if (newBase == incumbentBase) {
                // assertion failure.
                throw new IllegalStateException(
                    "ThrowableSet.add(Set): resultSet.contains() failed to screen duplicate AnySubType "
                        + newBase);
              } else if (hierarchy.canStoreType(incumbentBase, newBase)) {
                j.remove();
                changes++;
              } else if (hierarchy.canStoreType(newBase, incumbentBase)) {
                // No need to add this class.
                addNewType = false;
              }
            } else { // assertion failure.
              throw new IllegalStateException(
                  "ThrowableSet.add(Set): old Set element "
                      + incumbentType
                      + " is neither a RefType nor an AnySubType.");
            }
          }
        } else { // assertion failure.
          throw new IllegalArgumentException(
              "ThrowableSet.add(Set): new Set element "
                  + newType
                  + " is neither a RefType nor an AnySubType.");
        }
        if (addNewType) {
          changes++;
          resultSet.add(newType);
        }
      }
    }

    ThrowableSet result = null;
    if (changes > 0) {
      result = Manager.v().registerSetIfNew(resultSet, this.exceptionsExcluded);
    } else {
      result = this;
    }
    return result;
  }
Exemple #28
0
  /**
   * Returns a <code>ThrowableSet</code> which contains <code>e</code> and all of its subclasses as
   * well as the exceptions in this set.
   *
   * <p><code>e</code> should be an instance of {@link AnySubType} if you know that the compile-time
   * type of the exception you are representing is <code>e</code>, but the exception may be
   * instantiated at run-time by a subclass of <code>e</code>.
   *
   * <p>For example, if you were recording the type of the exception thrown by
   *
   * <pre>
   * catch (IOException e) {
   *    throw e;
   * }
   * </pre>
   *
   * you would call
   *
   * <pre>
   * <code>add(AnySubtype.v(Scene.v().getRefType("java.lang.Exception.IOException")))</code>
   * </pre>
   *
   * since the handler might rethrow any subclass of <code>IOException</code>.
   *
   * @param e represents a subtree of the exception class hierarchy to add to this set.
   * @return a set containing <code>e</code> and all its subclasses, as well as the exceptions
   *     represented by this set.
   * @throws ThrowableSet.AlreadyHasExclusionsException if this <code>ThrowableSet</code> is the
   *     result of a {@link #whichCatchableAs(RefType)} operation and, thus, unable to represent the
   *     addition of <code>e</code>.
   */
  public ThrowableSet add(AnySubType e) throws ThrowableSet.AlreadyHasExclusionsException {
    if (INSTRUMENTING) {
      Manager.v().addsOfAnySubType++;
    }

    ThrowableSet result = getMemoizedAdds(e);
    if (result != null) {
      if (INSTRUMENTING) {
        Manager.v().addsInclusionFromMemo++;
        Manager.v().addsExclusionWithoutSearch++;
      }
      return result;
    } else {
      FastHierarchy hierarchy = Scene.v().getOrMakeFastHierarchy();
      RefType newBase = e.getBase();

      if (INSTRUMENTING) {
        if (exceptionsExcluded.size() != 0) {
          Manager.v().addsExclusionWithSearch++;
        } else {
          Manager.v().addsExclusionWithoutSearch++;
        }
      }
      for (Iterator i = exceptionsExcluded.iterator(); i.hasNext(); ) {
        RefType exclusionBase = ((AnySubType) i.next()).getBase();
        if (hierarchy.canStoreType(newBase, exclusionBase)
            || hierarchy.canStoreType(exclusionBase, newBase)) {
          if (INSTRUMENTING) {
            // To ensure that the subcategories total properly:
            Manager.v().addsInclusionInterrupted++;
          }
          throw new AlreadyHasExclusionsException(
              "ThrowableSet.add("
                  + e.toString()
                  + ") to the set [ "
                  + this.toString()
                  + "] where "
                  + exclusionBase.toString()
                  + " is excluded.");
        }
      }

      if (this.exceptionsIncluded.contains(e)) {
        if (INSTRUMENTING) {
          Manager.v().addsInclusionFromMap++;
        }
        return this;

      } else {
        if (INSTRUMENTING) {
          Manager.v().addsInclusionFromSearch++;
        }

        int changes = 0;
        boolean addNewException = true;
        Set resultSet = new HashSet();

        for (Iterator i = this.exceptionsIncluded.iterator(); i.hasNext(); ) {
          RefLikeType incumbent = (RefLikeType) i.next();
          if (incumbent instanceof RefType) {
            if (hierarchy.canStoreType(incumbent, newBase)) {
              // Omit incumbent from result.
              changes++;
            } else {
              resultSet.add(incumbent);
            }
          } else if (incumbent instanceof AnySubType) {
            RefType incumbentBase = ((AnySubType) incumbent).getBase();
            // We have to use the base types in these hierarchy calls
            // because we want to know if _all_ possible
            // types represented by e can be represented by
            // the incumbent, or vice versa.
            if (hierarchy.canStoreType(newBase, incumbentBase)) {
              addNewException = false;
              resultSet.add(incumbent);
            } else if (hierarchy.canStoreType(incumbentBase, newBase)) {
              // Omit incumbent from result;
              changes++;
            } else {
              resultSet.add(incumbent);
            }
          } else { // assertion failure.
            throw new IllegalStateException(
                "ThrowableSet.add(AnySubType): Set element "
                    + incumbent.toString()
                    + " is neither a RefType nor an AnySubType.");
          }
        }
        if (addNewException) {
          resultSet.add(e);
          changes++;
        }
        if (changes > 0) {
          result = Manager.v().registerSetIfNew(resultSet, this.exceptionsExcluded);
        } else {
          result = this;
        }
        memoizedAdds.put(e, result);
        return result;
      }
    }
  }
Exemple #29
0
  /**
   * Returns a <code>ThrowableSet</code> which contains <code>e</code> in addition to the exceptions
   * in this <code>ThrowableSet</code>.
   *
   * <p>Add <code>e</code> as a {@link RefType} when you know that the run-time class of the
   * exception you are representing is necessarily <code>e</code> and cannot be a subclass of <code>
   * e</code>.
   *
   * <p>For example, if you were recording the type of the exception thrown by
   *
   * <pre>
   * throw new IOException("Permission denied");
   * </pre>
   *
   * you would call
   *
   * <pre>
   * <code>add(Scene.v().getRefType("java.lang.Exception.IOException"))</code>
   * </pre>
   *
   * since the class of the exception is necessarily <code>IOException</code>.
   *
   * @param e the exception class
   * @return a set containing <code>e</code> as well as the exceptions in this set.
   * @throws {@link ThrowableSet.IllegalStateException} if this <code>ThrowableSet</code> is the
   *     result of a {@link #whichCatchableAs(RefType)} operation and, thus, unable to represent the
   *     addition of <code>e</code>.
   */
  public ThrowableSet add(RefType e) throws ThrowableSet.AlreadyHasExclusionsException {
    if (INSTRUMENTING) {
      Manager.v().addsOfRefType++;
    }
    if (this.exceptionsIncluded.contains(e)) {
      if (INSTRUMENTING) {
        Manager.v().addsInclusionFromMap++;
        Manager.v().addsExclusionWithoutSearch++;
      }
      return this;
    } else {
      ThrowableSet result = getMemoizedAdds(e);
      if (result != null) {
        if (INSTRUMENTING) {
          Manager.v().addsInclusionFromMemo++;
          Manager.v().addsExclusionWithoutSearch++;
        }
        return result;
      } else {
        if (INSTRUMENTING) {
          Manager.v().addsInclusionFromSearch++;
          if (exceptionsExcluded.size() != 0) {
            Manager.v().addsExclusionWithSearch++;
          } else {
            Manager.v().addsExclusionWithoutSearch++;
          }
        }
        FastHierarchy hierarchy = Scene.v().getOrMakeFastHierarchy();

        for (Iterator i = exceptionsExcluded.iterator(); i.hasNext(); ) {
          RefType exclusionBase = ((AnySubType) i.next()).getBase();
          if (hierarchy.canStoreType(e, exclusionBase)) {
            throw new AlreadyHasExclusionsException(
                "ThrowableSet.add(RefType): adding"
                    + e.toString()
                    + " to the set [ "
                    + this.toString()
                    + "] where "
                    + exclusionBase.toString()
                    + " is excluded.");
          }
        }

        for (Iterator i = exceptionsIncluded.iterator(); i.hasNext(); ) {
          RefLikeType incumbent = (RefLikeType) i.next();
          if (incumbent instanceof AnySubType) {
            // Need to use incumbent.getBase() because
            // hierarchy.canStoreType() assumes that parent
            // is not an AnySubType.
            RefType incumbentBase = ((AnySubType) incumbent).getBase();
            if (hierarchy.canStoreType(e, incumbentBase)) {
              memoizedAdds.put(e, this);
              return this;
            }
          } else if (!(incumbent instanceof RefType)) {
            // assertion failure.
            throw new IllegalStateException(
                "ThrowableSet.add(RefType): Set element "
                    + incumbent.toString()
                    + " is neither a RefType nor an AnySubType.");
          }
        }
        Set resultSet = new HashSet(this.exceptionsIncluded);
        resultSet.add(e);
        result = Manager.v().registerSetIfNew(resultSet, this.exceptionsExcluded);
        memoizedAdds.put(e, result);
        return result;
      }
    }
  }
Exemple #30
0
 /**
  * A package-private method to provide unit tests with access to the collection of
  * ThrowableSets.
  */
 Map getSizeToSets() {
   return Manager.v().sizeToSets;
 }