Beispiel #1
0
  public void testStructs() throws Exception {
    File tmp = new File("tmp");
    PersistentMap<X> pm = new PersistentMap<X>(new File(tmp, "simple"), X.class);
    try {
      X x = new X();
      x.abc = "def";
      x.def = 5;
      x.list.add("abc");
      assertNull(pm.put("abc", x));
      pm.close();

      PersistentMap<X> pm2 = new PersistentMap<X>(new File(tmp, "simple"), X.class);

      X x2 = pm2.get("abc");
      assertEquals("def", x2.abc);
      assertEquals(5, x2.def);

      pm2.remove("abc");

      assertEquals(0, pm2.size());

      pm2.close();
    } finally {
      pm.close();
      IO.delete(tmp);
    }
  }
Beispiel #2
0
  /**
   * Queries all persons and shows their names.
   *
   * @param conn JDBC connection.
   * @throws SQLException In case of SQL error.
   */
  private static void queryAllPersons(Connection conn) throws SQLException {
    Statement stmt = conn.createStatement();

    ResultSet rs = stmt.executeQuery("select name from Person");

    X.println(">>> All persons:");

    while (rs.next()) X.println(">>>     " + rs.getString(1));
  }
Beispiel #3
0
  /**
   * Queries persons older than provided age.
   *
   * @param conn JDBC connection.
   * @param minAge Minimum age.
   * @throws SQLException In case of SQL error.
   */
  private static void queryPersons(Connection conn, int minAge) throws SQLException {
    PreparedStatement stmt = conn.prepareStatement("select name, age from Person where age >= ?");

    stmt.setInt(1, minAge);

    ResultSet rs = stmt.executeQuery();

    X.println(">>> Persons older than " + minAge + ":");

    while (rs.next())
      X.println(">>>     " + rs.getString("NAME") + " (" + rs.getInt("AGE") + " years old)");
  }
Beispiel #4
0
  /**
   * Queries persons working in provided organization.
   *
   * @param conn JDBC
   * @param orgName Organization name.
   * @throws SQLException In case of SQL error.
   */
  private static void queryPersonsInOrganization(Connection conn, String orgName)
      throws SQLException {
    PreparedStatement stmt =
        conn.prepareStatement(
            "select p.name from Person p, Organization o where p.orgId = o.id and o.name = ?");

    stmt.setString(1, orgName);

    ResultSet rs = stmt.executeQuery();

    X.println(">>> Persons working in " + orgName + ":");

    while (rs.next()) X.println(">>>     " + rs.getString(1));
  }
 /**
  * @param log Logger.
  * @param time Time.
  * @param msg Message.
  */
 private static void log0(@Nullable IgniteLogger log, long time, String msg) {
   if (log != null) {
     if (log.isDebugEnabled()) log.debug(msg);
     else log.warning(msg);
   } else
     X.println(
         String.format(
             "[%s][%s]%s",
             DEBUG_DATE_FMT.get().format(time), Thread.currentThread().getName(), msg));
 }
