/**
  * Register the device to Google Cloud Messaging service or return registration id if it's already
  * registered.
  *
  * @return registration id or empty string if it's not registered.
  */
 private static String gcmRegisterIfNot(Context context) {
   String regId = "";
   try {
     GCMRegistrar.checkDevice(context);
     GCMRegistrar.checkManifest(context);
     regId = GCMRegistrar.getRegistrationId(context);
     String gcmId = BuildConfig.GCM_ID;
     if (gcmId != null && TextUtils.isEmpty(regId)) {
       GCMRegistrar.register(context, gcmId);
     }
   } catch (UnsupportedOperationException e) {
     // GCMRegistrar.checkDevice throws an UnsupportedOperationException if the device
     // doesn't support GCM (ie. non-google Android)
     AppLog.e(T.NOTIFS, "Device doesn't support GCM: " + e.getMessage());
   } catch (IllegalStateException e) {
     // GCMRegistrar.checkManifest or GCMRegistrar.register throws an IllegalStateException if
     // Manifest
     // configuration is incorrect (missing a permission for instance) or if GCM dependencies are
     // missing
     AppLog.e(
         T.NOTIFS,
         "APK (manifest error or dependency missing) doesn't support GCM: " + e.getMessage());
   } catch (Exception e) {
     // SecurityException can happen on some devices without Google services (these devices
     // probably strip
     // the AndroidManifest.xml and remove unsupported permissions).
     AppLog.e(T.NOTIFS, e);
   }
   return regId;
 }
  /**
   * set date source
   *
   * @param path
   */
  public void setDataSource(String path)
      throws IOException, IllegalArgumentException, IllegalStateException {

    if (mPlayStatus != VideoConst.PLAY_STATUS_END) {
      MmpTool.LOG_ERROR("Video is playing,can't set setDataSource");
      sendMsg(VideoConst.MSG_IS_PLAYING);
    }

    isEnd = false;

    try {
      mmediaplayer.setDataSource(path);
    } catch (IOException e) {
      e.printStackTrace();
      throw new IOException();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      throw new IllegalArgumentException(e);
    } catch (IllegalStateException e) {
      e.printStackTrace();
      throw new IllegalStateException(e);
    }

    mPlayStatus = VideoConst.PLAY_STATUS_INITED;

    MmpTool.LOG_DBG("setDataSource finish!");
  }
Example #3
0
    @Override
    public void setDataSource(final String path) throws RemoteException {
      if (mPlayer != null) {
        mPlayer.setOnPreparedListener(
            new OnPreparedListener() {
              @Override
              public void onPrepared(VLCPlayer player) {
                infoOnPrepared();
              }
            });
        mPlayer.setOnBufferingUpdateListener(
            new OnBufferingUpdateListener() {
              @Override
              public void onBufferingUpdate(VLCPlayer player, int percent) {
                infoOnBufferingUpdate(percent);
              }
            });
        mPlayer.setOnCompletionListener(
            new OnCompletionListener() {
              @Override
              public void onCompletion(VLCPlayer player) {
                infoOnCompletion();
              }
            });
        mPlayer.setOnErrorListener(
            new OnErrorListener() {
              @Override
              public boolean onError(VLCPlayer player, int what, int extra) {
                return infoOnError(what, extra);
              }
            });

        boolean bail = false;
        try {
          mPlayer.setDataSource(path);
        } catch (IllegalArgumentException e) {
          e.printStackTrace();
          bail = true;
        } catch (SecurityException e) {
          e.printStackTrace();
          bail = true;
        } catch (IllegalStateException e) {
          e.printStackTrace();
          bail = true;
        } catch (IOException e) {
          e.printStackTrace();
          bail = true;
        } finally {
          if (bail) {
            infoOnError(-1001, 0);
          } else {
            mState = State.INITIALIZED;
            Log.d(TAG, "Player state changed to: INITIALIZED");
          }
        }
      } else {
        Log.e(TAG, "Player instance is null, call create first");
        infoOnError(-1001, 0);
      }
    }
