@Override
  public Feedback run() {
    isRunning.set(true);

    try {
      String persistenceMode =
          getMapping().getSettingValue(Constants.Misc.SETTING_PERSISTENCE_MODE);
      Database database = DatabaseFactory.createDatabase(persistenceMode);
      EasyTravelConfig cfg = EasyTravelConfig.read();

      boolean randomContent = true;
      // disable random content if disabled by setting
      String value = getMapping().getSettingValue("randomContent");
      if (Boolean.FALSE.toString().equalsIgnoreCase(value)) {
        LOGGER.info(
            "Not creating random content in database because it is disabled via setting 'randomContent=false'");
        randomContent = false;
      }

      try {
        database.createContents(cfg, randomContent);
      } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Setting up the database content failed.", e);
        return Feedback.Failure;
      } finally {
        database.closeConnection();
      }
    } finally {
      isRunning.set(false);
    }

    return Feedback.Neutral;
  }
  @Test
  public void shouldCallFail() throws Exception {
    final AtomicBoolean timeoutCalled = new AtomicBoolean(false);
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);
    final GremlinExecutor gremlinExecutor =
        GremlinExecutor.build()
            .afterFailure((b, e) -> failureCalled.set(true))
            .afterSuccess((b) -> successCalled.set(true))
            .afterTimeout((b) -> timeoutCalled.set(true))
            .create();
    try {
      gremlinExecutor.eval("10/0").get();
      fail();
    } catch (Exception ignored) {
    }

    // need to wait long enough for the callback to register
    Thread.sleep(500);

    assertFalse(timeoutCalled.get());
    assertFalse(successCalled.get());
    assertTrue(failureCalled.get());
    gremlinExecutor.close();
  }
