Пример #1
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);
    }
  }
Пример #2
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);
        }
Пример #3
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();
 }
Пример #4
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);
  }
  @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);
    }
  }
 /**
  * <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());
 }
Пример #7
0
 private void invoke(Iterable<Callable<?>> actions) throws Exception {
   if (actions != null) {
     for (Callable<?> action : actions) {
       action.call();
     }
   }
 }
Пример #8
0
 public T call() throws Exception {
   final T result1 = step1.call();
   if (result1.isSuccess() && !Thread.currentThread().isInterrupted()) {
     return step2.call();
   } else {
     return result1;
   }
 }
 @Test
 public void method_handle_to() throws Throwable {
   Method method_handle_to = moduleClass.getMethod("method_handle_to");
   Object result = method_handle_to.invoke(null);
   assertThat(result, instanceOf(Callable.class));
   Callable<?> callable = (Callable<?>) result;
   assertThat((String) callable.call(), is("ok"));
 }
Пример #10
0
 @SuppressWarnings("rawtypes")
 private Object getExtraContext(
     final Object testInstance, final Class<? extends Callable> providerClass) throws Exception {
   if (providerClass != null && providerClass != Callable.class) {
     final Callable<?> provider = ReflexUtils.instantiate(testInstance, providerClass);
     return provider.call();
   }
   return null;
 }
 @Override
 protected String toStringPollSource() {
   if (callable == null) return null;
   String cs = callable.toString();
   if (!cs.contains("" + Integer.toHexString(callable.hashCode()))) {
     return cs;
   }
   // if hashcode is in callable it's probably a custom internal; return class name
   return JavaClassNames.simpleClassName(callable);
 }
Пример #12
0
  public MessageExchange getMessageExchange(final String mexId) throws BpelEngineException {

    final MessageExchangeDAO inmemdao = getInMemMexDAO(mexId);

    Callable<MessageExchange> loadMex =
        new Callable<MessageExchange>() {

          public MessageExchange call() {
            MessageExchangeDAO mexdao =
                (inmemdao == null)
                    ? mexdao = _contexts.dao.getConnection().getMessageExchange(mexId)
                    : inmemdao;
            if (mexdao == null) return null;

            ProcessDAO pdao = mexdao.getProcess();
            ODEProcess process =
                pdao == null ? null : _registeredProcesses.get(pdao.getProcessId());

            if (process == null) {
              String errmsg = __msgs.msgProcessNotActive(pdao.getProcessId());
              __log.error(errmsg);
              // TODO: Perhaps we should define a checked exception for this
              // condition.
              throw new BpelEngineException(errmsg);
            }

            InvocationStyle istyle = mexdao.getInvocationStyle();
            if (istyle == InvocationStyle.RELIABLE || istyle == InvocationStyle.TRANSACTED)
              assertTransaction();

            switch (mexdao.getDirection()) {
              case MessageExchangeDAO.DIR_BPEL_INVOKES_PARTNERROLE:
                return process.createPartnerRoleMex(mexdao);
              case MessageExchangeDAO.DIR_PARTNER_INVOKES_MYROLE:
                return process.lookupMyRoleMex(mexdao);
              default:
                String errmsg =
                    "BpelEngineImpl: internal error, invalid MexDAO direction: " + mexId;
                __log.fatal(errmsg);
                throw new BpelEngineException(errmsg);
            }
          }
        };

    try {
      if (inmemdao != null || _contexts.isTransacted()) return loadMex.call();
      else return enqueueTransaction(loadMex).get();
    } catch (ContextException e) {
      throw new BpelEngineException(e);
    } catch (Exception e) {
      throw new BpelEngineException(e);
    }
  }
  @Test
  public void propagate_converter_failure() throws Exception {
    Callable<Object> callable = mock(Callable.class);
    when(callable.call()).thenThrow(new IllegalStateException("Need to cry"));

    List<Callable<Object>> callables = Lists.newArrayList(callable);
    try {
      new ViolationConverters(new Settings()).doExecute(new FakeTimerTask(), callables);
      fail();
    } catch (Exception e) {
      assertThat(ExceptionUtils.getRootCause(e).getMessage()).isEqualTo("Need to cry");
    }
  }
  @Test(expected = ApplicationTerminatedException.class)
  public void shouldThrowExceptionWhenApplicationHasTerminated() throws Exception {
    // Given
    given(execHandle.getState()).willReturn(ABORTED);
    task.exec();
    ArgumentCaptor<Callable> callableArgumentCaptor = ArgumentCaptor.forClass(Callable.class);
    verify(poller).awaitAtMost(anyInt(), any(TimeUnit.class), callableArgumentCaptor.capture());
    Callable callable = callableArgumentCaptor.getValue();

    // When
    callable.call();

    // Then exception is thrown
  }
Пример #15
0
 private static void demoSynchronousCallable() {
   Callable<String> getWiki =
       new Callable<String>() {
         public String call() throws Exception {
           return getContents("http://www.wikipedia.org/", 10);
         }
       };
   try {
     String homepage = getWiki.call();
     System.out.println(homepage);
   } catch (Exception exn) {
     throw new RuntimeException(exn);
   }
 }
  @Test
  public void shouldReturnFalseWhenApplicationIsNotReady() throws Exception {
    // Given
    task.exec();
    ArgumentCaptor<Callable> callableArgumentCaptor = ArgumentCaptor.forClass(Callable.class);
    verify(poller).awaitAtMost(anyInt(), any(TimeUnit.class), callableArgumentCaptor.capture());
    Callable<Boolean> callable = (Callable<Boolean>) callableArgumentCaptor.getValue();

    // When
    Boolean result = callable.call();

    // Then
    assertThat(result).isFalse();
  }
 /*     */ public void parse(final BeanT bean, CharSequence lexical)
     throws AccessorException, SAXException {
   /* 293 */ final String idref = WhiteSpaceProcessor.trim(lexical).toString();
   /* 294 */ final UnmarshallingContext context = UnmarshallingContext.getInstance();
   /*     */
   /* 296 */ final Callable callable = context.getObjectFromId(idref, this.acc.valueType);
   /* 297 */ if (callable == null)
   /*     */ {
     /* 299 */ context.errorUnresolvedIDREF(bean, idref, context.getLocator());
     /*     */ return;
     /*     */ }
   /*     */ Object t;
   /*     */ try {
     /* 305 */ t = callable.call();
     /*     */ } catch (SAXException e) {
     /* 307 */ throw e;
     /*     */ } catch (RuntimeException e) {
     /* 309 */ throw e;
     /*     */ } catch (Exception e) {
     /* 311 */ throw new SAXException2(e);
     /*     */ }
   /* 313 */ if (t != null) {
     /* 314 */ assign(bean, t, context);
     /*     */ }
   /*     */ else {
     /* 317 */ final LocatorEx loc = new LocatorEx.Snapshot(context.getLocator());
     /* 318 */ context.addPatcher(
         new Patcher() {
           /*     */ public void run() throws SAXException {
             /*     */ try {
               /* 321 */ Object t = callable.call();
               /* 322 */ if (t == null) /* 323 */ context.errorUnresolvedIDREF(bean, idref, loc);
               /*     */ else
                 /* 325 */ TransducedAccessor.IDREFTransducedAccessorImpl.this.assign(
                     bean, t, context);
               /*     */ }
             /*     */ catch (AccessorException e) {
               /* 328 */ context.handleError(e);
               /*     */ } catch (SAXException e) {
               /* 330 */ throw e;
               /*     */ } catch (RuntimeException e) {
               /* 332 */ throw e;
               /*     */ } catch (Exception e) {
               /* 334 */ throw new SAXException2(e);
               /*     */ }
             /*     */ }
           /*     */ });
     /*     */ }
   /*     */ }
Пример #18
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);
    }
  }
Пример #19
0
 private boolean invokeValve(final AtomicBoolean invokeValve) throws CacheAccessException {
   if (invokeValve == null || !invokeValve.get()) {
     return false;
   }
   invokeValve.set(false);
   Callable<Void> valve = this.valve;
   if (valve != null) {
     try {
       valve.call();
     } catch (Exception exception) {
       throw new CacheAccessException("Failed invoking valve", exception);
     }
   }
   return true;
 }
  @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());
   }
 }
Пример #22
0
 /**
  * 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());
   }
 }
Пример #23
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
   }
 }
Пример #24
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;
  }
Пример #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);
   }
 }
 @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;
 }
Пример #27
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);
   }
 }
Пример #28
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);
 }
Пример #29
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;
    }
  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);
    }
  }