예제 #1
0
  private static void solve(Grid grid, List<Grid> solutions) {
    // Return if there is already more than two solution
    if (solutions.size() >= 2) {
      return;
    }

    // Find first empty cell
    int loc = grid.findEmptyCell();

    // If no empty cells are found,a solution is found
    if (loc < 0) {
      solutions.add(grid.clone());
      return;
    }

    // Try each of the 9 digits in this empty cell
    for (int n = 1; n < 10; n++) {
      if (grid.set(loc, n)) {
        // With this cell set,work on the next cell
        solve(grid, solutions);

        // Clear the cell so that it can be filled with another digit
        grid.clear(loc);
      }
    }
  }
예제 #2
0
  /** @throws Exception If failed. */
  @SuppressWarnings({"ObjectEquality"})
  public void testDifferentTasks() throws Exception {
    Grid grid1 = null;
    Grid grid2 = null;

    try {
      grid1 = startGrid(1, new GridSpringResourceContextImpl(new GenericApplicationContext()));
      grid2 = startGrid(2, new GridSpringResourceContextImpl(new GenericApplicationContext()));

      // Execute different tasks.
      grid1.compute().execute(SharedResourceTask1.class, null).get();
      grid1.compute().execute(SharedResourceTask2.class, null).get();

      // In ISOLATED_CLASSLOADER mode tasks should have the class
      // loaders because they have the same CL locally and thus the same
      // resources.
      // So 1 resource locally and 1 remotely
      assert task1Rsrc1 == task2Rsrc1;
      assert task1Rsrc2 == task2Rsrc2;
      assert task1Rsrc3 == task2Rsrc3;
      assert task1Rsrc4 == task2Rsrc4;

      checkUsageCount(createClss, UserResource1.class, 4);
      checkUsageCount(createClss, UserResource2.class, 4);

      checkUsageCount(deployClss, UserResource1.class, 4);
      checkUsageCount(deployClss, UserResource2.class, 4);
    } finally {
      GridTestUtils.close(grid1, log());
      GridTestUtils.close(grid2, log());
    }

    checkUsageCount(undeployClss, UserResource1.class, 4);
    checkUsageCount(undeployClss, UserResource2.class, 4);
  }
  /** @throws Exception If failed. */
  @SuppressWarnings("unchecked")
  public void testCancel() throws Exception {
    Grid grid = G.grid(getTestGridName());

    grid.compute()
        .localDeployTask(GridCancelTestTask.class, U.detectClassLoader(GridCancelTestTask.class));

    GridComputeTaskFuture<?> fut = grid.compute().execute(GridCancelTestTask.class.getName(), null);

    // Wait until jobs begin execution.
    boolean await = startSignal.await(WAIT_TIME, TimeUnit.MILLISECONDS);

    assert await : "Jobs did not start.";

    info("Test task result: " + fut);

    assert fut != null;

    // Only first job should successfully complete.
    Object res = fut.get();
    assert (Integer) res == 1;

    // Wait for all jobs to finish.
    await = stopSignal.await(WAIT_TIME, TimeUnit.MILLISECONDS);
    assert await : "Jobs did not stop.";

    // One is definitely processed. But there might be some more processed or cancelled or processed
    // and cancelled.
    // Thus total number should be at least SPLIT_COUNT and at most (SPLIT_COUNT - 1) *2 +1
    assert (cancelCnt + processedCnt) >= SPLIT_COUNT
            && (cancelCnt + processedCnt) <= (SPLIT_COUNT - 1) * 2 + 1
        : "Invalid cancel count value: " + cancelCnt;
  }
