@Test
  @SuppressWarnings("unchecked")
  public void testDoWithRetry_ReadTimeOut() throws Exception {
    AmazonElasticMapReduceCustomClient client =
        new AmazonElasticMapReduceCustomClient("dummy", "dummy");
    client.setRequestInterval(100);

    Callable callable = mock(Callable.class);
    AmazonClientException exception =
        new AmazonClientException("Unable to execute HTTP request: Read timed out");
    when(callable.call()).thenThrow(exception, exception, exception).thenReturn(new Object());

    long startTime = System.currentTimeMillis();
    Object result = client.doThrottleSafe(callable);
    assertNotNull(result);
    assertThat(
        (System.currentTimeMillis() - startTime),
        greaterThanOrEqualTo(3 * client.getRequestInterval()));

    // now exceed retries
    client.setMaxRetriesOnConnectionErrors(2);
    when(callable.call()).thenThrow(exception, exception, exception).thenReturn(new Object());
    try {
      client.doThrottleSafe(callable);
      fail("should throw exception");
    } catch (Exception e) {
      assertSame(exception, e);
    }
  }
Esempio n. 2
0
 public T call() throws Exception {
   final T result1 = step1.call();
   if (result1.isSuccess() && !Thread.currentThread().isInterrupted()) {
     return step2.call();
   } else {
     return result1;
   }
 }
  @Override
  public <T> T withTransaction(Callable<T> command, Atomic atomic) throws Exception {
    if (transaction != null) return command.call();

    try {
      T ret = null;
      begin();
      ret = command.call();
      commit();
      return ret;
    } catch (Exception e) {
      rollback();
      throw e;
    }
  }
 public static void waitUntil(
     Callable<Boolean> evaluate, long timeout, Callable<String> errorMessage) {
   long startTime = System.currentTimeMillis();
   try {
     while (!evaluate.call()) {
       Thread.yield();
       if (System.currentTimeMillis() - timeout > startTime) {
         fail(errorMessage.call());
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
     fail(e.getMessage());
   }
 }
Esempio n. 5
0
  /**
   * Start probing, waiting for {@code condition} to become true.
   *
   * <p>
   *
   * <p>This method is blocking: It returns when condition becomes true or throws an exception if
   * timeout is reached.
   *
   * @param timeoutInMs wait time in milliseconds
   */
  public void probe(long timeoutInMs) {
    long start = System.nanoTime();

    try {
      while (!condition.call() && (elapsedMs(start) < timeoutInMs)) {
        Thread.yield();
      }

      if (!condition.call()) {
        throw new IllegalStateException("probe condition not true after " + timeoutInMs);
      }
    } catch (Exception e) {
      throw propagate(e);
    }
  }
  public static void registerCallback(Callable<?> callable) {
    List<List<Callable<?>>> callbackListList = _callbackListListThreadLocal.get();

    if (callbackListList.isEmpty()) {

      // Not within a transaction boundary and should only happen during
      // an upgrade or verify process. See
      // DBUpgrader#_disableTransactions.

      try {
        callable.call();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    } else {
      int index = callbackListList.size() - 1;

      List<Callable<?>> callableList = callbackListList.get(index);

      if (callableList == Collections.<Callable<?>>emptyList()) {
        callableList = new ArrayList<>();

        callbackListList.set(index, callableList);
      }

      callableList.add(callable);
    }
  }
Esempio n. 7
0
 public T parseNotation(Object notation) {
   if (notation == null) {
     return null;
   }
   if (notation instanceof CharSequence
       || notation instanceof Number
       || notation instanceof Boolean) {
     return (T) notation.toString();
   }
   if (notation instanceof Closure) {
     final Closure closure = (Closure) notation;
     final Object called = closure.call();
     return parseNotation(called);
   }
   if (notation instanceof Callable) {
     try {
       final Callable callableNotation = (Callable) notation;
       final Object called = callableNotation.call();
       return parseNotation(called);
     } catch (Exception e) {
       throw UncheckedException.throwAsUncheckedException(e);
     }
   }
   DeprecationLogger.nagUserOfDeprecated(
       String.format(
           "Converting class %s to path using toString() method", notation.getClass().getName()),
       "Please use java.io.File, java.lang.CharSequence, java.lang.Number, java.util.concurrent.Callable or groovy.lang.Closure");
   return (T) notation.toString();
 }
  /**
   * Calls the Callable and returns the value it returns. If an exception occurs, it is logged and a
   * new non-chained exception is thrown.
   *
   * @param <T> return type
   * @param callable code to call
   * @param message verbose description of operation
   * @return return value of Callable
   */
  private <T> T callLogThrow(final Callable<T> callable, final String message) {
    try {
      return callable.call();
    } catch (Exception e) {
      // generate reference #
      String refNum = UUID.randomUUID().toString();
      if (logger.isDebugEnabled()) {
        logger.debug(
            Messages.getInstance().getString("ExceptionLoggingDecorator.referenceNumber", refNum),
            e); //$NON-NLS-1$
      }

      // list all exceptions in stack
      @SuppressWarnings("unchecked")
      List<Throwable> throwablesInStack = ExceptionUtils.getThrowableList(e);
      // reverse them so most specific exception (root cause) comes first
      Collections.reverse(throwablesInStack);

      for (Throwable t : throwablesInStack) {
        String className = t.getClass().getName();
        if (exceptionConverterMap.containsKey(className)) {
          throw exceptionConverterMap
              .get(className)
              .convertException((Exception) t, message, refNum);
        }
      }

      // no converter; throw general exception
      throw new UnifiedRepositoryException(
          Messages.getInstance()
              .getString(
                  "ExceptionLoggingDecorator.generalException", message, refNum)); // $NON-NLS-1$
    }
  }
Esempio n. 9
0
    // for now, caching as long as the loader remains the same,
    // drop entire cache if it changes.
    synchronized Config getOrElseUpdate(ClassLoader loader, String key, Callable<Config> updater) {
      if (loader != currentLoader) {
        // reset the cache if we start using a different loader
        cache.clear();
        currentLoader = loader;
      }

      Config systemProperties = systemPropertiesAsConfig();
      if (systemProperties != currentSystemProperties) {
        cache.clear();
        currentSystemProperties = systemProperties;
      }

      Config config = cache.get(key);
      if (config == null) {
        try {
          config = updater.call();
        } catch (RuntimeException e) {
          throw e; // this will include ConfigException
        } catch (Exception e) {
          throw new ConfigException.Generic(e.getMessage(), e);
        }
        if (config == null) throw new ConfigException.BugOrBroken("null config from cache updater");
        cache.put(key, config);
      }

      return config;
    }
 /**
  * <a
  * href="http://sourceforge.net/tracker/?func=detail&aid=2081602&group_id=4075&atid=104075">Sourceforge
  * issue "NullPointerException Thrown by Overriden Method" - ID: 2081602</a>. Overriding a method
  * which is invoked from super-constructor issues a NPE.
  */
 @Test
 @Category(KnownIssue.class)
 public void sourceforge_issue_2081602() throws Exception {
   // Interpreter.DEBUG = true;
   Callable result =
       (Callable)
           TestUtil.eval(
               "Object echo(msg, x) {",
               "   print(msg + ' ' + x);",
               "   return x;",
               "}",
               "public class A implements " + Callable.class.getName() + " {",
               "   int _id;",
               "   public A (int id) {",
               "      print (\" A.<init> \" + id);",
               "      setId(id);",
               "   }",
               "   public void setId (int id) {",
               "      print (\" A.setId \" + id);",
               "      _id = id;",
               "   }",
               "   public Object call() { return _id; }",
               "}",
               "public class B extends A {",
               "   public B (int id) {",
               "      super (echo(\" B.<init>\", id * 3));",
               "   }",
               "   public void setId (int id) {",
               "      print (\" B.setId \" + id);",
               "      super.setId(id * 5);",
               "   }",
               "}",
               "return new B (1);");
   Assert.assertEquals(15, result.call());
 }
Esempio n. 11
0
  @CheckForNull
  public synchronized byte[] get(@Nonnull String obj, @Nullable Callable<byte[]> valueLoader)
      throws Exception {
    String key = getKey(obj);

    try {
      lock();
      if (!forceUpdate) {
        byte[] cached = getCache(key);

        if (cached != null) {
          log.debug("cache hit for " + obj + " -> " + key);
          return cached;
        }

        log.debug("cache miss for " + obj + " -> " + key);
      } else {
        log.debug("cache force update for " + obj + " -> " + key);
      }

      if (valueLoader != null) {
        byte[] value = valueLoader.call();
        if (value != null) {
          putCache(key, value);
        }
        return value;
      }
    } finally {
      unlock();
    }

    return null;
  }
Esempio n. 12
0
        @Override
        protected void doSessionOpened(final HttpSession createSession) throws Exception {
          Callable<WsebSession> sessionFactory = WSE_SESSION_FACTORY_KEY.remove(createSession);
          final WsebSession wsebSession = sessionFactory.call();

          // clean up session map
          wsebSession
              .getCloseFuture()
              .addListener(
                  new IoFutureListener<CloseFuture>() {
                    @Override
                    public void operationComplete(CloseFuture future) {
                      ResourceAddress readAddress = wsebSession.getReadAddress();
                      if (readAddress != null) {
                        sessionMap.remove(readAddress);
                      }

                      ResourceAddress writeAddress = wsebSession.getWriteAddress();
                      if (writeAddress != null) {
                        sessionMap.remove(writeAddress);
                      }

                      if (wsebSession.getInactivityTimeout() > 0) {
                        currentSessionInactivityTracker.get().removeSession(wsebSession);
                      }

                      // handle exception during create response
                      createSession.close(false);
                    }
                  });

          // store created session to process during session close, or exception
          WSE_SESSION_KEY.set(createSession, wsebSession);
          WSE_CONNECT_FUTURE_KEY.remove(createSession);
        }
Esempio n. 13
0
 /**
  * Adds a Crashreport section with the given name with the value set to the result of the given
  * Callable;
  */
 public void addCrashSectionCallable(String par1Str, Callable par2Callable) {
   try {
     this.addCrashSection(par1Str, par2Callable.call());
   } catch (Throwable var4) {
     this.addCrashSectionThrowable(par1Str, var4);
   }
 }
Esempio n. 14
0
 protected RequestHandler runForward(
     final int index,
     final HttpServletRequest request,
     final HttpServletResponse response,
     final Callable<RequestHandler> last)
     throws Exception {
   if (index < this.interceptors.length) {
     return this.interceptors[index].before(
         this.controller,
         this.m,
         request,
         response,
         (chainReq, chainRes) -> {
           try {
             return runForward(index + 1, chainReq, chainRes, last);
           } catch (final RuntimeException e) {
             throw e;
           } catch (final Exception e) {
             throw new RuntimeException(e);
           }
         });
   } else {
     return last.call();
   }
 }
Esempio n. 15
0
  /** Performs the given operations on a clean git repository */
  protected <T> T gitOperation(PersonIdent personIdent, Callable<T> callable) {
    synchronized (lock) {
      try {
        // lets check if we have done a commit yet...
        boolean hasHead = true;
        try {
          git.log().all().call();
        } catch (NoHeadException e) {
          hasHead = false;
        }

        // TODO pull if we have a remote repo

        if (hasHead) {
          // lets stash any local changes just in case..
          git.stashCreate()
              .setPerson(personIdent)
              .setWorkingDirectoryMessage("Stash before a write")
              .setRef("HEAD")
              .call();
        }
        return callable.call();
      } catch (Exception e) {
        throw new RuntimeIOException(e);
      }
    }
  }
    @Theory
    public void shouldHold(@ForAll Callable<Integer> c) throws Exception {
      ++iterations;

      Integer value = functionValue(new IntegerGenerator(), null);
      for (int i = 0; i < 10000; ++i) assertEquals(value, c.call());
    }
Esempio n. 17
0
  /**
   * Spin through to attempt to replace any dead/missing workers. WorkerFactory is not required to
   * return a worker. (This is mostly useful when the workers are tied to limited resources.)
   */
  public void checkWorkers() {
    for (int i = 0; i < maxWorkerCount; i++) {
      if (!paused && (workerThreads[i] == null || !workerThreads[i].isAlive())) {
        Worker worker;
        try {
          worker = workerFactory.call();
        } catch (Exception e) {
          throw new RuntimeException("Failed to get a worker from the workerFactory", e);
        }
        if (worker != null) {
          log.info(
              "Started worker(s) of type '{}' with queues: '{}'",
              worker.getName(),
              worker.getQueues());

          Thread workerThread = new Thread(worker);
          workerThread.setDaemon(false);
          workerThread.start();

          workers[i] = worker;
          workerThreads[i] = workerThread;
        }
      }
    }
  }
 private void assertActionShouldProduce(String expected, Callable<byte[]> action) {
   try {
     assertEquals("Wrong result,", expected, new String(action.call(), "UTF-8"));
   } catch (Exception e) {
     fail(e.getMessage());
   }
 }
Esempio n. 19
0
 @SneakyThrows
 public static <T> Result<T> time(Callable<T> callable) {
   long start = System.currentTimeMillis();
   T result = callable.call();
   long total = System.currentTimeMillis() - start;
   return new Result<>(result, total);
 }
Esempio n. 20
0
 private static void run(Callable c, boolean read, int size) {
   // Count all i/o time from here, including all retry overheads
   long start_io_ms = System.currentTimeMillis();
   while (true) {
     try {
       long start_ns = System.nanoTime(); // Blocking i/o call timing - without counting repeats
       c.call();
       TimeLine.record_IOclose(start_ns, start_io_ms, read ? 1 : 0, size, Value.HDFS);
       break;
       // Explicitly ignore the following exceptions but
       // fail on the rest IOExceptions
     } catch (EOFException e) {
       ignoreAndWait(e, false);
     } catch (SocketTimeoutException e) {
       ignoreAndWait(e, false);
     } catch (S3Exception e) {
       // Preserve S3Exception before IOException
       // Since this is tricky code - we are supporting different HDFS version
       // New version declares S3Exception as IOException
       // But old versions (0.20.xxx) declares it as RuntimeException
       // So we have to catch it before IOException !!!
       ignoreAndWait(e, false);
     } catch (IOException e) {
       ignoreAndWait(e, true);
     } catch (Exception e) {
       throw Log.errRTExcept(e);
     }
   }
 }
Esempio n. 21
0
  @EventHandler
  public void asyncChatTrigger(final AsyncPlayerChatEvent event) {
    if (event.isCancelled()) return;

    // Return if "Use asynchronous event" is false in config file
    if (!Settings.ChatAsynchronous()) return;

    Callable<Boolean> call =
        new Callable<Boolean>() {
          public Boolean call() {
            return process(event.getPlayer(), event.getMessage());
          }
        };

    Boolean cancelled = false;

    try {
      cancelled =
          event.isAsynchronous()
              ? Bukkit.getScheduler().callSyncMethod(DenizenAPI.getCurrentInstance(), call).get()
              : call.call();
    } catch (InterruptedException e) {
      // dB.echoError(e);
    } catch (ExecutionException e) {
      dB.echoError(e);
    } catch (Exception e) {
      dB.echoError(e);
    }

    event.setCancelled(cancelled);
  }
Esempio n. 22
0
 /**
  * Method invoked to optionally run the given {@link Callable} on behalf of a {@link RunContext}.
  */
 @Internal
 protected <T> T handle(
     final MessageContext messageContext, final String method, final Callable<T> callable) {
   try {
     if (m_handlerRunContextProducer == null) {
       return callable.call();
     } else {
       final Subject subject = MessageContexts.getSubject(messageContext, HANDLER_SUBJECT);
       return m_handlerRunContextProducer
           .produce(subject)
           .call(
               new Callable<T>() {
                 @Override
                 public T call() throws Exception {
                   return callable.call();
                 }
               },
               DefaultExceptionTranslator.class);
     }
   } catch (final Exception e) {
     LOG.error(
         "Failed to handle message [handler={}, method={}, inbound={}]",
         m_handler.getClass().getName(),
         method,
         MessageContexts.isInboundMessage(messageContext),
         e);
     throw new HTTPException(
         HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // do not send cause to the client
   }
 }
 @Override
 public <T> T run(Callable<T> r) {
   T result = null;
   try {
     synchronized (store) {
       result = r.call();
       File temp = new File(store.getParentFile(), "temp_" + store.getName());
       FileOutputStream file = new FileOutputStream(temp);
       ObjectOutputStream out = new ObjectOutputStream(file);
       out.writeObject(properties);
       out.writeObject(maps);
       out.flush();
       out.close();
       file.flush();
       file.close();
       Files.move(
           temp.toPath(),
           store.toPath(),
           StandardCopyOption.ATOMIC_MOVE,
           StandardCopyOption.REPLACE_EXISTING);
     }
   } catch (Exception e) {
     // If something happened here, that is a serious bug so we need to assert.
     throw Assert.failure("Failure flushing FlatFileKeyValueStorage", e);
   }
   return result;
 }
 protected Object withTx(int cacheIndex, Callable<Object> c) throws Exception {
   if (txEnabled) {
     return TestingUtil.withTx(cache(cacheIndex).getAdvancedCache().getTransactionManager(), c);
   } else {
     return c.call();
   }
 }
Esempio n. 25
0
 public void func_71500_a(String p_71500_1_, Callable p_71500_2_) {
   try {
     this.func_71507_a(p_71500_1_, p_71500_2_.call());
   } catch (Throwable var4) {
     this.func_71499_a(p_71500_1_, var4);
   }
 }
 private void changeSchema(Callable<Void> callable) throws MessageQueueException {
   for (int i = 0; i < 3; i++) {
     try {
       callable.call();
       try {
         Thread.sleep(SCHEMA_CHANGE_DELAY);
       } catch (InterruptedException ie) {
         Thread.currentThread().interrupt();
         throw new MessageQueueException(
             "Interrupted while trying to create column family for queue " + getName(), ie);
       }
       return;
     } catch (SchemaDisagreementException e) {
       try {
         Thread.sleep(SCHEMA_CHANGE_DELAY);
       } catch (InterruptedException ie) {
         Thread.currentThread().interrupt();
         throw new MessageQueueException(
             "Interrupted while trying to create column family for queue " + getName(), ie);
       }
     } catch (Exception e) {
       if (e.getMessage().contains("already exist")) return;
       throw new MessageQueueException(
           "Failed to create column family for " + queueColumnFamily.getName(), e);
     }
   }
 }
Esempio n. 27
0
 private void invoke(Iterable<Callable<?>> actions) throws Exception {
   if (actions != null) {
     for (Callable<?> action : actions) {
       action.call();
     }
   }
 }
Esempio n. 28
0
 public void initContainer() throws Exception {
   if (launchConfig == null) {
     launchConfig = launchConfigLoader.call();
   }
   runtimeConfiguration =
       new StaticRuntimeConfiguration(launchConfig, configDatabaseLoader.call());
   runtimeConfiguration.setCurrentVersion(currentVersion);
   services =
       new NewConfigDesktopServiceFactory(
           runtimeConfiguration, new SqliteTransactionManager(connection));
   desktopServiceFactory = new CompositeServiceFactory();
   desktopServiceFactory.addServiceFactory(services);
   AfterburnerInjector.setConfigurationSource(key -> desktopServiceFactory.get((String) key));
   AfterburnerInjector.setInstanceSupplier(
       new RecursiveInjectionInstanceSupplier(desktopServiceFactory));
 }
 /**
  * Wrap the given service call with the {@link ConstantFlowRegulator} protection logic.
  *
  * @param c the {@link Callable} to attempt
  * @return whatever c would return on success
  * @throws FlowRateExceededException if the total requests per second through the flow regulator
  *     exceeds the configured value
  * @throws Exception if <code>c</code> throws one during execution
  */
 public <T> T invoke(Callable<T> c) throws Exception {
   if (canProceed()) {
     return c.call();
   } else {
     throw mapException(new FlowRateExceededException());
   }
 }
Esempio n. 30
0
  private void runJava(PrintStream out, PrintStream err) {
    Binding.out = out;
    Binding.err = err;
    Binding.ctx = bundle.getBundleContext();

    try {
      Callable<?> callable =
          javacService.compileJavaSnippet(code, classLoaderContext, err).orElse(ERROR);

      if (callable != ERROR) {
        Object result = callable.call();

        if (result != null) {
          out.println(result);
        }

        code.commit();
      } else {
        code.abort();
      }
    } catch (Throwable e) {
      code.abort();
      e.printStackTrace(err);
    }
  }