Example #4
0
  public static StringBuilder getResponseString(HttpResponse result) {
    if (result == null) {
      return null;
    }
    StringBuilder builder = new StringBuilder("");

    HttpEntity res = result.getEntity();
    InputStream is = null;
    try {
      is = res.getContent();
    } catch (IllegalStateException e) {
      Log.d("ResponseString", "Response invalid (IllegalStateException) " + e.getMessage());
      return builder;
    } catch (IOException e) {
      Log.d("ResponseString", "Response invalid (IoException)  " + e.getMessage());
      return builder;
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line = null;
    try {
      while ((line = br.readLine()) != null) {
        builder.append(line);
      }
    } catch (IOException e) {
      Log.d("ResponseString", "IOException " + e.getMessage());
      return builder;
    }
    return builder;
  }
Example #5
0
  @Override
  public Result loadInBackground() {
    final Fetch fetch = mFetch;
    final HttpConnectionHelper helper = mHelper;

    List<NameValuePair> parameters = mParameterExtractor.extract(fetch);
    HttpUriRequest request =
        helper.obtainHttpRequest(fetch.getFetchMethod(), fetch.getUrl(), parameters);
    Utils.debug(request.getURI().toString());
    if (fetch.onPreFetch(request, Collections.unmodifiableList(parameters))) {
      return mResult;
    }
    HttpResponse response = helper.execute(request);
    fetch.onPostFetch(request);
    if (null == response) {
      return null;
    }
    try {
      Result result =
          mResult = mParser.parse(fetch, new InputStreamReader(response.getEntity().getContent()));
      Utils.debug(result);
      return result;
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return null;
  }
Example #6
0
  public static void Setup() {

    String musicDir = Environment.getExternalStorageDirectory().getAbsolutePath() + MUSIC_DIR;

    mediaPlayer = new MediaPlayer();

    try {

      mediaPlayer.setDataSource(musicDir);
      mediaPlayer.prepare();
      mediaPlayer.setLooping(true);

    } catch (IllegalArgumentException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SecurityException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IllegalStateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    DistributedTable table = getTable(req, resp);
    if (table == null) {
      return;
    }

    int diff;
    try {
      table.useTransaction(sessionID);
      diff = table.rollback();
      table.removeTransaction(sessionID);
    } catch (IllegalStateException e) {
      resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      return;
    } finally {
      manager.deleteTableByID(sessionID);
    }

    resp.setStatus(HttpServletResponse.SC_OK);

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF8");
    resp.getWriter().println("diff=" + diff);
  }
Example #8
0
  public void setFileState(int state) {
    switch (state) {
      case 0:
        m_mediaPlayer.pause();
        break;

      case 1:
        m_mediaPlayer.stop();
        try {
          m_mediaPlayer.prepare();
        } catch (IllegalStateException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
        m_mediaPlayer.seekTo(0);
        break;

      case 2:
      case 3:
        m_mediaPlayer.start();
        break;

      default:
        break;
    }
  }
 /**
  * メディアの停止.
  *
  * @param response レスポンス
  */
 public void stopMedia(final Intent response) {
   if (mSetMediaType == MEDIA_TYPE_MUSIC) {
     try {
       mMediaPlayer.stop();
       mMediaStatus = MEDIA_PLAYER_STOP;
       sendOnStatusChangeEvent("stop");
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
         mMediaPlayer.reset();
         putMediaId(null, mBackupMediaId);
       }
     } catch (IllegalStateException e) {
       if (BuildConfig.DEBUG) {
         e.printStackTrace();
       }
     }
     response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_OK);
     sendResponse(response);
   } else if (mSetMediaType == MEDIA_TYPE_VIDEO) {
     mMediaStatus = MEDIA_PLAYER_STOP;
     Intent mIntent = new Intent(VideoConst.SEND_HOSTDP_TO_VIDEOPLAYER);
     mIntent.putExtra(VideoConst.EXTRA_NAME, VideoConst.EXTRA_VALUE_VIDEO_PLAYER_STOP);
     getContext().sendBroadcast(mIntent);
     sendOnStatusChangeEvent("stop");
     response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_OK);
     sendResponse(response);
   }
 }
  /**
   * メディアの一時停止.
   *
   * @return セッションID
   */
  public int pauseMedia() {
    if (mSetMediaType == MEDIA_TYPE_MUSIC
        && mMediaStatus != MEDIA_PLAYER_STOP
        && mMediaStatus != MEDIA_PLAYER_SET) {
      try {
        mMediaStatus = MEDIA_PLAYER_PAUSE;
        mMediaPlayer.pause();
      } catch (IllegalStateException e) {
        if (BuildConfig.DEBUG) {
          e.printStackTrace();
        }
      }
      sendOnStatusChangeEvent("pause");
      return mMediaPlayer.getAudioSessionId();

    } else if (mSetMediaType == MEDIA_TYPE_VIDEO) {
      mMediaStatus = MEDIA_PLAYER_PAUSE;
      Intent mIntent = new Intent(VideoConst.SEND_HOSTDP_TO_VIDEOPLAYER);
      mIntent.putExtra(VideoConst.EXTRA_NAME, VideoConst.EXTRA_VALUE_VIDEO_PLAYER_PAUSE);
      getContext().sendBroadcast(mIntent);
      sendOnStatusChangeEvent("pause");
      return 0;
    } else {
      return 0;
    }
  }
Example #11
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.post);

    twitter = ((TwittApplication) getApplication()).getTwitter();

    buttonTweet = (Button) findViewById(R.id.buttonTweet);
    buttonTweet.setOnClickListener(this);

    buttonClear = (Button) findViewById(R.id.buttonClear);
    buttonClear.setOnClickListener(this);

    buttonCancel = (Button) findViewById(R.id.buttonCancel);
    buttonCancel.setOnClickListener(this);

    myName = (TextView) findViewById(R.id.myName);
    try {
      myName.setText(twitter.getScreenName());
    } catch (IllegalStateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TwitterException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  /**
   * Encode the user ID in a secure cookie.
   *
   * @param userId
   * @return
   */
  String encodeCookie(String userId, String tokenType) {
    if (userId == null) {
      return null;
    }
    if (clusterCookieServer != null) {
      return clusterCookieServer.encodeCookie(userId);
    } else {
      long expires = System.currentTimeMillis() + ttl;
      SecureCookie secretKeyHolder = tokenStore.getActiveToken();

      try {
        return secretKeyHolder.encode(expires, userId, tokenType);
      } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
      } catch (InvalidKeyException e) {
        LOG.error(e.getMessage(), e);
      } catch (IllegalStateException e) {
        LOG.error(e.getMessage(), e);
      } catch (UnsupportedEncodingException e) {
        LOG.error(e.getMessage(), e);
      } catch (SecureCookieException e) {
        if (e.isError()) {
          LOG.error(e.getMessage(), e);
        } else {
          LOG.info(e.getMessage(), e);
        }
      }
      return null;
    }
  }
  private void doForward(String relativeUrlPath) throws ServletException, IOException {

    // JSP.4.5 If the buffer was flushed, throw IllegalStateException
    try {
      out.clear();
    } catch (IOException ex) {
      IllegalStateException ise =
          new IllegalStateException(
              Localizer.getMessage("jsp.error.attempt_to_clear_flushed_buffer"));
      ise.initCause(ex);
      throw ise;
    }

    // Make sure that the response object is not the wrapper for include
    while (response instanceof ServletResponseWrapperInclude) {
      response = ((ServletResponseWrapperInclude) response).getResponse();
    }

    final String path = getAbsolutePathRelativeToContext(relativeUrlPath);
    String includeUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);

    if (includeUri != null) request.removeAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
    try {
      context.getRequestDispatcher(path).forward(request, response);
    } finally {
      if (includeUri != null)
        request.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, includeUri);
    }
  }