예제 #4
0
  /** @throws Exception If failed. */
  @SuppressWarnings({"ObjectEquality"})
  public void testUndeployedTask() throws Exception {
    Grid grid1 = null;
    Grid grid2 = null;

    try {
      grid1 = startGrid(1, new GridSpringResourceContextImpl(new GenericApplicationContext()));
      grid2 = startGrid(2, new GridSpringResourceContextImpl(new GenericApplicationContext()));

      // Execute tasks.
      grid1.compute().execute(SharedResourceTask1.class, null).get();
      grid1.compute().execute(SharedResourceTask2.class, null).get();

      grid1.compute().undeployTask(SharedResourceTask1.class.getName());

      // Wait until resources get undeployed remotely
      // because undeploy is asynchronous apply.
      Thread.sleep(3000);

      // 1 local and 1 remote resource instances
      checkUsageCount(createClss, UserResource1.class, 4);
      checkUsageCount(deployClss, UserResource1.class, 4);
      checkUsageCount(createClss, UserResource2.class, 4);
      checkUsageCount(deployClss, UserResource2.class, 4);
      checkUsageCount(undeployClss, UserResource1.class, 4);
      checkUsageCount(undeployClss, UserResource2.class, 4);

      grid1.compute().undeployTask(SharedResourceTask2.class.getName());

      // Wait until resources get undeployed remotely
      // because undeploy is asynchronous apply.
      Thread.sleep(3000);

      // We undeployed last task for this class loader and resources.
      // All resources should be undeployed.
      checkUsageCount(undeployClss, UserResource1.class, 4);
      checkUsageCount(undeployClss, UserResource2.class, 4);

      // Execute the same tasks.
      grid1.compute().execute(SharedResourceTask1.class, null).get();
      grid1.compute().execute(SharedResourceTask2.class, null).get();

      // 2 new resources.
      checkUsageCount(createClss, UserResource1.class, 8);
      checkUsageCount(deployClss, UserResource1.class, 8);
      checkUsageCount(createClss, UserResource2.class, 8);
      checkUsageCount(deployClss, UserResource2.class, 8);
    } finally {
      GridTestUtils.close(grid1, log());
      GridTestUtils.close(grid2, log());
    }

    checkUsageCount(undeployClss, UserResource1.class, 8);
    checkUsageCount(undeployClss, UserResource2.class, 8);
  }
  /**
   * Starts the local node and checks for presence of log file. Also checks that this is really a
   * log of a started node.
   *
   * @param id Test-local node ID.
   * @throws Exception If error occurred.
   */
  private void checkOneNode(int id) throws Exception {
    try (Grid grid = G.start(getConfiguration("grid" + id))) {
      String id8 = U.id8(grid.localNode().id());
      String logPath = "work/log/gridgain-" + id8 + ".log";
      File logFile = U.resolveGridGainPath(logPath);

      assertNotNull("Failed to resolve path: " + logPath, logFile);
      assertTrue("Log file does not exist: " + logFile, logFile.exists());

      String logContent = U.readFileToString(logFile.getAbsolutePath(), "UTF-8");

      assertTrue(
          "Log file does not contain it's node ID: " + logFile,
          logContent.contains(">>> Local node [ID=" + id8.toUpperCase()));
    }
  }
예제 #6
0
  /** @throws Exception If failed. */
  public void testSameTaskFromTwoNodesLeft() throws Exception {
    Grid grid1 = null;
    Grid grid2 = null;
    Grid grid3 = null;

    try {
      grid1 = startGrid(1, new GridSpringResourceContextImpl(new GenericApplicationContext()));
      grid2 = startGrid(2, new GridSpringResourceContextImpl(new GenericApplicationContext()));
      grid3 = startGrid(3, new GridSpringResourceContextImpl(new GenericApplicationContext()));

      grid1.compute().execute(SharedResourceTask1.class, null).get();
      grid2.compute().execute(SharedResourceTask1.class, null).get();

      checkUsageCount(createClss, UserResource1.class, 6);
      checkUsageCount(deployClss, UserResource1.class, 6);
      checkUsageCount(createClss, UserResource2.class, 6);
      checkUsageCount(deployClss, UserResource2.class, 6);

      checkUsageCount(undeployClss, UserResource1.class, 0);
      checkUsageCount(undeployClss, UserResource2.class, 0);

      GridTestUtils.close(grid1, log());

      // Wait until other nodes get notified
      // this grid1 left.
      Thread.sleep(1000);

      // Undeployment happened only on Grid1.
      checkUsageCount(undeployClss, UserResource1.class, 2);
      checkUsageCount(undeployClss, UserResource2.class, 2);

      GridTestUtils.close(grid2, log());

      // Wait until resources get undeployed remotely
      // because undeploy is asynchronous apply.
      Thread.sleep(1000);

      // Grid1 and Grid2
      checkUsageCount(undeployClss, UserResource1.class, 4);
      checkUsageCount(undeployClss, UserResource2.class, 4);
    } finally {
      GridTestUtils.close(grid1, log());
      GridTestUtils.close(grid2, log());
      GridTestUtils.close(grid3, log());
    }
  }
