Exemplo n.º 1
0
  @Override
  public void onApplicationStop() {

    List<Class> jobs = Play.classloader.getAssignableClasses(Job.class);

    for (final Class clazz : jobs) {
      // @OnApplicationStop
      if (clazz.isAnnotationPresent(OnApplicationStop.class)) {
        try {
          Job<?> job = ((Job<?>) clazz.newInstance());
          scheduledJobs.add(job);
          job.run();
          if (job.wasError) {
            if (job.lastException != null) {
              throw job.lastException;
            }
            throw new RuntimeException("@OnApplicationStop Job has failed");
          }
        } catch (InstantiationException e) {
          throw new UnexpectedException("Job could not be instantiated", e);
        } catch (IllegalAccessException e) {
          throw new UnexpectedException("Job could not be instantiated", e);
        } catch (Throwable ex) {
          if (ex instanceof PlayException) {
            throw (PlayException) ex;
          }
          throw new UnexpectedException(ex);
        }
      }
    }

    executor.shutdownNow();
    executor.getQueue().clear();
  }
Exemplo n.º 2
0
  private static void testPotato(
      Class<? extends Collection> implClazz, Class<? extends List> argClazz) throws Throwable {
    try {
      System.out.printf("implClazz=%s, argClazz=%s\n", implClazz.getName(), argClazz.getName());
      final int iterations = 100000;
      final List<Integer> list = (List<Integer>) argClazz.newInstance();
      final Integer one = Integer.valueOf(1);
      final List<Integer> oneElementList = Collections.singletonList(one);
      final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class);
      final Thread t =
          new CheckedThread() {
            public void realRun() {
              for (int i = 0; i < iterations; i++) {
                list.add(one);
                list.remove(one);
              }
            }
          };
      t.setDaemon(true);
      t.start();

      for (int i = 0; i < iterations; i++) {
        Collection<?> coll = constr.newInstance(list);
        Object[] elts = coll.toArray();
        check(elts.length == 0 || (elts.length == 1 && elts[0] == one));
      }
    } catch (Throwable t) {
      unexpected(t);
    }
  }
Exemplo n.º 3
0
  private void logEndpoints() {
    final StringBuilder stringBuilder = new StringBuilder(1024).append("\n\n");

    final ImmutableList.Builder<Class<?>> builder = ImmutableList.builder();
    for (Object o : config.getSingletons()) {
      if (o.getClass().isAnnotationPresent(Path.class)) {
        builder.add(o.getClass());
      }
    }
    for (Class<?> klass : config.getClasses()) {
      if (klass.isAnnotationPresent(Path.class)) {
        builder.add(klass);
      }
    }

    for (Class<?> klass : builder.build()) {
      final String path = klass.getAnnotation(Path.class).value();
      final ImmutableList.Builder<String> endpoints = ImmutableList.builder();
      for (AnnotatedMethod method : annotatedMethods(klass)) {
        for (HttpMethod verb : method.getMetaMethodAnnotations(HttpMethod.class)) {
          endpoints.add(
              String.format("    %-7s %s (%s)", verb.value(), path, klass.getCanonicalName()));
        }
      }

      for (String line : Ordering.natural().sortedCopy(endpoints.build())) {
        stringBuilder.append(line).append('\n');
      }
    }

    LOG.info(stringBuilder.toString());
  }
Exemplo n.º 4
0
  /**
   * Returns compact class host.
   *
   * @param obj Object to compact.
   * @return String.
   */
  @Nullable
  public static Object compactObject(Object obj) {
    if (obj == null) return null;

    if (obj instanceof Enum) return obj.toString();

    if (obj instanceof String || obj instanceof Boolean || obj instanceof Number) return obj;

    if (obj instanceof Collection) {
      Collection col = (Collection) obj;

      Object[] res = new Object[col.size()];

      int i = 0;

      for (Object elm : col) res[i++] = compactObject(elm);

      return res;
    }

    if (obj.getClass().isArray()) {
      Class<?> arrType = obj.getClass().getComponentType();

      if (arrType.isPrimitive()) {
        if (obj instanceof boolean[]) return Arrays.toString((boolean[]) obj);
        if (obj instanceof byte[]) return Arrays.toString((byte[]) obj);
        if (obj instanceof short[]) return Arrays.toString((short[]) obj);
        if (obj instanceof int[]) return Arrays.toString((int[]) obj);
        if (obj instanceof long[]) return Arrays.toString((long[]) obj);
        if (obj instanceof float[]) return Arrays.toString((float[]) obj);
        if (obj instanceof double[]) return Arrays.toString((double[]) obj);
      }

      Object[] arr = (Object[]) obj;

      int iMax = arr.length - 1;

      StringBuilder sb = new StringBuilder("[");

      for (int i = 0; i <= iMax; i++) {
        sb.append(compactObject(arr[i]));

        if (i != iMax) sb.append(", ");
      }

      sb.append("]");

      return sb.toString();
    }

    return U.compact(obj.getClass().getName());
  }
  /**
   * Constructs new instance of the specified class.
   *
   * @param exp Expected class for the new instance.
   * @param clsName Class name to create new instance for.
   * @param <T> Expected class type for the new instance.
   * @return New instance of specified class.
   * @throws GridClientException If loading failed.
   */
  private static <T> T newInstance(Class<T> exp, String clsName) throws GridClientException {
    Object obj;

    try {
      obj = Class.forName(clsName).newInstance();
    }
    // Catch all for convenience.
    catch (Exception e) {
      throw new GridClientException("Failed to create class instance: " + clsName, e);
    }

    return exp.cast(obj);
  }
