示例#1
0
  /**
   * Execute {@code HelloWorld} example on the grid.
   *
   * @param args Command line arguments, none required but if provided first one should point to the
   *     Spring XML configuration file. See {@code "examples/config/"} for configuration file
   *     examples.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws GridException {
    if (args.length == 0) {
      G.start();
    } else {
      G.start(args[0]);
    }

    try {
      Grid grid = G.grid();

      // Execute Hello World task.
      GridTaskFuture<Integer> fut = grid.execute(GridHelloWorldTask.class, "Hello World");

      // Wait for task completion.
      int phraseLen = fut.get();

      X.println(">>>");
      X.println(">>> Finished executing Grid \"Hello World\" example with custom task.");
      X.println(">>> Total number of characters in the phrase is '" + phraseLen + "'.");
      X.println(">>> You should see print out of 'Hello' on one node and 'World' on another node.");
      X.println(">>> Check all nodes for output (this node is also part of the grid).");
      X.println(">>>");
    } finally {
      G.stop(true);
    }
  }
  /**
   * Execute {@code HelloWorld} example grid-enabled with {@code Gridify} annotation.
   *
   * @param args Command line arguments, none required but if provided first one should point to the
   *     Spring XML configuration file. See {@code "examples/config/"} for configuration file
   *     examples.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws GridException {
    if (args.length == 0) {
      G.start();
    } else {
      G.start(args[0]);
    }

    try {
      // Simple example stateful instance to demonstrate
      // how object state can be handled with grid-enabled methods.
      GridifyHelloWorld helloWorld = new GridifyHelloWorld();

      // Set simple state.
      helloWorld.setState("Hello World");

      // This method is grid-enabled and
      // will be executed on remote grid nodes.
      int phraseLen = helloWorld.sayIt();

      X.println(">>>");
      X.println(">>> Finished executing Gridify \"Hello World\" stateful example.");
      X.println(">>> Total number of characters in the phrase is '" + phraseLen + "'.");
      X.println(">>> You should see print out of 'Hello' on one node and 'World' on another node.");
      X.println(">>> Check all nodes for output (this node is also part of the grid).");
      X.println(">>>");
    } finally {
      G.stop(true);
    }
  }
  /**
   * Execute {@code HelloWorld} example on the grid.
   *
   * @param args Command line arguments, none required but if provided first one should point to the
   *     Spring XML configuration file. See {@code "examples/config/"} for configuration file
   *     examples.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws GridException {
    if (args.length == 0) {
      G.start();
    } else {
      G.start(args[0]);
    }

    try {
      // Broadcast this message to all nodes using GridClosure.
      broadcastWordsClosure("Broadcasting This Message To All Nodes!");

      // Print individual words from this phrase on different nodes
      // using GridClosure
      spreadWordsClosure("Print Worlds Functional Style!");

      // Print this message using anonymous runnable object.
      unicastWordsRunnable("Printing This Message From Runnable!");

      // Split the message into words and pass them as arguments
      // for remote execution of Callable objects.
      countLettersCallable("Letter Count With Callable!");

      // Split the message into words and pass them as arguments
      // for remote execution of GridClosure objects.
      countLettersClosure("Letter Count With Closure!");

      // Split the message into words and pass them as arguments
      // for remote execution of GridClosure objects and
      // then aggregate results using GridReducer.
      countLettersReducer("Letter Count With Reducer!");
    } finally {
      G.stop(true);
    }
  }
  /**
   * Execute {@code HelloWorld} example grid-enabled with {@code Gridify} annotation.
   *
   * @param args Command line arguments, none required but if provided first one should point to the
   *     Spring XML configuration file. See {@code "examples/config/"} for configuration file
   *     examples.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws GridException {
    if (args.length == 0) {
      G.start();
    } else {
      G.start(args[0]);
    }

    try {
      // This method will be executed on a remote grid nodes.
      int phraseLen = sayIt("Hello World");

      X.println(">>>");
      X.println(">>> Finished executing Gridify \"Hello World\" example with custom task.");
      X.println(">>> Total number of characters in the phrase is '" + phraseLen + "'.");
      X.println(">>> You should see print out of 'Hello' on one node and 'World' on another node.");
      X.println(">>> Check all nodes for output (this node is also part of the grid).");
      X.println(">>>");
    } finally {
      G.stop(true);
    }
  }
示例#5
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);
    }
  }
  /**
   * Starts up grid and checks all provided values for prime.
   *
   * @param args Command line arguments, none required but if provided first one should point to the
   *     Spring XML configuration file. See {@code "examples/config/"} for configuration file
   *     examples.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws GridException {
    // Starts grid.
    Grid grid = args.length == 0 ? G.start() : G.start(args[0]);

    // Values we want to check for prime.
    long[] checkVals = {32452841, 32452843, 32452847, 32452849, 236887699, 217645199};

    X.println(">>>");
    X.println(
        ">>> Starting to check the following numbers for primes: " + Arrays.toString(checkVals));

    try {
      long start = System.currentTimeMillis();

      for (long checkVal : checkVals) {
        // This method will be executed on the Grid as it is
        // annotated with @Gridify annotation.
        Long divisor = GridPrimeChecker.checkPrime(checkVal, 2, checkVal);

        // If divisor is null, then the number is prime.
        if (divisor == null) {
          X.println("Value '" + checkVal + "'is a prime number.");
        } else {
          X.println("Value '" + checkVal + "' is divisible by '" + divisor + '\'');
        }
      }

      long totalTime = System.currentTimeMillis() - start;

      X.println(">>> Total time to calculate all primes (milliseconds): " + totalTime);
      X.println(">>>");
    } finally {
      // Stops grid.
      G.stop(grid.name(), true);
    }
  }
  /**
   * Executes {@link GridSegmentATask} and {@link GridSegmentBTask} tasks on the grid.
   *
   * @param args Command line arguments, none required or used.
   * @throws GridException If example execution failed.
   */
  public static void main(String[] args) throws GridException {
    AbstractApplicationContext ctx =
        new ClassPathXmlApplicationContext("org/gridgain/examples/multispi/master.xml");

    // Get configuration from Spring.
    GridConfiguration cfg = ctx.getBean("grid.cfg", GridConfiguration.class);

    G.start(cfg);

    try {
      Grid grid = G.grid();

      // Execute task on segment "A".
      GridTaskFuture<Integer> futA = grid.execute(GridSegmentATask.class, null);

      // Execute task on segment "B".
      GridTaskFuture<Integer> futB = grid.execute(GridSegmentBTask.class, null);

      // Wait for task completion.
      futA.get();
      futB.get();

      X.println(">>>");
      X.println(">>> Finished executing Grid \"Multiple Topology\" example with custom tasks.");
      X.println(
          ">>> You should see print out of 'Executing job on node that is from segment A.'"
              + "on node that has attribute \"segment=A\"");
      X.println(
          ">>> and 'Executing job on node that is from segment B.' on node that has "
              + "attribute \"segment=B\"");
      X.println(">>> Check all nodes for output (this node is not a part of the grid).");
      X.println(">>>");
    } finally {
      G.stop(true);
    }
  }
 /** Stops grid only if it was started by this test suite. */
 private void stopGrid() {
   // Only stop grid if it was started here.
   if (selfStarted) {
     G.stop(gridName, true);
   }
 }
  /**
   * See <a href="http://e-docs.bea.com/wls/docs100/javadocs/weblogic/common/T3StartupDef.html">
   * http://e-docs.bea.com/wls/docs100/javadocs/weblogic/common/T3StartupDef.html</a> for more
   * information.
   *
   * @param str Virtual name by which the class is registered as a {@code startupClass} in the
   *     {@code config.xml} file
   * @param params A hashtable that is made up of the name-value pairs supplied from the {@code
   *     startupArgs} property
   * @return Result string (log message).
   * @throws Exception Thrown if error occurred.
   */
  @SuppressWarnings({"unchecked", "CatchGenericClass"})
  @Override
  public String startup(String str, Hashtable params) throws Exception {
    GridLogger log = new GridJavaLogger(LoggingHelper.getServerLogger());

    cfgFile = (String) params.get(cfgFilePathParam);

    if (cfgFile == null) {
      throw new IllegalArgumentException("Failed to read property: " + cfgFilePathParam);
    }

    String workMgrName = (String) params.get(workMgrParam);

    URL cfgUrl = U.resolveGridGainUrl(cfgFile);

    if (cfgUrl == null)
      throw new ServerLifecycleException(
          "Failed to find Spring configuration file (path provided should be "
              + "either absolute, relative to GRIDGAIN_HOME, or relative to META-INF folder): "
              + cfgFile);

    GenericApplicationContext springCtx;

    try {
      springCtx = new GenericApplicationContext();

      XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(springCtx);

      xmlReader.loadBeanDefinitions(new UrlResource(cfgUrl));

      springCtx.refresh();
    } catch (BeansException e) {
      throw new ServerLifecycleException(
          "Failed to instantiate Spring XML application context: " + e.getMessage(), e);
    }

    Map cfgMap;

    try {
      // Note: Spring is not generics-friendly.
      cfgMap = springCtx.getBeansOfType(GridConfiguration.class);
    } catch (BeansException e) {
      throw new ServerLifecycleException(
          "Failed to instantiate bean [type="
              + GridConfiguration.class
              + ", err="
              + e.getMessage()
              + ']',
          e);
    }

    if (cfgMap == null)
      throw new ServerLifecycleException(
          "Failed to find a single grid factory configuration in: " + cfgUrl);

    if (cfgMap.isEmpty())
      throw new ServerLifecycleException("Can't find grid factory configuration in: " + cfgUrl);

    try {
      ExecutorService execSvc = null;

      MBeanServer mbeanSrv = null;

      for (GridConfiguration cfg : (Collection<GridConfiguration>) cfgMap.values()) {
        assert cfg != null;

        GridConfigurationAdapter adapter = new GridConfigurationAdapter(cfg);

        // Set logger.
        if (cfg.getGridLogger() == null) adapter.setGridLogger(log);

        if (cfg.getExecutorService() == null) {
          if (execSvc == null)
            execSvc =
                workMgrName != null
                    ? new GridThreadWorkManagerExecutor(workMgrName)
                    : new GridThreadWorkManagerExecutor(J2EEWorkManager.getDefault());

          adapter.setExecutorService(execSvc);
        }

        if (cfg.getMBeanServer() == null) {
          if (mbeanSrv == null) {
            InitialContext ctx = null;

            try {
              ctx = new InitialContext();

              mbeanSrv = (MBeanServer) ctx.lookup("java:comp/jmx/runtime");
            } catch (Exception e) {
              throw new IllegalArgumentException(
                  "MBean server was not provided and failed to obtain " + "Weblogic MBean server.",
                  e);
            } finally {
              if (ctx != null) ctx.close();
            }
          }

          adapter.setMBeanServer(mbeanSrv);
        }

        Grid grid = G.start(adapter, springCtx);

        // Test if grid is not null - started properly.
        if (grid != null) gridNames.add(grid.name());
      }

      return getClass().getSimpleName() + " started successfully.";
    } catch (GridException e) {
      // Stop started grids only.
      for (String name : gridNames) G.stop(name, true);

      throw new ServerLifecycleException("Failed to start GridGain.", e);
    }
  }
  /**
   * @param args Command arguments.
   * @throws GridException If failed.
   */
  public static void main(String[] args) throws GridException {
    // Starts grid.
    Grid grid = args.length == 0 ? G.start() : G.start(args[0]);

    try {
      // Create portfolio.
      GridCredit[] portfolio = new GridCredit[5000];

      Random rnd = new Random();

      // Generate some test portfolio items.
      for (int i = 0; i < portfolio.length; i++) {
        portfolio[i] =
            new GridCredit(
                50000 * rnd.nextDouble(), // Credit amount.
                rnd.nextInt(1000), // Credit term in days.
                rnd.nextDouble() / 10, // APR.
                rnd.nextDouble() / 20 + 0.02 // EDF.
                );
      }

      // Forecast horizon in days.
      int horizon = 365;

      // Number of Monte-Carlo iterations.
      int iter = 10000;

      // Percentile.
      double percentile = 0.95;

      // Mark the stopwatch.
      long start = System.currentTimeMillis();

      // Calculate credit risk and print it out.
      // As you can see the grid enabling is completely hidden from the caller
      // and it is fully transparent to him. In fact, the caller is never directly
      // aware if method was executed just locally or on the 100s of grid nodes.
      // Credit risk crdRisk is the minimal amount that creditor has to have
      // available to cover possible defaults.
      double crdRisk =
          grid.reduce(
              SPREAD,
              closures(grid.size(), portfolio, horizon, iter, percentile),
              new R1<Double, Double>() {
                /** Collected values sum. */
                private double sum;

                /** Collected values count. */
                private int count;

                /** {@inheritDoc} */
                @Override
                public boolean collect(Double e) {
                  sum += e;
                  count++;

                  return true;
                }

                /** {@inheritDoc} */
                @Override
                public Double apply() {
                  return sum / count;
                }
              });

      X.println(
          "Credit risk [crdRisk="
              + crdRisk
              + ", duration="
              + (System.currentTimeMillis() - start)
              + "ms]");
    }
    // We specifically don't do any error handling here to
    // simplify the example. Real application may want to
    // add error handling and application specific recovery.
    finally {
      // Stops grid.
      G.stop(true);
    }
  }
  /**
   * Runs basic cache example.
   *
   * @param args Command line arguments, none required.
   * @throws Exception If example execution failed.
   */
  public static void main(String[] args) throws Exception {
    final Grid g =
        args.length == 0 ? G.start("examples/config/spring-cache.xml") : G.start(args[0]);

    try {
      // Subscribe to events on every node, so we can visualize what's
      // happening in remote caches.
      g.run(
          BROADCAST,
          new CA() {
            @Override
            public void apply() {
              GridLocalEventListener lsnr =
                  new GridLocalEventListener() {
                    @Override
                    public void onEvent(GridEvent event) {
                      switch (event.type()) {
                        case EVT_CACHE_OBJECT_PUT:
                        case EVT_CACHE_OBJECT_READ:
                        case EVT_CACHE_OBJECT_REMOVED:
                          {
                            GridCacheEvent e = (GridCacheEvent) event;

                            X.println("Cache event [name=" + e.name() + ", key=" + e.key() + ']');
                          }
                      }
                    }
                  };

              GridNodeLocal<String, GridLocalEventListener> loc = g.nodeLocal();

              GridLocalEventListener prev = loc.remove("lsnr");

              // If there is a listener subscribed from previous runs, unsubscribe it.
              if (prev != null) g.removeLocalEventListener(prev);

              // Record new listener, so we can check it on next run.
              loc.put("lsnr", lsnr);

              // Subscribe listener.
              g.addLocalEventListener(lsnr, EVTS_CACHE);
            }
          });

      final GridCacheProjection<Integer, String> cache =
          g.cache(CACHE_NAME).projection(Integer.class, String.class);

      final int keyCnt = 20;

      // Store keys in cache.
      for (int i = 0; i < keyCnt; i++) cache.putx(i, Integer.toString(i));

      // Peek and get on local node.
      for (int i = 0; i < keyCnt; i++) {
        X.println("Peeked [key=" + i + ", val=" + cache.peek(i) + ']');
        X.println("Got [key=" + i + ", val=" + cache.get(i) + ']');
      }

      // Projection (view) for remote nodes.
      GridProjection rmts = g.remoteProjection();

      if (!rmts.isEmpty()) {
        // Peek and get on remote nodes (comment it out if output gets too crowded).
        g.remoteProjection()
            .run(
                BROADCAST,
                new GridAbsClosureX() {
                  @Override
                  public void applyx() throws GridException {
                    for (int i = 0; i < keyCnt; i++) {
                      X.println("Peeked [key=" + i + ", val=" + cache.peek(i) + ']');
                      X.println("Got [key=" + i + ", val=" + cache.get(i) + ']');
                    }
                  }
                });
      }
    } finally {
      G.stop(true);
    }
  }