Пример #3
0
  @Override
  public int getInt(long i) {
    if (dataType() == Type.DOUBLE) {
      dirty.set(false);
      if (indexer instanceof DoubleIndexer) {
        return (int) ((DoubleIndexer) indexer).get(offset() + i);
      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return other.get(offset() + i);
      }
    } else if (dataType() == Type.INT) {
      dirty.set(false);
      if (indexer instanceof IntIndexer) {
        return ((IntIndexer) indexer).get(offset() + i);

      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return other.get(offset() + i);
      }
    } else {
      if (indexer instanceof FloatIndexer) {
        return (int) ((FloatIndexer) indexer).get(offset() + i);

      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return other.get(offset() + i);
      }
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mVolleyRequestQueue = Volley.newRequestQueue(getActivity());
    intilizeStatic();
    mMovieAdapter = new MovieAdapter(getActivity(), null, 0);
    trailerDataModified.set(false);
    reviewDataModified.set(false);
    movieDetailsModified.set(false);
    movieMinutesModified.set(false);

    if (savedInstanceState != null) {
      synchronized (mMovieId) {
        mMovieId = savedInstanceState.getLong(sMovieIdKey);
        YouTubeFirstTrailerURL = savedInstanceState.getParcelable("ShareYoutubeLinkKey");
        if (YouTubeFirstTrailerURL != null)
          if (mShareActionProvider != null) {
            mMenu.findItem(R.id.action_share).setVisible(true);
          } else Log.e(LOG_TAG, "mShareActionProvider not set");
        try {
          mMovieId.notifyAll();
        } catch (IllegalMonitorStateException x) {
        }
      }
      Bundle b = new Bundle();
      b.putLong(sMovieIdKey, mMovieId);
      getLoaderManager().restartLoader(MovieQuery.DETAIL_LOADER, b, this);
      getLoaderManager().restartLoader(TrailerQuery.TRAILER_LOADER, b, this);
      getLoaderManager().restartLoader(ReviewQuery.REVIEW_LOADER, b, this);
    }
  }
  public void handleStop() {
    if (timer != null) {
      timer.cancel();
    }
    animating.set(false);
    isStopping.set(true);

    if (loaderThread != null) {
      try {
        loaderThread.join();
      } catch (InterruptedException e) {
        Log.e(LCAT, "loaderThread termination interrupted");
      }
      loaderThread = null;
    }
    if (loader != null) {
      synchronized (loader) {
        loader.notify();
      }
    }

    loader = null;
    timer = null;
    animator = null;
    paused = false;

    fireStop();
  }
  private int runTest() throws Exception {
    LOG.info("Starting the test");

    String runtimeKey = String.format(RUN_TIME_KEY, this.getClass().getSimpleName());
    long runtime = util.getConfiguration().getLong(runtimeKey, DEFAULT_RUN_TIME);

    String numThreadKey = String.format(NUM_THREADS_KEY, this.getClass().getSimpleName());
    numThreads = util.getConfiguration().getInt(numThreadKey, DEFAULT_NUM_THREADS);

    ArrayList<Worker> workers = new ArrayList<>();
    for (int i = 0; i < numThreads; i++) {
      checkException(workers);
      Worker worker = new Worker();
      LOG.info("Launching worker thread " + worker.getName());
      workers.add(worker);
      worker.start();
    }

    Threads.sleep(runtime / 2);
    LOG.info("Stopping creating new tables");
    create_table.set(false);
    Threads.sleep(runtime / 2);
    LOG.info("Runtime is up");
    running.set(false);

    checkException(workers);

    for (Worker worker : workers) {
      worker.join();
    }
    LOG.info("All Worker threads stopped");

    // verify
    LOG.info("Verify actions of all threads succeeded");
    checkException(workers);
    LOG.info("Verify namespaces");
    verifyNamespaces();
    LOG.info("Verify states of all tables");
    verifyTables();

    // RUN HBCK

    HBaseFsck hbck = null;
    try {
      LOG.info("Running hbck");
      hbck = HbckTestingUtil.doFsck(util.getConfiguration(), false);
      if (HbckTestingUtil.inconsistencyFound(hbck)) {
        // Find the inconsistency during HBCK. Leave table and namespace undropped so that
        // we can check outside the test.
        keepObjectsAtTheEnd = true;
      }
      HbckTestingUtil.assertNoErrors(hbck);
      LOG.info("Finished hbck");
    } finally {
      if (hbck != null) {
        hbck.close();
      }
    }
    return 0;
  }
Пример #7
0
 @Override
 public final void add(final EventType elem) {
   do {
     if (isFreeLock.compareAndSet(true, false)) {
       final RokkaQueue<EventType> tq = actualRokkaQueueRef.get();
       if (tq.add(elem)) {
         boolean callSignalConsumer = false;
         if (signalEnabled.compareAndSet(true, false)) // && tq.getPosition() == 1
         {
           callSignalConsumer = true;
         }
         isFreeLock.set(true);
         if (callSignalConsumer) {
           signalConsumer.signal(this);
         }
         return;
       } else {
         isFreeLock.set(true);
         try {
           Thread.yield();
         } catch (Exception e) {
           e.printStackTrace();
         }
       }
     }
   } while (true);
 }
    public GremlinExecutor create() {
      final BasicThreadFactory threadFactory =
          new BasicThreadFactory.Builder().namingPattern("gremlin-executor-default-%d").build();

      final AtomicBoolean poolCreatedByBuilder = new AtomicBoolean();
      final AtomicBoolean suppliedExecutor = new AtomicBoolean(true);
      final AtomicBoolean suppliedScheduledExecutor = new AtomicBoolean(true);

      final ExecutorService es =
          Optional.ofNullable(executorService)
              .orElseGet(
                  () -> {
                    poolCreatedByBuilder.set(true);
                    suppliedExecutor.set(false);
                    return Executors.newScheduledThreadPool(4, threadFactory);
                  });
      executorService = es;

      final ScheduledExecutorService ses =
          Optional.ofNullable(scheduledExecutorService)
              .orElseGet(
                  () -> {
                    // if the pool is created by the builder and we need another just re-use it,
                    // otherwise create
                    // a new one of those guys
                    suppliedScheduledExecutor.set(false);
                    return (poolCreatedByBuilder.get())
                        ? (ScheduledExecutorService) es
                        : Executors.newScheduledThreadPool(4, threadFactory);
                  });
      scheduledExecutorService = ses;

      return new GremlinExecutor(this, suppliedExecutor.get(), suppliedScheduledExecutor.get());
    }
  public void testMightForkCheck() {
    final AtomicBoolean isSeccompInstalled = new AtomicBoolean();
    final AtomicBoolean mightFork = new AtomicBoolean();
    final BootstrapCheck.MightForkCheck check =
        new BootstrapCheck.MightForkCheck() {
          @Override
          boolean isSeccompInstalled() {
            return isSeccompInstalled.get();
          }

          @Override
          boolean mightFork() {
            return mightFork.get();
          }

          @Override
          public String errorMessage() {
            return "error";
          }
        };

    runMightForkTest(
        check,
        isSeccompInstalled,
        () -> mightFork.set(false),
        () -> mightFork.set(true),
        e -> assertThat(e.getMessage(), containsString("error")));
  }
Пример #10
0
 protected Object verifyArg(
     Class<?> clazz, Command command, String string, AtomicBoolean usedString) {
   if (Command.class == clazz) {
     usedString.set(false);
     return command;
   }
   if (string == null) throw new ArrayIndexOutOfBoundsException();
   usedString.set(true);
   if (Player.class == clazz) {
     return verifyPlayer(string);
   } else if (OfflinePlayer.class == clazz) {
     return verifyOfflinePlayer(string);
   } else if (String.class == clazz) {
     return string;
   } else if (Integer.class == clazz || int.class == clazz) {
     return verifyInteger(string);
   } else if (Boolean.class == clazz || boolean.class == clazz) {
     return Boolean.parseBoolean(string);
   } else if (Object.class == clazz) {
     return string;
   } else if (Float.class == clazz || float.class == clazz) {
     return verifyFloat(string);
   } else if (Double.class == clazz || double.class == clazz) {
     return verifyDouble(string);
   }
   return null;
 }
 void loginImpl() throws FriendException {
   synchronized (this) {
     try {
       loggingIn.set(true);
       connectionMulticaster.broadcast(
           new FriendConnectionEvent(this, FriendConnectionEvent.Type.CONNECTING));
       org.jivesoftware.smack.XMPPConnection.addConnectionCreationListener(
           smackConnectionListener);
       org.jivesoftware.smack.XMPPConnection.DEBUG_ENABLED = configuration.isDebugEnabled();
       connect();
       LOG.infof("connected.");
       LOG.infof(
           "logging in {0} with resource: {1} ...",
           configuration.getUserInputLocalID(), configuration.getResource());
       connection.login(
           configuration.getUserInputLocalID(),
           configuration.getPassword(),
           configuration.getResource());
       LOG.infof("logged in.");
       loggedIn.set(true);
       loggingIn.set(false);
       connectionMulticaster.broadcast(
           new FriendConnectionEvent(this, FriendConnectionEvent.Type.CONNECTED));
     } catch (org.jivesoftware.smack.XMPPException e) {
       handleLoginError(e);
       throw new FriendException(e);
     } catch (RuntimeException e) {
       handleLoginError(e);
       throw e;
     }
   }
 }
Пример #12
0
  public void close() {
    if (!real_socket.isClosed()) {
      synchronized (sinc_send_socket) {
        byte[] to_fin = new byte[Pacote.head_payload];
        OperacoesBinarias.inserirCabecalho(to_fin, 0, 0, false, false, false, true, 0, 0);
        DatagramPacket packet;
        if (is_server) {
          packet = new DatagramPacket(to_fin, Pacote.head_payload, client_adress, client_port);
        } else {
          packet = new DatagramPacket(to_fin, Pacote.head_payload, server_adress, server_port);
        }

        try {
          for (int i = 0; i < max_win && !real_socket.isClosed(); i++) {
            real_socket.send(packet);
          }
        } catch (IOException e) {
          System.out.println("Problema com socket interno");
          System.out.println("Fechando conexão...");
          close.set(true);
          e.printStackTrace();
        }
      }
      close.set(true);
      real_socket.close();
    }
  }
Пример #13
0
  private void doRegisterBookie(final String regPath) throws IOException {
    if (null == zk) {
      // zookeeper instance is null, means not register itself to zk
      return;
    }

    zkRegistered.set(false);

    // ZK ephemeral node for this Bookie.
    try {
      if (!checkRegNodeAndWaitExpired(regPath)) {
        // Create the ZK ephemeral node for this Bookie.
        zk.create(regPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        LOG.info("Registered myself in ZooKeeper at {}.", regPath);
      }
      zkRegistered.set(true);
    } catch (KeeperException ke) {
      LOG.error("ZK exception registering ephemeral Znode for Bookie!", ke);
      // Throw an IOException back up. This will cause the Bookie
      // constructor to error out. Alternatively, we could do a System
      // exit here as this is a fatal error.
      throw new IOException(ke);
    } catch (InterruptedException ie) {
      LOG.error("ZK exception registering ephemeral Znode for Bookie!", ie);
      // Throw an IOException back up. This will cause the Bookie
      // constructor to error out. Alternatively, we could do a System
      // exit here as this is a fatal error.
      throw new IOException(ie);
    }
  }
Пример #14
0
  @Override
  public void run() {
    this.reactorThread = Thread.currentThread();
    Thread.currentThread()
        .setName("BS REACTOR THREAD#" + BsThreadPool.BOSS_COUNT.getAndIncrement());

    for (; ; ) {
      try {
        dealTaskQueue();
        wakenUp.set(false);
        int selected = nioSelector.select(selectTime);
        wakenUp.set(true);
        if (selected == 0) {
          continue;
        }
        processSelectedKeys();
      } catch (IOException exc) {
        // TODO
        // logger.warn("Unexpected exception in the selector loop.", t);

        // Prevent possible consecutive immediate failures that lead to
        // excessive CPU consumption.
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          // Ignore.
        }
      }
    }
  }
Пример #15
0
  /** Run the bollie thread */
  @Override
  public void run() {
    golfBall[] ballsCollected; // Array to hold the balls bollie collects
    while (done.get() != true) { // Check that Range has not closed
      try {
        sleep(waitTime.nextInt(5000) + 2000); // Sleep for 2-7 seconds
        if (done.get() != true) { // Recheck condition for closing, just in case!
          bollieOnField.set(true); // Set Atomic boolean to true
          System.out.println("*********** Bollie collecting balls   ************");
          ballsCollected =
              sharedField
                  .collectAllBallsFromField(); // Collect balls, no golfers allowed to swing while
          // this is happening

          semaphore.drainPermits(); // drain permits so that golfers must wait
          System.out.println(
              "*********** Bollie collected " + ballsCollected.length + " balls ************");

          sleep(1000); // Simulate collecting and adding
          sharedStash.addBallsToStash(ballsCollected); // Add collected balls to stash
          semaphore.release(
              noGolfers); // Release semaphore and all waiting threads, so that golfers waiting can
          // continue to their next swing
          bollieOnField.set(false); // Set Atomic boolean to false, condition no longer blocked
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    sharedStash.golfersGo();
  }
Пример #16
0
 private void pageOutput(OutputFormat format, List<String> fieldNames) throws IOException {
   try (Pager pager = Pager.create();
       Writer writer = createWriter(pager);
       OutputHandler handler = createOutputHandler(format, writer, fieldNames)) {
     if (!pager.isNullPager()) {
       // ignore the user pressing ctrl-C while in the pager
       ignoreUserInterrupt.set(true);
       Thread clientThread = Thread.currentThread();
       pager
           .getFinishFuture()
           .thenRun(
               () -> {
                 userAbortedQuery.set(true);
                 ignoreUserInterrupt.set(false);
                 clientThread.interrupt();
               });
     }
     handler.processRows(client);
   } catch (RuntimeException | IOException e) {
     if (userAbortedQuery.get() && !(e instanceof QueryAbortedException)) {
       throw new QueryAbortedException(e);
     }
     throw e;
   }
 }
Пример #17
0
 public synchronized void setInstanceDescriptor(UbaCoordinate ubaCoordinate, InstanceDescriptor id)
     throws Exception {
   InstanceDescriptor got = instanceDescriptor.get();
   if (got != null && !got.equals(id)) {
     instancePath.writeInstanceDescriptor(ubaCoordinate, id);
     ensureCerts(id);
     startupId.incrementAndGet();
     unexpectedRestartTimestamp.set(-1);
     redeploy.set(true);
     LOG.info("Instance changed from " + got + " to " + id);
   } else if (!instancePath.script("status").exists()) {
     startupId.incrementAndGet();
     unexpectedRestartTimestamp.set(-1);
     redeploy.set(true);
     LOG.info("Missing status script from " + got + " to " + id);
   }
   if (!redeploy.get()) {
     LOG.debug("Service:" + instancePath.toHumanReadableName() + " has NOT changed.");
   } else {
     instanceDescriptor.set(id);
   }
   if (id.restartTimestampGMTMillis > lastRestart.get()) {
     restartAtTimestamp.set(id.restartTimestampGMTMillis);
   }
 }
Пример #18
0
 public void setInactive(boolean local) {
   if (local) {
     localActive.set(false);
   } else {
     globalActive.set(false);
   }
 }
Пример #19
0
  /** {@inheritDoc} */
  public void destroy() {
    started.set(false);
    destroyed.set(true);
    releaseExternalResources();
    if (notifierFuture != null) {
      notifierFuture.cancel(true);
    }

    if (asyncWriteFuture != null) {
      asyncWriteFuture.cancel(true);
    }

    if (bc != null) {
      bc.destroy();
    }

    if (broadcasterCache != null) {
      broadcasterCache.stop();
    }
    resources.clear();
    broadcastOnResume.clear();
    messages.clear();
    asyncWriteQueue.clear();
    delayedBroadcast.clear();
    broadcasterCache = null;

    if (BroadcasterFactory.getDefault() != null) {
      BroadcasterFactory.getDefault().remove(this, name);
    }

    if (currentLifecycleTask != null) {
      currentLifecycleTask.cancel(true);
    }
  }
Пример #20
0
  public void _gotobattleVC() {
    d.set(false);
    Thread th =
        new Thread() {
          int i;

          @Override
          public void run() {
            for (i = 0; i < 11 && d.get(); i++) {
              try {
                runOnUiThread(
                    new Runnable() {
                      @Override
                      public void run() {
                        if (i == 10) _transdata();
                      }
                    });
                Thread.sleep(1000);
              } catch (Exception e) {

              }
            }
          }
        };
    d.set(true);
    th.start();
  }
Пример #21
0
  @Override
  public final boolean add(final EventType elem, final int timeOut) {
    long startTime = System.currentTimeMillis();

    do {
      if (isFreeLock.compareAndSet(true, false)) {
        final RokkaQueue<EventType> tq = actualRokkaQueueRef.get();
        if (tq.add(elem)) {
          boolean callSignalConsumer = false;
          if (signalEnabled.compareAndSet(true, false)) {
            callSignalConsumer = true;
          }
          isFreeLock.set(true);
          if (callSignalConsumer) {
            signalConsumer.signal(this);
          }
          return true;
        } else {
          isFreeLock.set(true);
          try {
            Thread.yield();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    } while (startTime + timeOut > System.currentTimeMillis());
    return false;
  }
Пример #22
0
  /// The watcher thread - from the Runnable interface.
  // This has to be pretty anal to avoid monitor lockup, lost
  // threads, etc.
  public synchronized void run() {
    Thread me = Thread.currentThread();
    me.setPriority(Thread.MAX_PRIORITY);

    ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
    startTimeInNs = threadMXBean.getCurrentThreadCpuTime();

    if (enabled.get()) {
      do {
        loop.set(false);
        try {
          wait(millis);
        } catch (InterruptedException e) {
        }
      } while (enabled.get() && loop.get());
    }

    if (enabled.get() && targetThread.isAlive()) {
      isDoneRunning.set(true);

      printThread();
      if (kill) {
        logger.warn(
            "Trying to kill thread with id:"
                + targetThread.getId()
                + " but did not as it can cause deadlocks etc.");
        // targetThread.interrupt();
        // targetThread.stop(); //Never kill thread - it can cause other problems
      }
      done();
      isDoneRunning.set(false);
    }
  }
Пример #23
0
  public void handleStart() {
    if (animator == null) {
      timer = new Timer();

      if (loader == null) {
        loader = new Loader();
        loaderThread = new Thread(loader);
        Log.d(TAG, "STARTING LOADER THREAD " + loaderThread + " for " + this, Log.DEBUG_MODE);
      }

      animator = new Animator(loader);
      if (!animating.get() && !loaderThread.isAlive()) {
        isStopping.set(false);
        loaderThread.start();
      }

      currentDuration = (int) getDuration();

      animating.set(true);
      fireStart();
      timer.schedule(animator, currentDuration, currentDuration);
    } else {
      resume();
    }
  }
Пример #24
0
  /**
   * Default constructor. The same as Android's MediaPlayer().
   *
   * <p>When done with the MediaPlayer, you should call {@link #release()}, to free the resources.
   * If not released, too many MediaPlayer instances may result in an exception.
   *
   * @param preferHWDecoder MediaPlayer will try to use hardware accelerated decoder if true
   */
  public MediaPlayer(Context ctx, boolean preferHWDecoder) {
    mContext = ctx;

    String LIB_ROOT = Vitamio.getLibraryPath();
    if (preferHWDecoder) {
      if (!NATIVE_OMX_LOADED.get()) {
        if (Build.VERSION.SDK_INT > 17) loadOMX_native(LIB_ROOT + "libOMX.18.so");
        else if (Build.VERSION.SDK_INT > 13) loadOMX_native(LIB_ROOT + "libOMX.14.so");
        else if (Build.VERSION.SDK_INT > 10) loadOMX_native(LIB_ROOT + "libOMX.11.so");
        else loadOMX_native(LIB_ROOT + "libOMX.9.so");
        NATIVE_OMX_LOADED.set(true);
      }
    } else {
      unloadOMX_native();
      NATIVE_OMX_LOADED.set(false);
    }

    Looper looper;
    if ((looper = Looper.myLooper()) != null) mEventHandler = new EventHandler(this, looper);
    else if ((looper = Looper.getMainLooper()) != null)
      mEventHandler = new EventHandler(this, looper);
    else mEventHandler = null;

    native_init();
  }
  @Test
  public void shouldTimeoutSleepingScript() throws Exception {
    final AtomicBoolean successCalled = new AtomicBoolean(false);
    final AtomicBoolean failureCalled = new AtomicBoolean(false);

    final CountDownLatch timeOutCount = new CountDownLatch(1);

    final GremlinExecutor gremlinExecutor =
        GremlinExecutor.build()
            .scriptEvaluationTimeout(250)
            .afterFailure((b, e) -> failureCalled.set(true))
            .afterSuccess((b) -> successCalled.set(true))
            .afterTimeout((b) -> timeOutCount.countDown())
            .create();
    try {
      gremlinExecutor.eval("Thread.sleep(1000);10").get();
      fail("This script should have timed out with an exception");
    } catch (Exception ex) {
      assertEquals(TimeoutException.class, ex.getCause().getClass());
    }

    assertTrue(timeOutCount.await(2000, TimeUnit.MILLISECONDS));

    assertFalse(successCalled.get());
    assertFalse(failureCalled.get());
    assertEquals(0, timeOutCount.getCount());
    gremlinExecutor.close();
  }
Пример #26
0
 @Override
 public void download(String url, OutputStream output) {
   Cookie cookie = new Cookie(".dmm.co.jp", SESSION_ID_KEY, sessionId, "/", null, false);
   HttpClient client = new HttpClient();
   client.getState().addCookie(cookie);
   GetMethod method = new GetMethod(url);
   try {
     downloding.set(true);
     client.executeMethod(method);
     InputStream input = method.getResponseBodyAsStream();
     try {
       IOUtils.copyLarge(input, output);
       byte[] buffer = new byte[4096];
       int n = 0;
       while (downloding.get() && -1 != (n = input.read(buffer))) {
         output.write(buffer, 0, n);
       }
       if (!downloding.get()) {
         LOGGER.warn("interrupted to download " + url);
       }
     } finally {
       IOUtils.closeQuietly(input);
     }
   } catch (IOException e) {
     throw new EgetException("failed to download " + url, e);
   } finally {
     downloding.set(false);
     method.releaseConnection();
   }
 }
Пример #27
0
  @Override
  public double getDouble(long i) {
    if (dataType() == Type.FLOAT) {
      dirty.set(false);
      if (indexer instanceof FloatIndexer) {
        return ((FloatIndexer) indexer).get(offset() + i);

      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return (double) other.get(offset() + i);
      }
    } else if (dataType() == Type.INT) {
      dirty.set(false);
      if (indexer instanceof IntIndexer) {
        return ((IntIndexer) indexer).get(offset() + i);

      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return (double) other.get(offset() + i);
      }
    } else {
      dirty.set(false);
      if (indexer instanceof DoubleIndexer) {
        return ((DoubleIndexer) indexer).get(offset() + i);

      } else {
        UByteRawIndexer other = (UByteRawIndexer) indexer;
        return (double) other.get(offset() + i);
      }
    }
  }
  private boolean displaySlideup(Slideup slideup) {
    final View slideupView = getSlideupViewFactory().createSlideupView(mActivity, slideup);

    if (slideupView == null) {
      Log.e(
          TAG,
          "The slideup view returned from the ISlideupViewFactory was null. The slideup will "
              + "not be displayed and will not be put back on the stack.");
      mDisplayingSlideup.set(false);
      return false;
    }

    if (slideupView.getParent() != null) {
      Log.e(
          TAG,
          "The slideup view returned from the ISlideupViewFactory already has a parent. This "
              + "is a sign that the view is being reused. The ISlideupViewFactory method createSlideupView"
              + "must return a new view without a parent. The slideup will not be displayed and will not "
              + "be put back on the stack.");
      mDisplayingSlideup.set(false);
      return false;
    }

    mSlideupViewWrapper =
        new SlideupViewWrapper(slideupView, slideup, mSlideupViewLifecycleListener);
    FrameLayout root =
        (FrameLayout) mActivity.getWindow().getDecorView().findViewById(android.R.id.content);
    mSlideupViewWrapper.open(root);
    return true;
  }
Пример #29
0
  private void processBackgroundCallback(CuratorEvent event) throws Exception {
    String path = null;
    boolean nodeExists = false;
    if (event.getResultCode() == KeeperException.Code.NODEEXISTS.intValue()) {
      path = event.getPath();
      nodeExists = true;
    } else if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
      path = event.getName();
    } else if (event.getResultCode() == KeeperException.Code.NOAUTH.intValue()) {
      log.warn("Client does not have authorisation to write node at path {}", event.getPath());
      authFailure.set(true);
      return;
    }
    if (path != null) {
      authFailure.set(false);
      nodePath.set(path);
      watchNode();

      if (nodeExists) {
        client.setData().inBackground(setDataCallback).forPath(getActualPath(), getData());
      } else {
        initialisationComplete();
      }
    } else {
      createNode();
    }
  }
  private MapValue<V> removeInternal(K key, Optional<V> value, Optional<MapValue<V>> tombstone) {
    checkState(!destroyed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);
    checkNotNull(value, ERROR_NULL_VALUE);
    tombstone.ifPresent(v -> checkState(v.isTombstone()));

    counter.incrementCount();
    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<MapValue<V>> previousValue = new AtomicReference<>();
    items.compute(
        key,
        (k, existing) -> {
          boolean valueMatches = true;
          if (value.isPresent() && existing != null && existing.isAlive()) {
            valueMatches = Objects.equals(value.get(), existing.get());
          }
          if (existing == null) {
            log.trace("ECMap Remove: Existing value for key {} is already null", k);
          }
          if (valueMatches) {
            if (existing == null) {
              updated.set(tombstone.isPresent());
            } else {
              updated.set(!tombstone.isPresent() || tombstone.get().isNewerThan(existing));
            }
          }
          if (updated.get()) {
            previousValue.set(existing);
            return tombstone.orElse(null);
          } else {
            return existing;
          }
        });
    return previousValue.get();
  }