Exemplo n.º 6
0
 /**
  * Log task mapped.
  *
  * @param log Logger.
  * @param clazz Task class.
  * @param nodes Mapped nodes.
  */
 public static void logMapped(
     @Nullable IgniteLogger log, Class<?> clazz, Collection<ClusterNode> nodes) {
   log0(
       log,
       U.currentTimeMillis(),
       String.format("[%s]: MAPPED: %s", clazz.getSimpleName(), U.toShortString(nodes)));
 }
Exemplo n.º 7
0
  private void logProviders() {
    final ImmutableSet.Builder<String> builder = ImmutableSet.builder();

    for (Class<?> klass : config.getClasses()) {
      if (klass.isAnnotationPresent(Provider.class)) {
        builder.add(klass.getCanonicalName());
      }
    }

    for (Object o : config.getSingletons()) {
      if (o.getClass().isAnnotationPresent(Provider.class)) {
        builder.add(o.getClass().getCanonicalName());
      }
    }

    LOG.debug("providers = {}", builder.build());
  }
  /**
   * Checks whether or not given class should be excluded from marshalling.
   *
   * @param cls Class to check.
   * @return {@code true} if class should be excluded, {@code false} otherwise.
   */
  public static boolean isExcluded(Class<?> cls) {
    assert cls != null;

    for (Class<?> c : INCL_CLASSES) {
      if (c.isAssignableFrom(cls)) {
        return false;
      }
    }

    for (Class<?> c : EXCL_CLASSES) {
      if (c.isAssignableFrom(cls)) {
        return true;
      }
    }

    return false;
  }
Exemplo n.º 9
0
 private void sendResponse(long requestId, Object value, Class<?> declaredType)
     throws IOException {
   DataOutputStream out = newFlusher();
   out.writeByte(RESPONSE);
   out.writeLong(requestId);
   if (value == null) {
     out.writeBoolean(false);
   } else {
     out.writeBoolean(true);
     Class<?> clazz = value.getClass();
     out.writeUTF(clazz.getName());
     Serializer<Object> s = serializerFor(clazz, declaredType);
     s.serialize(out, value);
   }
   out.writeBoolean(false);
   out.flush();
 }
Exemplo n.º 10
0
  private static void testImplementation(Class<? extends Collection> implClazz) throws Throwable {
    testPotato(implClazz, Vector.class);
    testPotato(implClazz, CopyOnWriteArrayList.class);

    final Constructor<? extends Collection> constr = implClazz.getConstructor(Collection.class);
    final Collection<Object> coll = constr.newInstance(Arrays.asList(new String[] {}));
    coll.add(1);
    equal(coll.toString(), "[1]");
  }
Exemplo n.º 11
0
  /**
   * Log finished.
   *
   * @param log Logger.
   * @param clazz Class.
   * @param start Start time.
   */
  public static void logFinish(@Nullable IgniteLogger log, Class<?> clazz, long start) {
    final long end = U.currentTimeMillis();

    log0(
        log,
        end,
        String.format(
            "[%s]: FINISHED, duration: %s", clazz.getSimpleName(), formatDuration(end - start)));
  }
Exemplo n.º 12
0
  public JxpSource getJxpServlet(String name) {
    JxpSource source = _httpServlets.get(name);
    if (source != null) return source;

    try {
      Class c = Class.forName(name);
      Object n = c.newInstance();
      if (!(n instanceof HttpServlet))
        throw new RuntimeException("class [" + name + "] is not a HttpServlet");

      HttpServlet servlet = (HttpServlet) n;
      servlet.init(createServletConfig(name));
      source = new ServletSource(servlet);
      _httpServlets.put(name, source);
      return source;
    } catch (Exception e) {
      throw new RuntimeException("can't load [" + name + "]", e);
    }
  }
Exemplo n.º 13
0
 /**
  * Searches the current debug scope, bottom up, for a context object that is an instance of a
  * given type. The first such object found is returned.
  */
 @SuppressWarnings("unchecked")
 public static <T> T contextLookup(Class<T> clazz) {
   if (ENABLED) {
     for (Object o : context()) {
       if (clazz.isInstance(o)) {
         return ((T) o);
       }
     }
   }
   return null;
 }
Exemplo n.º 14
0
 @SuppressWarnings("unchecked")
 static Class loadClass(String name, SolrCore core) throws ClassNotFoundException {
   try {
     return core != null ? core.getResourceLoader().findClass(name) : Class.forName(name);
   } catch (Exception e) {
     try {
       String n = DocBuilder.class.getPackage().getName() + "." + name;
       return core != null ? core.getResourceLoader().findClass(n) : Class.forName(n);
     } catch (Exception e1) {
       throw new ClassNotFoundException(
           "Unable to load "
               + name
               + " or "
               + DocBuilder.class.getPackage().getName()
               + "."
               + name,
           e);
     }
   }
 }
