@Test
  public void testContinueOnSomeDbDirectoriesMissing() throws Exception {
    File targetDir1 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    File targetDir2 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());

    try {
      assertTrue(targetDir1.mkdirs());
      assertTrue(targetDir2.mkdirs());

      if (!targetDir1.setWritable(false, false)) {
        System.err.println(
            "Cannot execute 'testContinueOnSomeDbDirectoriesMissing' because cannot mark directory non-writable");
        return;
      }

      RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(TEMP_URI);
      rocksDbBackend.setDbStoragePaths(targetDir1.getAbsolutePath(), targetDir2.getAbsolutePath());

      try {
        rocksDbBackend.initializeForJob(getMockEnvironment(), "foobar", IntSerializer.INSTANCE);
      } catch (Exception e) {
        e.printStackTrace();
        fail("Backend initialization failed even though some paths were available");
      }
    } finally {
      //noinspection ResultOfMethodCallIgnored
      targetDir1.setWritable(true, false);
      FileUtils.deleteDirectory(targetDir1);
      FileUtils.deleteDirectory(targetDir2);
    }
  }
  public void testHomePageAndFeedLinks() {
    try {
      Crawler crawler = new LaRepubblicaCrawler();
      Set<String> set = new HashSet<String>();
      set.addAll(crawler.retrieveArticleUrlsFromFeed());
      set.addAll(crawler.retrieveArticleUrlsFromHomePage());

      Iterator<String> i = set.iterator();
      boolean result = true;
      while (i.hasNext()) {
        String s = i.next();
        try {
          if (crawler.getArticle(s) != null) {
            System.out.println("  OK  >> \t " + s);
            result &= true;
          }
        } catch (CrawlerCannotReadArticleException e) {
          System.err.println("ERROR >> \t " + s);
          result &= false;
          e.printStackTrace();
        }
      }
      assertEquals(true, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Test
  public void testFailWhenNoLocalStorageDir() throws Exception {
    File targetDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
    try {
      assertTrue(targetDir.mkdirs());

      if (!targetDir.setWritable(false, false)) {
        System.err.println(
            "Cannot execute 'testFailWhenNoLocalStorageDir' because cannot mark directory non-writable");
        return;
      }

      RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(TEMP_URI);
      rocksDbBackend.setDbStoragePath(targetDir.getAbsolutePath());

      try {
        rocksDbBackend.initializeForJob(getMockEnvironment(), "foobar", IntSerializer.INSTANCE);
      } catch (Exception e) {
        assertTrue(e.getMessage().contains("No local storage directories available"));
        assertTrue(e.getMessage().contains(targetDir.getAbsolutePath()));
      }
    } finally {
      //noinspection ResultOfMethodCallIgnored
      targetDir.setWritable(true, false);
      FileUtils.deleteDirectory(targetDir);
    }
  }
  @SuppressWarnings("serial")
  private String getTestProductRatePlan(final String productId) {
    SaveResult saveResult = null;

    try {
      saveResult =
          module
              .create(
                  ZObjectType.ProductRatePlan,
                  Collections.<Map<String, Object>>singletonList(
                      new HashMap<String, Object>() {
                        {
                          put("ProductId", productId);
                          put("Name", "TestProductRatePlan");
                          put("EffectiveStartDate", "2011-01-01T20:00:00");
                          put("EffectiveEndDate", "2013-01-01T20:00:00");
                          put("Description", "Test product used in unit test.");
                        }
                      }))
              .get(0);
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }
    return saveResult.getId();
  }
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    con.addCustomer(
        "Buddy", "Bear", "1520 Garnet Ave", "", "San Diego", "CA", "92109", "4766666656");
    con.addPublication("Runner Magazine", "Sports", 9.80, "Monthly", 5);

    ResultSet r = con.searchCustomer(0, "Buddy", "");
    try {
      while (r.next()) {
        testCustID = r.getInt("CustomerID");
      }
      r.close();

    } catch (Exception e) {
      e.printStackTrace();
    }

    ResultSet rs = con.searchPublication(0, "", "Runner Magazine");

    try {
      while (rs.next()) {
        testPubID = rs.getInt("PublicationID");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    subscriptions newSub = new subscriptions(testCustID, testPubID);
  }
  @Test
  public void testClusterInitialization() {
    try {
      Cluster cluster = defaultFactory.getCluster("Cluster Un");
      assertNotNull("Test cluster should not be null", cluster);

      // now check that it has the data we expect from the database
      assertEquals("Wrong ID Found", 1000L, cluster.getId());
      assertEquals("Wrong name found", "Cluster Un", cluster.getName());

      // Now check for the master node
      Node master = cluster.getMaster();
      assertNotNull("Master node for cluster should not be null", master);
      assertEquals(
          "Unexpected name for master found", "Cluster 0 - Primary master", master.getName());
      assertEquals("Unexpected ID for master found", 1L, master.getId());
      assertTrue("Master should be available", master.isAvailable());

      // Now check for the slave nodes
      Set<Node> slaves = cluster.getSlaves();
      assertNotNull("Slave node set should not be null", slaves);
      assertEquals("Unexpected length for slave node set", 2, slaves.size());
    } catch (Exception e) {
      e.printStackTrace();
      fail("Exception caught: " + e.getLocalizedMessage());
    }
  }
  @Test
  public void testPollBatch() {
    try {
      ClosableBlockingQueue<String> queue = new ClosableBlockingQueue<>();

      assertNull(queue.pollBatch());

      queue.add("a");
      queue.add("b");

      assertEquals(asList("a", "b"), queue.pollBatch());
      assertNull(queue.pollBatch());

      queue.add("c");

      assertEquals(singletonList("c"), queue.pollBatch());
      assertNull(queue.pollBatch());

      assertTrue(queue.close());

      try {
        queue.pollBatch();
        fail("should cause an exception");
      } catch (IllegalStateException ignored) {
        // expected
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
 protected boolean execute(int address, String expectedOutput) {
   boolean isSuccess = false;
   Cpu cpu = computer.getCpu();
   cpu.writeRegister(false, Cpu.PC, address);
   long startTime = System.currentTimeMillis();
   while ((System.currentTimeMillis() - startTime) < MAX_EXECUTION_TIME
       || terminal.getWrittenData().length() > Terminal.MAX_DATA_LENGTH) {
     try {
       cpu.executeNextOperation();
       if (cpu.isHaltMode()) {
         throw new IllegalStateException("HALT mode");
       }
     } catch (Exception e) {
       e.printStackTrace();
       fail(
           "can't execute operation, PC: 0"
               + Integer.toOctalString(cpu.readRegister(false, Cpu.PC)));
     }
     if (expectedOutput.equals(terminal.getWrittenData())) {
       isSuccess = true;
       break;
     }
   }
   return isSuccess;
 }
  /**
   * Test method for {@link
   * org.talend.dataquality.standardization.record.SynonymRecordSearcher#addSearcher(org.talend.dataquality.standardization.index.SynonymIndexSearcher,
   * int)} .
   */
  @Test
  public void testAddSearcher() {
    SynonymRecordSearcher recSearcher = new SynonymRecordSearcher(2);
    try {
      recSearcher.addSearcher(null, 0);
    } catch (Exception e) {
      Assert.assertNotNull("we should get an exception here", e);
    }
    try {
      recSearcher.addSearcher(new SynonymIndexSearcher(), 2);
      Assert.fail(
          "Index should be out of bounds here: trying to set a searcher at position in an empty array");
    } catch (Exception e) {
      Assert.assertNotNull("we should get an exception here", e);
    } catch (java.lang.AssertionError e) {
      Assert.assertNotNull(
          "we should get an assertion error here when -ea is added to the VM arguments", e);
    }

    try {
      SynonymIndexSearcher searcher = new SynonymIndexSearcher();
      recSearcher.addSearcher(searcher, 1);
    } catch (Exception e) {
      fail(e.getMessage());
    }

    try {
      SynonymIndexSearcher searcher = new SynonymIndexSearcher();
      recSearcher.addSearcher(searcher, -1);
    } catch (Exception e) {
      Assert.assertNotNull("we should get an exception here", e);
    }
  }
  @Test
  public void testPostEmployee() {
    if (null == cookie) {
      fail("cannot login!!!");
    }
    Employee ep1 = generateEmployee();

    try {
      ResteasyClient client = new ResteasyClientBuilder().build();

      WebTarget target = client.target(baseUrl + "/rest/ag/employee");
      client.register(new CookieRequestFilter(cookie));

      Response response = target.request().post(Entity.entity(ep1, "application/json"));

      if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
      }

      Employee value = response.readEntity(Employee.class);
      System.out.println("Server response : \n");
      System.out.println(value.toString());

      assertEquals("same first name", "Special", value.getFirstName());

      client.close();

    } catch (Exception e) {

      e.printStackTrace();
    }
  }
  /**
   * 测试列分隔符,不能够包含行分隔符,出错 <br>
   * 命令:upload test_data.txt test_table -rd "||" -fd "||||"<br>
   */
  @Test
  public void testFailDelimiterInclude() {

    String[] args;

    try {
      args =
          new String[] {
            "upload",
            "src/test/resources/test_data.txt",
            "test_table/ds='2113',pt='pttest'",
            "-field-delimiter",
            "||||",
            "-record-delimiter",
            "||",
            "-charset=gbk"
          };
      OptionsBuilder.buildUploadOption(args);

      // MockUploadSession us = new MockUploadSession(context);
      // SessionHistory sh = SessionHistoryManager.createSessionHistory("xxxx");
      // FileUploader uploader = new FileUploader(new File(context.get(Constants.RESUME_PATH)), us,
      // sh);
      fail("need fail");
    } catch (Exception e) {

      assertTrue(
          "need include bad command",
          e.getMessage().indexOf("Field delimiter can not include record delimiter") >= 0);
    }
  }
  @Test
  public void testTopologicalSort1() {
    try {
      AbstractJobVertex source1 = new AbstractJobVertex("source1");
      AbstractJobVertex source2 = new AbstractJobVertex("source2");
      AbstractJobVertex target1 = new AbstractJobVertex("target1");
      AbstractJobVertex target2 = new AbstractJobVertex("target2");
      AbstractJobVertex intermediate1 = new AbstractJobVertex("intermediate1");
      AbstractJobVertex intermediate2 = new AbstractJobVertex("intermediate2");

      target1.connectNewDataSetAsInput(source1, DistributionPattern.POINTWISE);
      target2.connectNewDataSetAsInput(source1, DistributionPattern.POINTWISE);
      target2.connectNewDataSetAsInput(intermediate2, DistributionPattern.POINTWISE);
      intermediate2.connectNewDataSetAsInput(intermediate1, DistributionPattern.POINTWISE);
      intermediate1.connectNewDataSetAsInput(source2, DistributionPattern.POINTWISE);

      JobGraph graph =
          new JobGraph(
              "TestGraph", source1, source2, intermediate1, intermediate2, target1, target2);
      List<AbstractJobVertex> sorted = graph.getVerticesSortedTopologicallyFromSources();

      assertEquals(6, sorted.size());

      assertBefore(source1, target1, sorted);
      assertBefore(source1, target2, sorted);
      assertBefore(source2, target2, sorted);
      assertBefore(source2, intermediate1, sorted);
      assertBefore(source2, intermediate2, sorted);
      assertBefore(intermediate1, target2, sorted);
      assertBefore(intermediate2, target2, sorted);
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
  @Test
  public void testTopoSortCyclicGraphIntermediateCycle() {
    try {
      AbstractJobVertex source = new AbstractJobVertex("source");
      AbstractJobVertex v1 = new AbstractJobVertex("1");
      AbstractJobVertex v2 = new AbstractJobVertex("2");
      AbstractJobVertex v3 = new AbstractJobVertex("3");
      AbstractJobVertex v4 = new AbstractJobVertex("4");
      AbstractJobVertex target = new AbstractJobVertex("target");

      v1.connectNewDataSetAsInput(source, DistributionPattern.POINTWISE);
      v1.connectNewDataSetAsInput(v4, DistributionPattern.POINTWISE);
      v2.connectNewDataSetAsInput(v1, DistributionPattern.POINTWISE);
      v3.connectNewDataSetAsInput(v2, DistributionPattern.POINTWISE);
      v4.connectNewDataSetAsInput(v3, DistributionPattern.POINTWISE);
      target.connectNewDataSetAsInput(v3, DistributionPattern.POINTWISE);

      JobGraph jg = new JobGraph("Cyclic Graph", v1, v2, v3, v4, source, target);
      try {
        jg.getVerticesSortedTopologicallyFromSources();
        fail("Failed to raise error on topologically sorting cyclic graph.");
      } catch (InvalidProgramException e) {
        // that what we wanted
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
  @Test
  public void testTopologicalSort3() {
    //             --> op1 --
    //            /         \
    //  (source) -           +-> op2 -> op3
    //            \         /
    //             ---------

    try {
      AbstractJobVertex source = new AbstractJobVertex("source");
      AbstractJobVertex op1 = new AbstractJobVertex("op4");
      AbstractJobVertex op2 = new AbstractJobVertex("op2");
      AbstractJobVertex op3 = new AbstractJobVertex("op3");

      op1.connectNewDataSetAsInput(source, DistributionPattern.POINTWISE);
      op2.connectNewDataSetAsInput(op1, DistributionPattern.POINTWISE);
      op2.connectNewDataSetAsInput(source, DistributionPattern.POINTWISE);
      op3.connectNewDataSetAsInput(op2, DistributionPattern.POINTWISE);

      JobGraph graph = new JobGraph("TestGraph", source, op1, op2, op3);
      List<AbstractJobVertex> sorted = graph.getVerticesSortedTopologicallyFromSources();

      assertEquals(4, sorted.size());

      assertBefore(source, op1, sorted);
      assertBefore(source, op2, sorted);
      assertBefore(op1, op2, sorted);
      assertBefore(op2, op3, sorted);
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
Example #15
0
  @Test
  public void testOutputFormatVertex() {
    try {
      final TestingOutputFormat outputFormat = new TestingOutputFormat();
      final OutputFormatVertex of = new OutputFormatVertex("Name");
      new TaskConfig(of.getConfiguration())
          .setStubWrapper(new UserCodeObjectWrapper<OutputFormat<?>>(outputFormat));
      final ClassLoader cl = getClass().getClassLoader();

      try {
        of.initializeOnMaster(cl);
        fail("Did not throw expected exception.");
      } catch (TestException e) {
        // all good
      }

      OutputFormatVertex copy = SerializationUtils.clone(of);
      try {
        copy.initializeOnMaster(cl);
        fail("Did not throw expected exception.");
      } catch (TestException e) {
        // all good
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
Example #16
0
  /**
   * method will test the set bytes method of the stack segment
   *
   * @throws StackException
   */
  @Test
  public void testSetBytes() throws StackException {
    { // valid write (no growth of stack)
      StackSegment stack = createStack(10, 0);
      assertEquals(4, stack.size());
      stack.setBytes(0, new byte[] {0x11, 0x10, 0x11, 0x10});
      assertEquals(4, stack.size());
      assertEquals(0x11, stack.getBytes(0, 4)[0]);
      assertEquals(0x10, stack.getBytes(0, 4)[1]);
      assertEquals(0x11, stack.getBytes(0, 4)[2]);
      assertEquals(0x10, stack.getBytes(0, 4)[3]);
    }

    { // valid write (growth of stack)
      StackSegment stack = createStack(10, 0);
      assertEquals(4, stack.size());
      stack.setBytes(2, new byte[] {0x00, 0x11, 0x10, 0x01});
      assertEquals(6, stack.size());
      assertEquals(0x00, stack.getBytes(2, 4)[0]);
      assertEquals(0x11, stack.getBytes(2, 4)[1]);
      assertEquals(0x10, stack.getBytes(2, 4)[2]);
      assertEquals(0x01, stack.getBytes(2, 4)[3]);
    }

    { // valid write (outside force growth)
      StackSegment stack = createStack(10, 0);
      assertEquals(4, stack.size());
      try {
        stack.setBytes(5, new byte[] {0x11, 0x10});
        fail();
      } catch (StackException e) {
        assertTrue(e.getMessage().equals("Invalid write onto stack."));
      }
    }

    { // stack overflow test
      StackSegment stack = createStack(10, 0);
      assertEquals(4, stack.size());
      try {
        stack.setBytes(
            0, new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
        fail();
      } catch (Exception e) {
        assertTrue(e.getMessage().equals("Stack overflow."));
      }
    }

    { // stack overflow test 2 (in more stages)
      StackSegment stack = createStack(10, 0);
      assertEquals(4, stack.size());
      try {
        stack.setBytes(0, new byte[] {0x00, 0x00, 0x00, 0x00, 0x00});
        stack.setBytes(5, new byte[] {0x00, 0x00, 0x00, 0x00, 0x00});
        stack.setBytes(10, new byte[] {0x00});
        fail();
      } catch (Exception e) {
        assertTrue(e.getMessage().equals("Stack overflow."));
      }
    }
  }
  /** Test of SavePersonData method, of class MetadataRDFConverter. */
  @Test
  public void testSavePersonData() {
    System.out.println("* MetadataRDFConverterTest: SavePersonData");
    try {
      foaf_Person oPersonNull = null;
      OntModel oModel = MetadataGlobal.LoadOWL(MetadataConstants.sLocationLoadAlert);
      MetadataRDFConverter.SavePersonData(oPersonNull, oModel);
      MetadataGlobal.SaveOWL(oModel, MetadataConstants.sLocationSaveAlert);

      foaf_Person oPerson = new foaf_Person();
      oPerson.m_sFirstName = "Ivan";
      oPerson.m_sLastName = "Obradovic";
      // oPerson.m_sGender = ""; //???
      oPerson.m_sID = "*****@*****.**";
      oPerson.m_sEmail = "*****@*****.**"; // ???
      MetadataRDFConverter.SavePersonData(oPerson, oModel);
      MetadataGlobal.SaveOWL(oModel, MetadataConstants.sLocationSaveAlert);
      assertNotNull(oPerson);
      assertEquals(oPerson.m_sObjectURI.isEmpty(), false);

      //// TO-DO review the generated test code and remove the default call to fail.
      // fail("The test case is a prototype.");
    } catch (Exception ex) {
      System.out.println("Error: " + ex.getMessage());
    }
  }
  /**
   * checkEnvのテストケース 異常系:"ASAKUSA_HOME"の設定が不正のケース
   *
   * @throws Exception
   */
  @Test
  public void checkEnvTest04() throws Exception {
    ConfigurationLoader.init(properties_db, true, false);
    Map<String, String> m = new HashMap<String, String>();
    m.put(Constants.ASAKUSA_HOME, "J:\temp");
    m.put(
        Constants.THUNDER_GATE_HOME,
        ConfigurationLoader.getEnvProperty(Constants.THUNDER_GATE_HOME));
    ConfigurationLoader.setEnv(m);

    Properties p = System.getProperties();
    p.setProperty(Constants.ASAKUSA_HOME, "J:\temp");
    p.setProperty(Constants.THUNDER_GATE_HOME, "src/test");
    ConfigurationLoader.setSysProp(p);
    System.setProperties(p);

    try {
      ConfigurationLoader.checkEnv();
      fail();
    } catch (Exception e) {
      assertTrue(e instanceof Exception);
      System.out.println(e.getMessage());
      e.printStackTrace();
    }
  }
  @Test
  public void testCloseNonEmptyQueue() {
    try {
      ClosableBlockingQueue<Integer> queue = new ClosableBlockingQueue<>(asList(1, 2, 3));
      assertTrue(queue.isOpen());

      assertFalse(queue.close());
      assertFalse(queue.close());

      queue.poll();

      assertFalse(queue.close());
      assertFalse(queue.close());

      queue.pollBatch();

      assertTrue(queue.close());
      assertFalse(queue.isOpen());

      assertFalse(queue.addIfOpen(42));
      assertTrue(queue.isEmpty());

      try {
        queue.add(99);
        fail("should cause an exception");
      } catch (IllegalStateException ignored) {
        // expected
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
Example #20
0
  @Test
  public void testMain() {
    // Usage が標準出力に表示されること
    // main.main(null);

    String[] args = {
      "test/sim/simulator_raposda_2.xml",
      "test/sim/memoryModel.xml",
      "test/sim/dataDiskModel.xml",
      "test/sim/cacheDiskModel.xml",
      "test/sim/workload",
      "on",
      "on",
      "test/sim/out"
    };
    try {
      SimMain.main(args);
    } catch (Exception e) {
      e.printStackTrace();
      fail("Exceptionが発生しました.");
    }

    RAPoSDALayoutManager layoutManager = (RAPoSDALayoutManager) Environment.getLayoutManager();
    layoutManager.debugCreateManagedDevices();
    layoutManager.debugDeviceMapping();
  }
Example #21
0
  @Test
  public void
      testAuthenticateValidAuthInHeaderAndUserInDataStoreButNotAuthorizedToRunAsAnotherUser()
          throws Exception {
    UserObjectifyDAOImpl userDAO = new UserObjectifyDAOImpl();

    User dbuser = new User();
    dbuser.setLogin("bob");
    dbuser.setToken("smith");
    dbuser.setPermissions(Permission.LIST_ALL_JOBS);
    dbuser = userDAO.insert(dbuser);

    AuthenticatorImpl auth = new AuthenticatorImpl();
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getRemoteAddr()).thenReturn("192.168.1.1");
    when(request.getHeader(AuthenticatorImpl.AUTHORIZATION_HEADER))
        .thenReturn("Basic " + encodeString("bob:smith"));
    when(request.getParameter(Constants.USER_LOGIN_TO_RUN_AS_PARAM)).thenReturn("joe");

    try {
      auth.authenticate(request);
    } catch (Exception ex) {
      assertTrue(ex.getMessage().equals("User does not have permission to run as another user"));
    }
  }
Example #22
0
  private Player getPlayer(Element el) {

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    Player p = new Player();

    try {

      String guid = el.getAttribute("id");
      String firstName = el.getAttribute("name_first");
      String lastName = el.getAttribute("name_last");
      String bdate = el.getAttribute("birthdate");
      String height = el.getAttribute("height");
      String weight = el.getAttribute("weight");
      String college = el.getAttribute("college");
      String position = el.getAttribute("position");
      String jersey = el.getAttribute("jersey_number");

      p.setId(guid);
      p.setFirstName(firstName);
      p.setLastName(lastName);
      p.setCollege(college);
      p.setPosition(position);
      p.setHeight(Integer.parseInt(height));
      p.setWeight(Integer.parseInt(weight));
      p.setBirthdate(formatter.parse(bdate));
      p.setJerseyNumber(Integer.parseInt(jersey));

    } catch (Exception e) {
      e.printStackTrace();
    }

    return p;
  }
Example #23
0
  @Test
  public void testLoadFlush() {
    DataAccess da = createDataAccess(name);
    assertFalse(da.loadExisting());
    da.create(300);
    da.setInt(7 * 4, 123);
    assertEquals(123, da.getInt(7 * 4));
    da.setInt(10 * 4, Integer.MAX_VALUE / 3);
    assertEquals(Integer.MAX_VALUE / 3, da.getInt(10 * 4));
    da.flush();

    // check noValue clearing
    assertEquals(0, da.getInt(2 * 4));
    assertEquals(0, da.getInt(3 * 4));
    assertEquals(123, da.getInt(7 * 4));
    assertEquals(Integer.MAX_VALUE / 3, da.getInt(10 * 4));
    da.close();

    // cannot load data if already closed
    try {
      da.loadExisting();
      assertTrue(false);
    } catch (Exception ex) {
      assertEquals("already closed", ex.getMessage());
    }

    da = createDataAccess(name);
    assertTrue(da.loadExisting());
    assertEquals(123, da.getInt(7 * 4));
    da.close();
  }
 @Before
 public void setUp() {
   try {
     Class.forName("com.intersys.jdbc.CacheDriver").newInstance();
   } catch (InstantiationException ex) {
     System.out.print(ex.getMessage());
   } catch (Exception ex) {
     System.out.print(ex.getMessage());
   }
   CacheDataSource ds = new CacheDataSource();
   try {
     ds.setURL("jdbc:Cache://192.168.1.172:56773/USER");
   } catch (SQLException ex) {
     System.out.println(ex.getMessage());
   }
   java.sql.Connection dbconn = null;
   try {
     dbconn = ds.getConnection("_SYSTEM", "SYS");
   } catch (SQLException ex) {
     Logger.getLogger(DatabaseDAOTests.class.getName()).log(Level.SEVERE, null, ex);
   }
   try {
     db = CacheDatabase.getDatabase(dbconn);
   } catch (CacheException ex) {
     System.out.print(ex.getMessage());
   }
   dbDao = new DatabaseDAO(dbconn, db);
 }
  @SuppressWarnings("serial")
  private String getTestProduct() {

    Map<String, Object> returnMap = new HashMap<String, Object>();

    SaveResult saveResult = null;

    try {
      saveResult =
          module
              .create(
                  ZObjectType.Product,
                  Collections.<Map<String, Object>>singletonList(
                      new HashMap<String, Object>() {
                        {
                          put("Name", "UnitTestProduct");
                          put("EffectiveStartDate", "2011-01-01T20:00:00");
                          put("EffectiveEndDate", "2013-01-01T20:00:00");
                        }
                      }))
              .get(0);
    } catch (Exception e) {
      e
          .printStackTrace(); // To change body of catch statement use File | Settings | File
                              // Templates.
    }

    return saveResult.getId();
  }
  @Test
  public void testNonEqualSplitsPerhost() {
    int numHosts = 3;
    int slotsPerHost = 2;
    int parallelism = 5;

    TestLocatableInputSplit[] splits =
        new TestLocatableInputSplit[] {
          new TestLocatableInputSplit(1, "host3"),
          new TestLocatableInputSplit(2, "host1"),
          new TestLocatableInputSplit(3, "host1"),
          new TestLocatableInputSplit(4, "host1"),
          new TestLocatableInputSplit(5, "host1"),
          new TestLocatableInputSplit(6, "host1"),
          new TestLocatableInputSplit(7, "host2"),
          new TestLocatableInputSplit(8, "host2")
        };

    try {
      String[] hostsForTasks = runTests(numHosts, slotsPerHost, parallelism, splits);

      assertEquals("host1", hostsForTasks[0]);
      assertEquals("host1", hostsForTasks[1]);
      assertEquals("host2", hostsForTasks[2]);
      assertEquals("host2", hostsForTasks[3]);
      assertEquals("host3", hostsForTasks[4]);
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
Example #27
0
 void report(Exception e) {
   System.out.println("Exception occurred:");
   System.out.println(e.toString());
   e.printStackTrace(System.err);
   report2(e);
   //        failed();
 }
  @Test
  public void testNotEnoughSubtasks() {
    int numHosts = 3;
    int slotsPerHost = 1;
    int parallelism = 2;

    TestLocatableInputSplit[] splits =
        new TestLocatableInputSplit[] {
          new TestLocatableInputSplit(1, "host1"),
          new TestLocatableInputSplit(2, "host2"),
          new TestLocatableInputSplit(3, "host3")
        };

    // This should fail with an exception, since the DOP of 2 does not
    // support strictly local assignment onto 3 hosts
    try {
      runTests(numHosts, slotsPerHost, parallelism, splits);
      fail("should throw an exception");
    } catch (JobException e) {
      // what a great day!
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
  @Test
  public void testPersistence() {
    try {

      em.getTransaction().begin();

      Student u = new Student();
      u.setScore(12);
      u.setName("eskatos");

      em.persist(u);
      assertTrue(em.contains(u));

      em.remove(u);

      assertFalse(em.contains(u));

      em.getTransaction().commit();

    } catch (Exception ex) {
      em.getTransaction().rollback();
      ex.printStackTrace();
      fail("Exception during testPersistence");
    }
  }
  // Test for [JACKSON-631]
  public void testBase64Text() throws Exception {
    // let's actually iterate over sets of encoding modes, lengths

    final int[] LENS = {1, 2, 3, 4, 7, 9, 32, 33, 34, 35};
    final Base64Variant[] VARIANTS = {
      Base64Variants.MIME,
      Base64Variants.MIME_NO_LINEFEEDS,
      Base64Variants.MODIFIED_FOR_URL,
      Base64Variants.PEM
    };

    for (int len : LENS) {
      byte[] input = new byte[len];
      for (int i = 0; i < input.length; ++i) {
        input[i] = (byte) i;
      }
      for (Base64Variant variant : VARIANTS) {
        TextNode n = new TextNode(variant.encode(input));
        byte[] data = null;
        try {
          data = n.getBinaryValue(variant);
        } catch (Exception e) {
          throw new IOException(
              "Failed (variant " + variant + ", data length " + len + "): " + e.getMessage());
        }
        assertNotNull(data);
        assertArrayEquals(data, input);
      }
    }
  }