/** {@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);
    }
  }
  /**
   * Creates JUnit test router. Note that router must have a no-arg constructor.
   *
   * @return JUnit router instance.
   */
  @SuppressWarnings({"unchecked"})
  private GridTestRouter createRouter() {
    try {
      if (routerCls == null) {
        routerCls = (Class<? extends GridTestRouter>) Class.forName(routerClsName);
      } else {
        routerClsName = routerCls.getName();
      }

      return routerCls.newInstance();
    } catch (ClassNotFoundException e) {
      throw new GridRuntimeException("Failed to initialize JUnit router: " + routerClsName, e);
    } catch (IllegalAccessException e) {
      throw new GridRuntimeException("Failed to initialize JUnit router: " + routerClsName, e);
    } catch (InstantiationException e) {
      throw new GridRuntimeException("Failed to initialize JUnit router: " + routerClsName, e);
    }
  }
  /**
   * 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;
  }
Example #4
0
  /**
   * Runs JDBC example.
   *
   * @param args Command line arguments.
   * @throws Exception In case of error.
   */
  public static void main(String[] args) throws Exception {
    Grid grid = G.start("examples/config/spring-cache.xml");

    Connection conn = null;

    try {
      // Populate cache with data.
      populate(grid.cache(CACHE_NAME));

      // Register JDBC driver.
      Class.forName("org.gridgain.jdbc.GridJdbcDriver");

      // Open JDBC connection.
      conn =
          DriverManager.getConnection("jdbc:gridgain://localhost/" + CACHE_NAME, configuration());

      X.println(">>>");

      // Query all persons.
      queryAllPersons(conn);

      X.println(">>>");

      // Query person older than 30 years.
      queryPersons(conn, 30);

      X.println(">>>");

      // Query persons working in GridGain.
      queryPersonsInOrganization(conn, "GridGain");

      X.println(">>>");
    } finally {
      // Close JDBC connection.
      if (conn != null) conn.close();

      G.stop(true);
    }
  }
    /** {@inheritDoc} */
    @Override
    public void onDeployed(Class<?> cls) {
      assert !Thread.holdsLock(mux);

      boolean isTask = isTask(cls);

      String msg =
          (isTask ? "Task" : "Class") + " was deployed in SHARED or CONTINUOUS mode: " + cls;

      int type = isTask ? EVT_TASK_DEPLOYED : EVT_CLASS_DEPLOYED;

      if (ctx.event().isRecordable(type)) {
        GridDeploymentEvent evt = new GridDeploymentEvent();

        evt.nodeId(ctx.localNodeId());
        evt.message(msg);
        evt.type(type);
        evt.alias(cls.getName());

        ctx.event().record(evt);
      }

      if (log.isInfoEnabled()) log.info(msg);
    }
Example #6
0
  /**
   * Aspect implementation which executes grid-enabled methods on remote nodes.
   *
   * @param invoc Method invocation instance provided by JBoss AOP framework.
   * @return Method execution result.
   * @throws Throwable If method execution failed.
   */
  @SuppressWarnings({
    "ProhibitedExceptionDeclared",
    "ProhibitedExceptionThrown",
    "CatchGenericClass",
    "unchecked"
  })
  @Bind(
      pointcut = "execution(* *->@org.gridgain.grid.gridify.Gridify(..))",
      cflow = "org.gridgain.grid.gridify.aop.jboss.GridifyJbossAspect.CFLOW_STACK")
  public Object gridify(MethodInvocation invoc) throws Throwable {
    Method mtd = invoc.getMethod();

    Gridify ann = mtd.getAnnotation(Gridify.class);

    assert ann != null : "Intercepted method does not have gridify annotation.";

    // Since annotations in Java don't allow 'null' as default value
    // we have accept an empty string and convert it here.
    // NOTE: there's unintended behavior when user specifies an empty
    // string as intended grid name.
    // NOTE: the 'ann.gridName() == null' check is added to mitigate
    // annotation bugs in some scripting languages (e.g. Groovy).
    String gridName = F.isEmpty(ann.gridName()) ? null : ann.gridName();

    if (G.state(gridName) != STARTED) {
      throw new GridException("Grid is not locally started: " + gridName);
    }

    // Initialize defaults.
    GridifyArgument arg =
        new GridifyArgumentAdapter(
            mtd.getDeclaringClass(),
            mtd.getName(),
            mtd.getParameterTypes(),
            invoc.getArguments(),
            invoc.getTargetObject());

    if (!ann.interceptor().equals(GridifyInterceptor.class)) {
      // Check interceptor first.
      if (!ann.interceptor().newInstance().isGridify(ann, arg)) {
        return invoc.invokeNext();
      }
    }

    if (!ann.taskClass().equals(GridifyDefaultTask.class) && ann.taskName().length() > 0) {
      throw new GridException(
          "Gridify annotation must specify either Gridify.taskName() or "
              + "Gridify.taskClass(), but not both: "
              + ann);
    }

    try {
      Grid grid = G.grid(gridName);

      // If task class was specified.
      if (!ann.taskClass().equals(GridifyDefaultTask.class)) {
        return grid.execute(
                (Class<? extends GridTask<GridifyArgument, Object>>) ann.taskClass(),
                arg,
                ann.timeout())
            .get();
      }

      // If task name was not specified.
      if (ann.taskName().length() == 0) {
        return grid.execute(
                new GridifyDefaultTask(invoc.getActualMethod().getDeclaringClass()),
                arg,
                ann.timeout())
            .get();
      }

      // If task name was specified.
      return grid.execute(ann.taskName(), arg, ann.timeout()).get();
    } catch (Throwable e) {
      for (Class<?> ex : invoc.getMethod().getExceptionTypes()) {
        // Descend all levels down.
        Throwable cause = e.getCause();

        while (cause != null) {
          if (ex.isAssignableFrom(cause.getClass())) {
            throw cause;
          }

          cause = cause.getCause();
        }

        if (ex.isAssignableFrom(e.getClass())) {
          throw e;
        }
      }

      throw new GridifyRuntimeException("Undeclared exception thrown: " + e.getMessage(), e);
    }
  }
  /**
   * @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;
  }