Exemplo n.º 15
0
  /**
   * Log message.
   *
   * @param log Logger.
   * @param msg Message to log.
   * @param clazz class.
   * @param start start time.
   * @return Time when message was logged.
   */
  public static long log(@Nullable IgniteLogger log, String msg, Class<?> clazz, long start) {
    final long end = U.currentTimeMillis();

    log0(
        log,
        end,
        String.format(
            "[%s]: %s, duration: %s", clazz.getSimpleName(), msg, formatDuration(end - start)));

    return end;
  }
Exemplo n.º 16
0
 @SuppressWarnings("unchecked")
 public static <T> List<T> contextSnapshot(Class<T> clazz) {
   if (ENABLED) {
     List<T> result = new ArrayList<>();
     for (Object o : context()) {
       if (clazz.isInstance(o)) {
         result.add((T) o);
       }
     }
     return result;
   } else {
     return Collections.emptyList();
   }
 }
Exemplo n.º 17
0
 public void connectToSource() throws Exception {
   // load JDBC driver
   c = Class.forName(config.jdbcdriver);
 }
Exemplo n.º 18
0
 /** {@inheritDoc} */
 @Override
 public ClassLoader classLoader() {
   return p2pCls.getClassLoader();
 }
Exemplo n.º 19
0
  @Override
  public void afterApplicationStart() {
    List<Class<?>> jobs = new ArrayList<Class<?>>();
    for (Class clazz : Play.classloader.getAllClasses()) {
      if (Job.class.isAssignableFrom(clazz)) {
        jobs.add(clazz);
      }
    }
    scheduledJobs = new ArrayList<Job>();
    for (final Class<?> clazz : jobs) {
      // @OnApplicationStart
      if (clazz.isAnnotationPresent(OnApplicationStart.class)) {
        // check if we're going to run the job sync or async
        OnApplicationStart appStartAnnotation = clazz.getAnnotation(OnApplicationStart.class);
        if (!appStartAnnotation.async()) {
          // run job sync
          try {
            Job<?> job = ((Job<?>) clazz.newInstance());
            scheduledJobs.add(job);
            job.run();
            if (job.wasError) {
              if (job.lastException != null) {
                throw job.lastException;
              }
              throw new RuntimeException("@OnApplicationStart Job has failed");
            }
          } catch (InstantiationException e) {
            throw new UnexpectedException("Job could not be instantiated", e);
          } catch (IllegalAccessException e) {
            throw new UnexpectedException("Job could not be instantiated", e);
          } catch (Throwable ex) {
            if (ex instanceof PlayException) {
              throw (PlayException) ex;
            }
            throw new UnexpectedException(ex);
          }
        } else {
          // run job async
          try {
            Job<?> job = ((Job<?>) clazz.newInstance());
            scheduledJobs.add(job);
            // start running job now in the background
            @SuppressWarnings("unchecked")
            Callable<Job> callable = (Callable<Job>) job;
            executor.submit(callable);
          } catch (InstantiationException ex) {
            throw new UnexpectedException("Cannot instanciate Job " + clazz.getName());
          } catch (IllegalAccessException ex) {
            throw new UnexpectedException("Cannot instanciate Job " + clazz.getName());
          }
        }
      }

      // @On
      if (clazz.isAnnotationPresent(On.class)) {
        try {
          Job<?> job = ((Job<?>) clazz.newInstance());
          scheduledJobs.add(job);
          scheduleForCRON(job);
        } catch (InstantiationException ex) {
          throw new UnexpectedException("Cannot instanciate Job " + clazz.getName());
        } catch (IllegalAccessException ex) {
          throw new UnexpectedException("Cannot instanciate Job " + clazz.getName());
        }
      }
      // @Every
      if (clazz.isAnnotationPresent(Every.class)) {
        try {
          Job job = (Job) clazz.newInstance();
          scheduledJobs.add(job);
          String value = job.getClass().getAnnotation(Every.class).value();
          if (value.startsWith("cron.")) {
            value = Play.configuration.getProperty(value);
          }
          value = Expression.evaluate(value, value).toString();
          if (!"never".equalsIgnoreCase(value)) {
            executor.scheduleWithFixedDelay(
                job, Time.parseDuration(value), Time.parseDuration(value), TimeUnit.SECONDS);
          }
        } catch (InstantiationException ex) {
          throw new UnexpectedException("Cannot instanciate Job " + clazz.getName());
        } catch (IllegalAccessException ex) {
          throw new UnexpectedException("Cannot instanciate Job " + clazz.getName());
        }
      }
    }
  }
Exemplo n.º 20
0
 /**
  * Log start.
  *
  * @param log Logger.
  * @param clazz Class.
  * @param start Start time.
  */
 public static void logStart(@Nullable IgniteLogger log, Class<?> clazz, long start) {
   log0(log, start, "[" + clazz.getSimpleName() + "]: STARTED");
 }