예제 #7
0
  /** @throws Exception If failed. */
  @SuppressWarnings("unchecked")
  public void testRedeployedTask() throws Exception {
    Grid grid = startGrid(0, new GridSpringResourceContextImpl(new GenericApplicationContext()));

    try {
      // Execute same task with different class loaders. Second execution should redeploy first one.
      grid.compute().execute(SharedResourceTask1.class, null).get();

      checkUsageCount(createClss, UserResource1.class, 2);
      checkUsageCount(createClss, UserResource2.class, 2);

      checkUsageCount(deployClss, UserResource1.class, 2);
      checkUsageCount(deployClss, UserResource2.class, 2);

      // Change class loader of the task. So it's just implicit redeploy.
      ClassLoader tstClsLdr =
          new GridTestClassLoader(
              null,
              getClass().getClassLoader(),
              SharedResourceTask1.class.getName(),
              GridResourceSharedUndeploySelfTest.SharedResourceTask1.GridSharedJob1.class.getName(),
              GridResourceSharedUndeploySelfTest.class.getName());

      Class<? extends GridComputeTask<Object, Object>> taskCls =
          (Class<? extends GridComputeTask<Object, Object>>)
              tstClsLdr.loadClass(SharedResourceTask1.class.getName());

      grid.compute().execute(taskCls, null).get();

      // Old resources should be undeployed at this point.
      checkUsageCount(undeployClss, UserResource1.class, 2);
      checkUsageCount(undeployClss, UserResource2.class, 2);

      // We should detect redeployment and create new resources.
      checkUsageCount(createClss, UserResource1.class, 4);
      checkUsageCount(createClss, UserResource2.class, 4);

      checkUsageCount(deployClss, UserResource1.class, 4);
      checkUsageCount(deployClss, UserResource2.class, 4);
    } finally {
      GridTestUtils.close(grid, log());
    }

    checkUsageCount(undeployClss, UserResource1.class, 4);
    checkUsageCount(undeployClss, UserResource2.class, 4);
  }
예제 #8
0
  /** @throws Exception If failed. */
  public void testDifferentTaskNameLocally() throws Exception {
    Grid grid = startGrid(0, new GridSpringResourceContextImpl(new GenericApplicationContext()));

    // Versions are different - should not share
    // 2 resource created locally
    try {
      grid.compute().execute(SharedResourceTask1Version1.class, null).get();

      try {
        grid.compute().execute(SharedResourceTask1Version2.class, null).get();

        assert false : "SharedResourceTask4 should not be allowed to deploy.";
      } catch (GridException e) {
        info("Received expected exception: " + e);
      }
    } finally {
      GridTestUtils.close(grid, log());
    }
  }
예제 #9
0
  /** @throws Exception If failed. */
  public void testSameTaskLocally() throws Exception {
    Grid grid = startGrid(0, new GridSpringResourceContextImpl(new GenericApplicationContext()));

    try {
      // Execute the same task twice.
      // 1 resource created locally
      grid.compute().execute(SharedResourceTask1.class, null).get();
      grid.compute().execute(SharedResourceTask1.class, null).get();

      checkUsageCount(createClss, UserResource1.class, 2);
      checkUsageCount(createClss, UserResource2.class, 2);

      checkUsageCount(deployClss, UserResource1.class, 2);
      checkUsageCount(deployClss, UserResource2.class, 2);
    } finally {
      GridTestUtils.close(grid, log());
    }

    checkUsageCount(undeployClss, UserResource1.class, 2);
    checkUsageCount(undeployClss, UserResource2.class, 2);
  }
 public void actionPerformed(ActionEvent e) {
   if (e.getSource().equals(save)) new GridSaver(grid, fileName());
   if (e.getSource().equals(load)) {
     GridLoader gl = new GridLoader(grid, fileName());
     try {
       grid.setMap(gl.read());
     } catch (IOException ioex) {
       System.out.println("File load Failed ioex");
     }
   }
   parent.getParent().refresh();
 }
예제 #11
0
  /**
   * Tests that failover don't pick local node if it has been excluded from topology.
   *
   * @throws Exception If failed.
   */
  @SuppressWarnings({"WaitNotInLoop", "UnconditionalWait", "unchecked"})
  public void testFailoverTopology() throws Exception {
    try {
      Grid grid1 = startGrid(1);
      Grid grid2 = startGrid(2);

      assert grid1 != null;
      assert grid2 != null;

      grid1.compute().localDeployTask(JobTask.class, JobTask.class.getClassLoader());

      try {
        GridComputeTaskFuture<String> fut;

        synchronized (mux) {
          fut = grid1.compute().execute(JobTask.class, null);

          mux.wait();
        }

        stopAndCancelGrid(2);

        String res = fut.get();

        info("Task result: " + res);
      } catch (GridException e) {
        info("Got unexpected grid exception: " + e);
      }

      info("Failed over: " + failCnt.get());

      assert failCnt.get() == 1
          : "Invalid fail over counter [expected=1, actual=" + failCnt.get() + ']';
    } finally {
      stopGrid(1);

      // Stopping stopped instance just in case.
      stopGrid(2);
    }
  }
예제 #12
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);
    }
  }