Example #14
0
 @Override
 public void prepare() throws RemoteException {
   if (mPlayer != null) {
     boolean bail = false;
     try {
       mPlayer.prepare();
     } catch (IllegalStateException e) {
       e.printStackTrace();
       bail = true;
     } catch (IOException e) {
       e.printStackTrace();
       bail = true;
     } finally {
       if (bail) {
         infoOnError(-1001, 0);
       } else {
         mState = State.PREPARED;
         Log.d(TAG, "Player state changed to: PREPARED");
       }
     }
   } else {
     Log.e(TAG, "Player instance is null, call create first");
     infoOnError(-1001, 0);
   }
 }
  @Test
  public void testDisruptorCommandBusRepositoryNotAvailableOutsideOfInvokerThread() {
    DisruptorCommandBus commandBus = new DisruptorCommandBus(eventStore, eventBus);
    Repository<Aggregate> repository =
        commandBus.createRepository(new GenericAggregateFactory<Aggregate>(Aggregate.class));

    AggregateAnnotationCommandHandler<Aggregate> handler =
        new AggregateAnnotationCommandHandler<Aggregate>(Aggregate.class, repository);
    AggregateAnnotationCommandHandler.subscribe(handler, commandBus);
    DefaultCommandGateway gateway = new DefaultCommandGateway(commandBus);

    // Create the aggregate
    String aggregateId = "" + System.currentTimeMillis();
    gateway.sendAndWait(new CreateCommandAndEvent(aggregateId));

    // Load the aggretate from the repository -- from "worker" thread
    UnitOfWork uow = DefaultUnitOfWork.startAndGet();
    try {
      Aggregate aggregate = repository.load(aggregateId);
      fail("Expected IllegalStateException");
    } catch (IllegalStateException e) {
      assertTrue(e.getMessage().contains("DisruptorCommandBus"));
    } finally {
      uow.rollback();
    }
  }
  /** Query entries from the database */
  @Override
  public Cursor query(
      Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    if (database == null || !database.isOpen()) database = databaseHelper.getWritableDatabase();

    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    switch (sUriMatcher.match(uri)) {
      case SENSOR_DEV:
        qb.setTables(DATABASE_TABLES[0]);
        qb.setProjectionMap(sensorDeviceMap);
        break;
      case SENSOR_DATA:
        qb.setTables(DATABASE_TABLES[1]);
        qb.setProjectionMap(sensorDataMap);
        break;
      default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }
    try {
      Cursor c = qb.query(database, projection, selection, selectionArgs, null, null, sortOrder);
      c.setNotificationUri(getContext().getContentResolver(), uri);
      return c;
    } catch (IllegalStateException e) {
      if (Aware.DEBUG) Log.e(Aware.TAG, e.getMessage());

      return null;
    }
  }