Beispiel #6
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 ClusterStartNodeResult call() {
    JSch ssh = new JSch();

    Session ses = null;

    try {
      if (spec.key() != null) ssh.addIdentity(spec.key().getAbsolutePath());

      ses = ssh.getSession(spec.username(), spec.host(), spec.port());

      if (spec.password() != null) ses.setPassword(spec.password());

      ses.setConfig("StrictHostKeyChecking", "no");

      ses.connect(timeout);

      boolean win = isWindows(ses);

      char separator = win ? '\\' : '/';

      spec.fixPaths(separator);

      String igniteHome = spec.igniteHome();

      if (igniteHome == null) igniteHome = win ? DFLT_IGNITE_HOME_WIN : DFLT_IGNITE_HOME_LINUX;

      String script = spec.script();

      if (script == null) script = DFLT_SCRIPT_LINUX;

      String cfg = spec.configuration();

      if (cfg == null) cfg = "";

      String startNodeCmd;
      String scriptOutputFileName =
          FILE_NAME_DATE_FORMAT.format(new Date())
              + '-'
              + UUID.randomUUID().toString().substring(0, 8)
              + ".log";

      if (win)
        throw new UnsupportedOperationException(
            "Apache Ignite cannot be auto-started on Windows from IgniteCluster.startNodes(…) API.");
      else { // Assume Unix.
        int spaceIdx = script.indexOf(' ');

        String scriptPath = spaceIdx > -1 ? script.substring(0, spaceIdx) : script;
        String scriptArgs = spaceIdx > -1 ? script.substring(spaceIdx + 1) : "";
        String rmtLogArgs = buildRemoteLogArguments(spec.username(), spec.host());
        String tmpDir = env(ses, "$TMPDIR", "/tmp/");
        String scriptOutputDir = tmpDir + "ignite-startNodes";

        shell(ses, "mkdir " + scriptOutputDir);

        // Mac os don't support ~ in double quotes. Trying get home path from remote system.
        if (igniteHome.startsWith("~")) {
          String homeDir = env(ses, "$HOME", "~");

          igniteHome = igniteHome.replaceFirst("~", homeDir);
        }

        startNodeCmd =
            new SB()
                .
                // Console output is consumed, started nodes must use Ignite file appenders for log.
                a("nohup ")
                .a("\"")
                .a(igniteHome)
                .a('/')
                .a(scriptPath)
                .a("\"")
                .a(" ")
                .a(scriptArgs)
                .a(!cfg.isEmpty() ? " \"" : "")
                .a(cfg)
                .a(!cfg.isEmpty() ? "\"" : "")
                .a(rmtLogArgs)
                .a(" > ")
                .a(scriptOutputDir)
                .a("/")
                .a(scriptOutputFileName)
                .a(" 2>& 1 &")
                .toString();
      }

      info("Starting remote node with SSH command: " + startNodeCmd, spec.logger(), log);

      shell(ses, startNodeCmd);

      return new ClusterStartNodeResultImpl(spec.host(), true, null);
    } catch (IgniteInterruptedCheckedException e) {
      return new ClusterStartNodeResultImpl(spec.host(), false, e.getMessage());
    } catch (Exception e) {
      return new ClusterStartNodeResultImpl(spec.host(), false, X.getFullStackTrace(e));
    } finally {
      if (ses != null && ses.isConnected()) ses.disconnect();
    }
  }
  /** @throws Exception If failed. */
  public void testCompact() throws Exception {
    File file = new File(UUID.randomUUID().toString());

    X.println("file: " + file.getPath());

    FileSwapSpaceSpi.SwapFile f = new FileSwapSpaceSpi.SwapFile(file, 8);

    Random rnd = new Random();

    ArrayList<FileSwapSpaceSpi.SwapValue> arr = new ArrayList<>();

    int size = 0;

    for (int a = 0; a < 100; a++) {
      FileSwapSpaceSpi.SwapValue[] vals = new FileSwapSpaceSpi.SwapValue[1 + rnd.nextInt(10)];

      int size0 = 0;

      for (int i = 0; i < vals.length; i++) {
        byte[] bytes = new byte[1 + rnd.nextInt(49)];

        rnd.nextBytes(bytes);

        size0 += bytes.length;

        vals[i] = new FileSwapSpaceSpi.SwapValue(bytes);

        arr.add(vals[i]);
      }

      f.write(new FileSwapSpaceSpi.SwapValues(vals, size0), 1);

      size += size0;

      assertEquals(f.length(), size);
      assertEquals(file.length(), size);
    }

    int i = 0;

    for (FileSwapSpaceSpi.SwapValue val : arr) assertEquals(val.idx(), ++i);

    i = 0;

    for (int cnt = arr.size() / 2; i < cnt; i++) {

      FileSwapSpaceSpi.SwapValue v = arr.remove(rnd.nextInt(arr.size()));

      assertTrue(f.tryRemove(v.idx(), v));
    }

    int hash0 = 0;

    for (FileSwapSpaceSpi.SwapValue val : arr) hash0 += Arrays.hashCode(val.readValue(f.readCh));

    ArrayList<T2<ByteBuffer, ArrayDeque<FileSwapSpaceSpi.SwapValue>>> bufs = new ArrayList();

    for (; ; ) {
      ArrayDeque<FileSwapSpaceSpi.SwapValue> que = new ArrayDeque<>();

      ByteBuffer buf = f.compact(que, 1024);

      if (buf == null) break;

      bufs.add(new T2(buf, que));
    }

    f.delete();

    int hash1 = 0;

    for (FileSwapSpaceSpi.SwapValue val : arr) hash1 += Arrays.hashCode(val.value(null));

    assertEquals(hash0, hash1);

    File file0 = new File(UUID.randomUUID().toString());

    FileSwapSpaceSpi.SwapFile f0 = new FileSwapSpaceSpi.SwapFile(file0, 8);

    for (T2<ByteBuffer, ArrayDeque<FileSwapSpaceSpi.SwapValue>> t : bufs)
      f0.write(t.get2(), t.get1(), 1);

    int hash2 = 0;

    for (FileSwapSpaceSpi.SwapValue val : arr) hash2 += Arrays.hashCode(val.readValue(f0.readCh));

    assertEquals(hash2, hash1);
  }