/**
   * 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());
  }
  /** {@inheritDoc} */
  @Nullable
  @Override
  public GridDeployment explicitDeploy(Class<?> cls, ClassLoader clsLdr) throws GridException {
    try {
      // Make sure not to deploy peer loaded tasks with non-local class loader,
      // if local one exists.
      if (clsLdr.getClass().equals(GridDeploymentClassLoader.class)) clsLdr = clsLdr.getParent();

      GridDeployment dep;

      synchronized (mux) {
        boolean deployed = spi.register(clsLdr, cls);

        if (deployed) {
          dep = getDeployment(cls.getName());

          if (dep == null) {
            GridDeploymentResource rsrc = spi.findResource(cls.getName());

            if (rsrc != null && rsrc.getClassLoader() == clsLdr) {
              dep =
                  deploy(
                      ctx.config().getDeploymentMode(),
                      rsrc.getClassLoader(),
                      rsrc.getResourceClass(),
                      rsrc.getName());
            }
          }

          if (dep != null) {
            recordDeploy(cls, cls.getName(), true);
          }
        } else {
          dep = getDeployment(cls.getName());
        }
      }

      return dep;
    } catch (GridSpiException e) {
      recordDeployFailed(cls, clsLdr, true);

      // Avoid double wrapping.
      if (e.getCause() instanceof GridException) {
        throw (GridException) e.getCause();
      }

      throw new GridException("Failed to deploy class: " + cls.getName(), e);
    }
  }
  private static Object createArgumentPlaceholder(Class<?> clazz, Integer placeholderId) {
    if (clazz.isPrimitive() || Number.class.isAssignableFrom(clazz) || Character.class == clazz)
      return getPrimitivePlaceHolder(clazz, placeholderId);

    if (clazz == String.class) return String.valueOf(placeholderId);
    if (Date.class.isAssignableFrom(clazz)) return new Date(placeholderId);
    if (clazz.isArray()) return Array.newInstance(clazz.getComponentType(), 1);

    try {
      return createArgumentPlaceholderForUnknownClass(clazz, placeholderId);
    } catch (Exception e) {
      throw new ArgumentConversionException(
          "It is not possible to create a placeholder for class: " + clazz.getName(), e);
    }
  }
 /**
  * Register a custom argument creator factory for an unknown final class
  *
  * @param clazz The class for which this factory should be used
  * @param creator The argument factory
  * @param <T>
  */
 public static <T> void registerFinalClassArgumentCreator(
     Class<T> clazz, FinalClassArgumentCreator<T> creator) {
   if ((clazz.getModifiers() & Modifier.FINAL) == 0)
     throw new RuntimeException(
         "A custom argument creator can be registered only for final classes");
   FINAL_CLASS_ARGUMENT_CREATORS.put(clazz, creator);
 }
 /**
  * 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)));
 }
Example #6
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();
 }
  /**
   * 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)));
  }
  private static Object createArgumentPlaceholderForUnknownClass(
      Class<?> clazz, Integer placeholderId) throws IllegalAccessException, InstantiationException {
    FinalClassArgumentCreator<?> creator = FINAL_CLASS_ARGUMENT_CREATORS.get(clazz);
    if (creator != null) return creator.createArgumentPlaceHolder(placeholderId);

    for (Constructor constructor : clazz.getConstructors()) {
      Class<?>[] params = constructor.getParameterTypes();
      if (params.length != 1) continue;
      try {
        if (params[0] == String.class)
          return constructor.newInstance(String.valueOf(placeholderId));
        if (isNumericClass(params[0])) return constructor.newInstance(placeholderId);
      } catch (IllegalAccessException e1) {
      } catch (InvocationTargetException e2) {
      }
    }
    return clazz.newInstance();
  }
  /**
   * 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;
  }
  /**
   * Gets alias for a class.
   *
   * @param dep Deployment.
   * @param cls Class.
   * @return Alias for a class.
   */
  private String getAlias(GridDeployment dep, Class<?> cls) {
    String alias = cls.getName();

    if (isTask(cls)) {
      GridTaskName ann = dep.annotation(cls, GridTaskName.class);

      if (ann != null) {
        alias = ann.value();
      }
    }

    return alias;
  }
 /**
  * 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");
 }
 private static Object createPlaceholder(Class<?> clazz, InvocationSequence invocationSequence) {
   return !Modifier.isFinal(clazz.getModifiers())
       ? createProxy(new ProxyArgument(clazz, invocationSequence), clazz, false)
       : createArgumentPlaceholder(clazz);
 }
  /**
   * @param depMode Deployment mode.
   * @param ldr Class loader to deploy.
   * @param cls Class.
   * @param alias Class alias.
   * @return Deployment.
   */
  @SuppressWarnings({"ConstantConditions"})
  private GridDeployment deploy(
      GridDeploymentMode depMode, ClassLoader ldr, Class<?> cls, String alias) {
    assert Thread.holdsLock(mux);

    LinkedList<GridDeployment> cachedDeps = null;

    GridDeployment dep = null;

    // Find existing class loader info.
    for (LinkedList<GridDeployment> deps : cache.values()) {
      for (GridDeployment d : deps) {
        if (d.classLoader() == ldr) {
          // Cache class and alias.
          d.addDeployedClass(cls, alias);

          cachedDeps = deps;

          dep = d;

          break;
        }
      }

      if (cachedDeps != null) {
        break;
      }
    }

    if (cachedDeps != null) {
      assert dep != null;

      cache.put(alias, cachedDeps);

      if (!cls.getName().equals(alias)) {
        // Cache by class name as well.
        cache.put(cls.getName(), cachedDeps);
      }

      return dep;
    }

    GridUuid ldrId = GridUuid.randomUuid();

    long seqNum = seq.incrementAndGet();

    String userVer = getUserVersion(ldr);

    dep = new GridDeployment(depMode, ldr, ldrId, seqNum, userVer, cls.getName(), true);

    dep.addDeployedClass(cls, alias);

    LinkedList<GridDeployment> deps =
        F.addIfAbsent(cache, alias, F.<GridDeployment>newLinkedList());

    if (!deps.isEmpty()) {
      for (GridDeployment d : deps) {
        if (!d.isUndeployed()) {
          U.error(
              log,
              "Found more than one active deployment for the same resource "
                  + "[cls="
                  + cls
                  + ", depMode="
                  + depMode
                  + ", dep="
                  + d
                  + ']');

          return null;
        }
      }
    }

    // Add at the beginning of the list for future fast access.
    deps.addFirst(dep);

    if (!cls.getName().equals(alias)) {
      // Cache by class name as well.
      cache.put(cls.getName(), deps);
    }

    if (log.isDebugEnabled()) {
      log.debug("Created new deployment: " + dep);
    }

    return dep;
  }
Example #14
0
 @Override
 public String toString() {
   return toString(joinClass == null ? null : joinClass.getSimpleName()).toString();
 }
 @SuppressWarnings("unchecked")
 private static <T> T createFinalArgumentPlaceholder(Class<T> clazz) {
   if (clazz == Boolean.TYPE || clazz == Boolean.class) return (T) Boolean.FALSE;
   if (clazz.isEnum()) return (T) EnumSet.allOf((Class<? extends Enum>) clazz).iterator().next();
   return (T) createArgumentPlaceholder(clazz, FINAL_PLACEHOLDER_SEED);
 }
 @SuppressWarnings("unchecked")
 Object getNextPlaceholder(Class<?> clazz) {
   return clazz.isEnum()
       ? getNextEnumPlaceholder((Class<? extends Enum>) clazz)
       : getNextBooleanPlaceholder();
 }
 private static boolean isLimitedValues(Class<?> clazz) {
   return clazz == Boolean.TYPE || clazz == Boolean.class || clazz.isEnum();
 }