Example #17
0
 private void startTimeBufferingThread() {
   String period = manager.getProperty(LogConstants.BUFFER_TIME);
   long interval;
   if ((period != null) || (period.length() != 0)) {
     interval = Long.parseLong(period);
   } else {
     interval = LogConstants.BUFFER_TIME_DEFAULT;
   }
   interval *= 1000;
   if (bufferTask == null) {
     bufferTask = new TimeBufferingTask(interval);
     try {
       SystemTimer.getTimer()
           .schedule(
               bufferTask, new Date(((System.currentTimeMillis() + interval) / 1000) * 1000));
     } catch (IllegalArgumentException e) {
       Debug.error(logName + ":RemoteHandler:BuffTimeArg: " + e.getMessage());
     } catch (IllegalStateException e) {
       if (Debug.messageEnabled()) {
         Debug.message(logName + ":RemoteHandler:BuffTimeState: " + e.getMessage());
       }
     }
     if (Debug.messageEnabled()) {
       Debug.message("RemoteHandler: Time Buffering Thread Started");
     }
   }
 }
  /**
   * Delete multiple messages
   *
   * @param account
   * @param requestJSONContent JSON array of message UUIDs e.g. [uuid1, uuid2, ...]
   * @return
   */
  @DELETE
  @Produces(MediaType.APPLICATION_JSON)
  @Consumes(MediaType.APPLICATION_JSON)
  public Response deleteMessages(
      @PathParam("user") final String user,
      @PathParam("domain") final String domain,
      final String requestJSONContent) {
    Mailbox mailbox = new Mailbox(user, domain);
    List<UUID> messageIds = null;

    try {
      messageIds = JSONUtils.toUUIDList(requestJSONContent);
    } catch (IllegalStateException jpe) {
      logger.info("Malformed JSON request: {}", jpe.getMessage());
      throw new BadRequestException("Malformed JSON request");
    }

    if (messageIds == null || messageIds.isEmpty())
      throw new BadRequestException("Malformed JSON request");

    try {
      // delete message and ignore other parameters
      messageDAO.delete(mailbox, messageIds);
    } catch (Exception e) {
      logger.error("Message deletion failed: ", e);
      throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }

    return Response.noContent().build();
  }
 public void test_migratedFrom() throws Exception {
   assertTrue(
       OptionalThing.migratedFrom(
               Optional.of("sea"),
               () -> {
                 throw new IllegalStateException();
               })
           .isPresent());
   assertFalse(
       OptionalThing.migratedFrom(
               Optional.empty(),
               () -> {
                 throw new IllegalStateException();
               })
           .isPresent());
   try {
     OptionalThing.migratedFrom(
             Optional.empty(),
             () -> {
               throw new IllegalStateException("land");
             })
         .get();
     fail();
   } catch (IllegalStateException e) {
     String message = e.getMessage();
     log(message);
     assertContains(message, "land");
   }
 }
  public void stop(View view) {
    try {
      // stop the recored
      myRecorder.stop();
      myRecorder.release();
      myRecorder = null;

      // button logic
      playBtn.setEnabled(true);
      stopBtn.setEnabled(false);
      startBtn.setEnabled(true);
      browseBtn.setEnabled(true);

      text.setText("GlaDOS Status: Stopping recording");

      Toast.makeText(getApplicationContext(), "Stop recording...", Toast.LENGTH_SHORT).show();

      CURRENT_AUDIO = RECORDED_AUDIO;

    } catch (IllegalStateException e) {
      //  it is called before start()
      e.printStackTrace();
    } catch (RuntimeException e) {
      // no valid audio/video data has been received
      e.printStackTrace();
    }
  }
 public ServiceProduct getServiceProductBySpId(String productId) {
   //        ServiceProduct sp=new ServiceProduct();
   List list = null;
   Session session = getSession();
   try {
     String sql =
         "select sp.csp_id from service_product sp,product p where p.id = sp.product_id and p.MOBILE_PRODUCT = 1";
     Query query = session.createSQLQuery(sql);
     list = query.list();
   } catch (DataAccessResourceFailureException e) {
     logger.error("Hibernate错误:" + e.getMessage());
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   } catch (IllegalStateException e) {
     logger.error("Hibernate错误:" + e.getMessage());
     e
         .printStackTrace(); // To change body of catch statement use File | Settings | File
                             // Templates.
   } catch (HibernateException e) {
     logger.error("Hibernate错误:" + e.getMessage());
     e.printStackTrace();
   } finally {
     session.close();
   }
   //        return list==null||list.size() == 0?null:list.get(0);
   return null;
 }
  /**
   * Version-dependent support for generating a dummy disk store from the given cache and disk store
   * configuration.
   */
  protected static void generateDummyDiskStore(
      Cache dummyCache, String diskStoreConfig, String fn, Map XmlDiskStoreConfigs) {
    DiskStoreDescription dsd = DiskStoreHelper.getDiskStoreDescription(diskStoreConfig);
    DiskStoreFactory dummyFactory = ((CacheCreation) dummyCache).createDiskStoreFactory();
    dsd.configure(dummyFactory);
    String diskStoreName = dsd.getName();
    DiskStore dummyDiskStore = null;
    try {
      dummyDiskStore = dummyFactory.create(diskStoreName);
    } catch (IllegalStateException e) {
      String msg = "A disk store named \"" + diskStoreName + "\" already exists.";
      if (e.getMessage().equals(msg)) {
        if (!XmlDiskStoreConfigs.values().contains(diskStoreConfig)) {
          String s =
              "DiskStore with configuration "
                  + diskStoreConfig
                  + " named "
                  + diskStoreName
                  + " was already created without CacheHelper XML using"
                  + " an unknown, and possibly different, configuration";
          throw new HydraRuntimeException(s);
        } // else the configuration was done here, which is fine
      } else {
        throw e;
      }
    }
    if (Log.getLogWriter().infoEnabled()) {
      Log.getLogWriter()
          .info("Added dummy disk store: " + DiskStoreHelper.diskStoreToString(dummyDiskStore));
    }

    // save the disk store config for future reference
    XmlDiskStoreConfigs.put(fn, diskStoreConfig);
  }
    @Override
    public void run() {
      if (!backlogStore.exists()) {
        return;
      }

      try (BufferedReader fr = new BufferedReader(new FileReader(backlogStore))) {
        while (!Thread.interrupted()) {
          String line = fr.readLine();
          if (line == null) {
            break;
          }

          try {
            messageHandler.processBackloggedMessage(fromString(line));
          } catch (IllegalStateException e) {
            LOGGER.debug("Unable to reload message; {}", e.getMessage());
          }
        }

        backlogStore.delete();
      } catch (FileNotFoundException e) {
        LOGGER.error("Unable to reload checkpoint file: {}", e.getMessage());
      } catch (IOException e) {
        LOGGER.error("Unrecoverable error during reload checkpoint file: {}", e.getMessage());
      }

      LOGGER.info("Done reloading backlogged messages.");
    }
  public boolean setup(SessionDescription sd, int mediaIndex) {
    boolean finish = false;
    try {
      Vector<MediaDescription> mds = sd.getMediaDescriptions(true);

      if (mds.size() <= mediaIndex) {
        finish = true;
      } else {
        MediaDescription md = mds.get(mediaIndex);

        RtpSessionExt rtp = rtspStack.createRtpSession(md);
        rtp.bind(false, true);

        // sendTCPSetup(md.getAttribute("control"), rtp.getRtpInterleaved(),
        // rtp.getRtcpInterleaved());
        sendUDPSetup(md.getAttribute("control"), rtp.getRtpPort(), rtp.getRtcpPort());

        setState(RTSP.SETUP);
      }

    } catch (SdpException e) {
      throw new IllegalArgumentException(e);
    } catch (IllegalStateException e) {
      logger.error(e.getMessage(), e);
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
    }

    return finish;
  }
 /** pause */
 public void pause() throws IllegalStateException {
   if (mmediaplayer != null) {
     if (mPlayStatus == VideoConst.PLAY_STATUS_STARTED) {
       try {
         mmediaplayer.pause();
       } catch (IllegalStateException e) {
         e.printStackTrace();
         sendMsg(VideoConst.MSG_INVALID_STATE);
         throw new IllegalStateException(e);
       }
       mPlayStatus = VideoConst.PLAY_STATUS_PAUSED;
       MmpTool.LOG_DBG("pause!");
     } else {
       try {
         mmediaplayer.start();
       } catch (IllegalStateException e) {
         e.printStackTrace();
         sendMsg(VideoConst.MSG_INVALID_STATE);
         throw new IllegalStateException(e);
       }
       mPlayStatus = VideoConst.PLAY_STATUS_STARTED;
       MmpTool.LOG_DBG("play!");
     }
   }
 }