예제 #13
0
  /**
   * Starts Grid instance. Note that if grid is already started, then it will be looked up and
   * returned from this method.
   *
   * @return Started grid.
   */
  private Grid startGrid() {
    Properties props = System.getProperties();

    gridName = props.getProperty(GRIDGAIN_NAME.name());

    if (!props.containsKey(GRIDGAIN_NAME.name()) || G.state(gridName) != GridFactoryState.STARTED) {
      selfStarted = true;

      // Set class loader for the spring.
      ClassLoader curCl = Thread.currentThread().getContextClassLoader();

      // Add no-op logger to remove no-appender warning.
      Appender app = new NullAppender();

      Logger.getRootLogger().addAppender(app);

      try {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

        Grid grid = G.start(cfgPath);

        gridName = grid.name();

        System.setProperty(GRIDGAIN_NAME.name(), grid.name());

        return grid;
      } catch (GridException e) {
        throw new GridRuntimeException("Failed to start grid: " + cfgPath, e);
      } finally {
        Logger.getRootLogger().removeAppender(app);

        Thread.currentThread().setContextClassLoader(curCl);
      }
    }

    return G.grid(gridName);
  }
예제 #14
0
  public static void main(String[] args) throws Exception {
    // Open the file containing the givens
    File file = new File(args[0]);
    FileReader rd = new FileReader(args[0]);

    // Process each grid in the file
    while (true) {
      Grid grid = Grid.create(rd);
      if (grid == null) {
        // No more grids
        break;
      }

      // Find a solution
      List<Grid> solutions = solve(grid);

      printSolutions(grid, solutions);
    }
  }
예제 #15
0
  /** @throws Exception If failed. */
  public void testSameTaskFromTwoNodesUndeploy() throws Exception {
    Grid grid1 = null;
    Grid grid2 = null;
    Grid grid3 = null;

    try {
      grid1 = startGrid(1, new GridSpringResourceContextImpl(new GenericApplicationContext()));
      grid2 = startGrid(2, new GridSpringResourceContextImpl(new GenericApplicationContext()));
      grid3 = startGrid(3, new GridSpringResourceContextImpl(new GenericApplicationContext()));

      grid1.compute().execute(SharedResourceTask1.class, null).get();
      grid2.compute().execute(SharedResourceTask1.class, null).get();

      checkUsageCount(createClss, UserResource1.class, 6);
      checkUsageCount(deployClss, UserResource1.class, 6);
      checkUsageCount(createClss, UserResource2.class, 6);
      checkUsageCount(deployClss, UserResource2.class, 6);

      checkUsageCount(undeployClss, UserResource1.class, 0);
      checkUsageCount(undeployClss, UserResource2.class, 0);

      grid1.compute().undeployTask(SharedResourceTask1.class.getName());

      // Wait until resources get undeployed remotely
      // because undeploy is asynchronous apply.
      Thread.sleep(3000);

      checkUsageCount(undeployClss, UserResource1.class, 6);
      checkUsageCount(undeployClss, UserResource2.class, 6);

      grid2.compute().undeployTask(SharedResourceTask1.class.getName());

      // Wait until resources get undeployed remotely
      // because undeploy is asynchronous apply.
      Thread.sleep(3000);

      // All Tasks from originating nodes were undeployed. All resources should be cleaned up.
      checkUsageCount(undeployClss, UserResource1.class, 6);
      checkUsageCount(undeployClss, UserResource2.class, 6);
    } finally {
      GridTestUtils.close(grid1, log());
      GridTestUtils.close(grid2, log());
      GridTestUtils.close(grid3, log());
    }
  }
예제 #16
0
  /**
   * Runs all tests belonging to this test suite on the grid.
   *
   * @param result Test result collector.
   */
  @Override
  public void run(TestResult result) {
    if (isDisabled) {
      copy.run(result);
    } else {
      GridTestRouter router = createRouter();

      Grid grid = startGrid();

      try {
        List<GridTaskFuture<?>> futs = new ArrayList<GridTaskFuture<?>>(testCount());

        List<GridJunit3SerializableTest> tests =
            new ArrayList<GridJunit3SerializableTest>(testCount());

        for (int i = 0; i < testCount(); i++) {
          Test junit = testAt(i);

          GridJunit3SerializableTest test;

          if (junit instanceof TestSuite) {
            test = new GridJunit3SerializableTestSuite((TestSuite) junit);
          } else {
            assert junit instanceof TestCase
                : "Test must be either TestSuite or TestCase: " + junit;

            test = new GridJunit3SerializableTestCase((TestCase) junit);
          }

          tests.add(test);

          if (clsLdr == null) {
            clsLdr = U.detectClassLoader(junit.getClass());
          }

          futs.add(
              grid.execute(
                  new GridJunit3Task(junit.getClass(), clsLdr),
                  new GridJunit3Argument(router, test, locTests.contains(test.getName())),
                  timeout));
        }

        for (int i = 0; i < testCount(); i++) {
          GridTaskFuture<?> fut = futs.get(i);

          GridJunit3SerializableTest origTest = tests.get(i);

          try {
            GridJunit3SerializableTest resTest = (GridJunit3SerializableTest) fut.get();

            origTest.setResult(resTest);

            origTest.getTest().run(result);
          } catch (GridException e) {
            handleFail(result, origTest, e);
          }
        }
      } finally {
        stopGrid();
      }
    }
  }