Example #26
0
 @Test(expected = InvalidObjectException.class)
 public void shouldNotDeserializeListWithSizeLessThanOne() throws Throwable {
   try {
     /*
      * This implementation is stable regarding jvm impl changes of object serialization. The index of the number
      * of List elements is gathered dynamically.
      */
     final byte[] listWithOneElement = Serializables.serialize(List.of(0));
     final byte[] listWithTwoElements = Serializables.serialize(List.of(0, 0));
     int index = -1;
     for (int i = 0; i < listWithOneElement.length && index == -1; i++) {
       final byte b1 = listWithOneElement[i];
       final byte b2 = listWithTwoElements[i];
       if (b1 != b2) {
         if (b1 != 1 || b2 != 2) {
           throw new IllegalStateException("Difference does not indicate number of elements.");
         } else {
           index = i;
         }
       }
     }
     if (index == -1) {
       throw new IllegalStateException("Hack incomplete - index not found");
     }
     /*
      * Hack the serialized data and fake zero elements.
      */
     listWithOneElement[index] = 0;
     Serializables.deserialize(listWithOneElement);
   } catch (IllegalStateException x) {
     throw (x.getCause() != null) ? x.getCause() : x;
   }
 }
  public void testModuleBindings() throws Exception {
    Module module =
        new AbstractModule() {
          @Override
          protected void configure() {}

          @Provides
          Integer fail() {
            return 1;
          }
        };
    // sanity check that the injector works
    Injector injector = Guice.createInjector(module);
    assertEquals(1, injector.getInstance(Integer.class).intValue());
    ProviderInstanceBinding injectorBinding =
        (ProviderInstanceBinding) injector.getBinding(Integer.class);
    assertEquals(1, injectorBinding.getUserSuppliedProvider().get());

    ProviderInstanceBinding moduleBinding =
        (ProviderInstanceBinding) Iterables.getOnlyElement(Elements.getElements(module));
    try {
      moduleBinding.getUserSuppliedProvider().get();
      fail();
    } catch (IllegalStateException ise) {
      assertEquals(
          "This Provider cannot be used until the Injector has been created.", ise.getMessage());
    }
  }
  @Override
  public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
    Surface s = new Surface(surfaceTexture);

    try {
      mMediaPlayer = new MediaPlayer();
      mMediaPlayer.setDataSource(mContext, mVideoUri);
      mMediaPlayer.setSurface(s);
      mMediaPlayer.prepare();
      mMediaPlayer.setOnBufferingUpdateListener(this);
      mMediaPlayer.setOnCompletionListener(this);
      mMediaPlayer.setOnPreparedListener(this);
      mMediaPlayer.setOnVideoSizeChangedListener(this);
      mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
      mMediaPlayer.seekTo(0);
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (SecurityException e) {
      e.printStackTrace();
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    /*
    if ( mMediaPlayer != null ) {
       mSeekBar.setProgress( 0 );
       mSeekBar.setMax( mMediaPlayer.getDuration() );
       mVideoTextureView.SetVideoSize( mMediaPlayer.getVideoWidth(), mMediaPlayer.getVideoHeight() );
    }

    */
  }
  @Override
  protected ModelAndView onSubmit(
      HttpServletRequest request,
      HttpServletResponse response,
      Object command,
      BindException errors)
      throws Exception {

    SysMsgCommand msgCmd = (SysMsgCommand) command;
    log.info("SysMsgDetailController:onSubmit called.");

    NotificationDto sysMessage = msgCmd.getMsg();
    String btn = request.getParameter("btn");
    if ("delete".equalsIgnoreCase(btn)) {
      if (sysMessage.getType() == NotificationType.SYSTEM) {
        return null;
      }
      sysMessageService.removeMessage(sysMessage.getMsgId());
      ModelAndView mav = new ModelAndView("/deleteconfirm");
      mav.addObject("msg", "Location has been successfully deleted.");
      return mav;
    } else {
      if (msgCmd.getTemplateMethod() == 0) {
        MultipartFile providerScriptFile = msgCmd.getProviderScriptFile();
        String providerScriptFileName = "";
        if (providerScriptFile != null && providerScriptFile.getSize() > 0) {
          providerScriptFileName = providerScriptFile.getOriginalFilename();
          String filePath = res.getString("scriptRoot") + "/msgprovider/" + providerScriptFileName;
          File dest = new File(filePath);
          try {
            providerScriptFile.transferTo(dest);
            sysMessage.setProviderScriptName(providerScriptFileName);
            sysMessage.setMailTemplate(null);
          } catch (IllegalStateException e) {
            e.printStackTrace();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      } else {
        MailTemplateDto mailTemplateDto =
            mailTemplateWebService
                .getTemplateById(msgCmd.getSelectedTemplateId())
                .getMailTemplate();
        sysMessage.setMailTemplate(mailTemplateDto);
        sysMessage.setProviderScriptName(null);
      }

      if (StringUtils.isEmpty(sysMessage.getMsgId())) {
        sysMessageService.addMessage(sysMessage);
      } else {
        sysMessageService.updateMessage(sysMessage);
      }
    }

    ModelAndView mav = new ModelAndView(new RedirectView(redirectView, true));
    mav.addObject("sysMsgCmd", msgCmd);

    return mav;
  }
  @Test
  public void testDeleteAssignment() {
    final EntityKind entityKind = EntityKind.EXPERIMENT;
    final ExperimentTypePE experimentType = createExperimentType();
    final PropertyTypePE propertyType = createPropertyType();
    final ExperimentTypePropertyTypePE etpt = new ExperimentTypePropertyTypePE();
    prepareExperimentTypeAndPropertyType(entityKind, experimentType, propertyType);
    context.checking(
        new Expectations() {
          {
            one(entityPropertyTypeDAO).tryFindAssignment(experimentType, propertyType);
            will(returnValue(etpt));

            one(entityPropertyTypeDAO).delete(etpt);
          }
        });

    IEntityTypePropertyTypeBO bo = createEntityTypePropertyTypeBO(entityKind);
    bo.loadAssignment(propertyType.getCode(), experimentType.getCode());
    bo.deleteLoadedAssignment();

    try {
      bo.getLoadedAssignment();
      fail("IllegalStateException expected.");
    } catch (IllegalStateException e) {
      assertEquals("No assignment loaded.", e.getMessage());
    }
    context.assertIsSatisfied();
  }