protected static void buildAndDeployMavenProject(String basedir) {
   // need to backup (and later restore) the current class loader, because the Maven/Plexus does
   // some classloader
   // magic which then results in CNFE in RestEasy client
   // run the Maven build which will create the kjar. The kjar is then either installed or deployed
   // to local and
   // remote repo
   logger.debug("Building and deploying Maven project from basedir '{}'.", basedir);
   ClassLoader classLoaderBak = Thread.currentThread().getContextClassLoader();
   MavenCli cli = new MavenCli();
   String[] mvnArgs;
   if (TestConfig.isLocalServer()) {
     // just install into local repository when running the local server. Deploying to remote repo
     // will fail
     // if the repo does not exist.
     mvnArgs = new String[] {"-B", "clean", "install"};
   } else {
     mvnArgs = new String[] {"-B", "clean", "deploy"};
   }
   int mvnRunResult = cli.doMain(mvnArgs, basedir, System.out, System.out);
   if (mvnRunResult != 0) {
     throw new RuntimeException(
         "Error while building Maven project from basedir "
             + basedir
             + ". Return code="
             + mvnRunResult);
   }
   Thread.currentThread().setContextClassLoader(classLoaderBak);
   logger.debug("Maven project successfully built and deployed!");
 }
  @Test
  public void testRemovePackage() throws Exception {
    final org.drools.rule.Package pkg1 = new org.drools.rule.Package("org.droos.test");
    pkg1.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg1.addGlobal("global1", Object.class);
    pkg1.addGlobal("global2", Object.class);

    final org.drools.rule.Package pkg2 = new org.drools.rule.Package("org.droos.test");
    pkg2.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg2.addGlobal("global1", Object.class);
    pkg2.addGlobal("global3", Object.class);

    final org.drools.rule.Package pkg3 = new org.drools.rule.Package("org.droos.test2");
    pkg3.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg3.addGlobal("global3", Object.class);
    pkg3.addGlobal("global4", Object.class);

    this.ruleBase.addPackage(pkg1);
    this.ruleBase.addPackage(pkg2);
    this.ruleBase.addPackage(pkg3);

    this.ruleBase.removePackage(pkg1.getName());
    // packages were partially merged when adding, so removal
    // shall left only package 3 behind
    assertLength(1, this.ruleBase.getPackages());
    assertLength(2, this.ruleBase.getGlobals().values());

    this.ruleBase.removePackage(pkg3.getName());
    assertLength(0, this.ruleBase.getPackages());
    assertLength(0, this.ruleBase.getGlobals().values());
  }
  @Test
  public void testAddPackage() throws Exception {
    final org.drools.rule.Package pkg1 = new org.drools.rule.Package("org.droos.test");
    pkg1.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg1.addGlobal("global1", Object.class);
    pkg1.addGlobal("global2", Object.class);

    final org.drools.rule.Package pkg2 = new org.drools.rule.Package("org.droos.test");
    pkg2.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg2.addGlobal("global1", Object.class);
    pkg2.addGlobal("global3", Object.class);

    final org.drools.rule.Package pkg3 = new org.drools.rule.Package("org.droos.test2");
    pkg3.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    pkg3.addGlobal("global3", Object.class);
    pkg3.addGlobal("global4", Object.class);

    this.ruleBase.addPackage(pkg1);
    // one package
    assertLength(1, this.ruleBase.getPackages());
    // two globals
    assertLength(2, this.ruleBase.getGlobals().values());
    // two globals in the package also
    assertLength(2, this.ruleBase.getPackages()[0].getGlobals().values());

    this.ruleBase.addPackage(pkg2);
    // packages merged, so still 1 package
    assertLength(1, this.ruleBase.getPackages());
    // globals merged, so 3 globals total
    assertLength(3, this.ruleBase.getGlobals().values());
    // three globals in the package also
    assertLength(3, this.ruleBase.getPackages()[0].getGlobals().values());

    this.ruleBase.addPackage(pkg3);
    // new package, so now we have 2 package
    assertLength(2, this.ruleBase.getPackages());
    // globals partially merged, so 4 globals total
    assertLength(4, this.ruleBase.getGlobals().values());
    // two globals in the package
    final org.drools.rule.Package[] pkgs = this.ruleBase.getPackages();
    for (int i = 0; i < pkgs.length; i++) {
      if (pkgs[i].getName().equals(pkg3.getName())) {
        assertLength(2, pkgs[i].getGlobals().values());
      }
    }
  }
  @Before
  public void setUp() throws Exception {

    OnConsoleStatusListener.addNewInstanceToContext(loggerContext);
    MDC.clear();
    ServerSetup serverSetup = new ServerSetup(port, "localhost", ServerSetup.PROTOCOL_SMTP);
    greenMailServer = new GreenMail(serverSetup);
    greenMailServer.start();
    // give the server a head start
    if (EnvUtilForTests.isRunningOnSlowJenkins()) {
      Thread.currentThread().sleep(2000);
    } else {
      Thread.currentThread().sleep(50);
    }
  }
Esempio n. 5
0
  @Test
  public void testInterruptTerminalEventAwaitTimed() {
    TestSubscriber<Integer> ts = TestSubscriber.create();

    final Thread t0 = Thread.currentThread();
    Worker w = Schedulers.computation().createWorker();
    try {
      w.schedule(
          new Action0() {
            @Override
            public void call() {
              t0.interrupt();
            }
          },
          200,
          TimeUnit.MILLISECONDS);

      try {
        ts.awaitTerminalEvent(5, TimeUnit.SECONDS);
        fail("Did not interrupt wait!");
      } catch (RuntimeException ex) {
        if (!(ex.getCause() instanceof InterruptedException)) {
          fail("The cause is not InterruptedException! " + ex.getCause());
        }
      }
    } finally {
      w.unsubscribe();
    }
  }
  /*
   * @see DATAREDIS-415
   */
  @Test
  public void interruptAtStart() throws Exception {

    final Thread main = Thread.currentThread();

    // interrupt thread once Executor.execute is called
    doAnswer(
            new Answer<Object>() {

              @Override
              public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {

                main.interrupt();
                return null;
              }
            })
        .when(executorMock)
        .execute(any(Runnable.class));

    container.addMessageListener(adapter, new ChannelTopic("a"));
    container.start();

    // reset the interrupted flag to not destroy the teardown
    assertThat(Thread.interrupted(), is(true));

    assertThat(container.isRunning(), is(false));
  }
 public static ThreadGroup getRootThreadGroup() {
   if (rootThreadGroup != null) return rootThreadGroup;
   ThreadGroup tg = Thread.currentThread().getThreadGroup();
   ThreadGroup ptg;
   while ((ptg = tg.getParent()) != null) tg = ptg;
   return tg;
 }
Esempio n. 8
0
 public void run() {
   boolean live = true;
   Random rand = new Random();
   try {
     for (int j = 0; j < lockCountPerThread && live; j++) {
       final Lock lock = hz.getLock(key + rand.nextInt(locks));
       lock.lock();
       try {
         if (j % 100 == 0) {
           System.out.println(Thread.currentThread().getName() + " is at:" + j);
         }
         totalCount.incrementAndGet();
         Thread.sleep(1);
       } catch (InterruptedException e) {
         e.printStackTrace();
         break;
       } finally {
         try {
           lock.unlock();
         } catch (Exception e) {
           e.printStackTrace();
           live = false;
         }
       }
     }
   } finally {
     latch.countDown();
   }
 }
Esempio n. 9
0
  @Test
  public void testInterruptTerminalEventAwaitAndUnsubscribe() {
    TestSubscriber<Integer> ts = TestSubscriber.create();

    final Thread t0 = Thread.currentThread();
    Worker w = Schedulers.computation().createWorker();
    try {
      w.schedule(
          new Action0() {
            @Override
            public void call() {
              t0.interrupt();
            }
          },
          200,
          TimeUnit.MILLISECONDS);

      ts.awaitTerminalEventAndUnsubscribeOnTimeout(5, TimeUnit.SECONDS);
      if (!ts.isUnsubscribed()) {
        fail("Did not unsubscribe!");
      }
    } finally {
      w.unsubscribe();
    }
  }
  @Before
  public void setUp() {
    this.ruleBase = (ReteooRuleBase) RuleBaseFactory.newRuleBase();

    pkg = new org.drools.rule.Package("org.droos.test");
    pkg.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));

    JavaDialectRuntimeData data = new JavaDialectRuntimeData();
    data.onAdd(pkg.getDialectRuntimeRegistry(), ruleBase.getRootClassLoader());
    pkg.getDialectRuntimeRegistry().setDialectData("java", data);

    // we need to add one rule to the package because the previous deadlock was encountered
    // while removing rules from a package when said package is removed from the rulebase
    rule = new Rule("Test");
    rule.setDialect("java");
    rule.setConsequence(
        new Consequence() {
          public void evaluate(KnowledgeHelper knowledgeHelper, WorkingMemory workingMemory)
              throws Exception {}

          public String getName() {
            return "default";
          }
        });
    pkg.addRule(rule);

    ruleBase.addPackage(pkg);
  }
Esempio n. 11
0
  @Test
  public void test() throws Exception {
    Module module =
        new Module(
            "test",
            new Version("1.0.0", new LiquibaseMigration(), new AntMigration("test-ant_1.0.0.xml")));

    Connection conn = DriverManager.getConnection("jdbc:h2:mem:test", "sa", "sa");
    Path path = Paths.get("solidbase-test-dir");

    try {
      Solidbase solidbase = new Solidbase();
      solidbase.migrate(
          conn, Thread.currentThread().getContextClassLoader(), new H2Database(), module);

      Integer count = selectIntFromDatabase(conn, "SELECT COUNT(*) FROM PERSON");
      assertEquals(0, count.intValue());

      String version =
          selectStringFromDatabase(conn, "SELECT VERSION FROM VERSIONS WHERE MODULE_ID='test'");
      assertEquals("1.0.0", version);

      assertTrue(Files.exists(path));
      assertTrue(Files.isDirectory(path));

    } finally {
      ignoreException(() -> conn.close());
      ignoreException(() -> Files.delete(path));
    }
  }
 @Test
 public void testClassLoaders() {
   ClassLoader current = Thread.currentThread().getContextClassLoader();
   ClassLoader cl1 = new URLClassLoader(new URL[0], current);
   cl1.getParent();
   // TODO
 }
Esempio n. 13
0
  /**
   * This method does all of the setup for the test and returns a HashMap containing the persistence
   * objects that the test might need.
   *
   * @param persistenceUnitName The name of the persistence unit used by the test.
   * @return HashMap<String Object> with persistence objects, such as the EntityManagerFactory and
   *     DataSource
   */
  public static HashMap<String, Object> setupWithPoolingDataSource(
      final String persistenceUnitName, String dataSourceName, final boolean testMarshalling) {
    HashMap<String, Object> context = new HashMap<String, Object>();

    // set the right jdbc url
    Properties dsProps = getDatasourceProperties();
    String jdbcUrl = dsProps.getProperty("url");
    String driverClass = dsProps.getProperty("driverClassName");

    determineTestMarshalling(dsProps, testMarshalling);

    if (TEST_MARSHALLING) {
      Class<?> testClass = null;
      StackTraceElement[] ste = Thread.currentThread().getStackTrace();
      int i = 1;
      do {
        try {
          testClass = Class.forName(ste[i++].getClassName());
        } catch (ClassNotFoundException e) {
          // do nothing..
        }
      } while (PersistenceUtil.class.equals(testClass) && i < ste.length);
      assertNotNull("Unable to resolve test class!", testClass);

      jdbcUrl = initializeTestDb(dsProps, testClass);
    }

    boolean startH2TcpServer = false;
    if (jdbcUrl.matches("jdbc:h2:tcp:.*")) {
      startH2TcpServer = true;
    }

    // Setup the datasource
    PoolingDataSource ds1 = setupPoolingDataSource(dsProps, dataSourceName, startH2TcpServer);
    if (driverClass.startsWith("org.h2")) {
      ds1.getDriverProperties().setProperty("url", jdbcUrl);
    }
    ds1.init();
    context.put(DATASOURCE, ds1);

    // Setup persistence
    EntityManagerFactory emf;
    if (TEST_MARSHALLING) {
      Properties overrideProperties = new Properties();
      overrideProperties.setProperty("hibernate.connection.url", jdbcUrl);
      EntityManagerFactory realEmf =
          Persistence.createEntityManagerFactory(persistenceUnitName, overrideProperties);
      emf = (EntityManagerFactory) EntityManagerFactoryProxy.newInstance(realEmf);

      UserTransaction ut = (UserTransaction) UserTransactionProxy.newInstance(realEmf);
      context.put(TRANSACTION, ut);
    } else {
      emf = Persistence.createEntityManagerFactory(persistenceUnitName);
    }

    context.put(ENTITY_MANAGER_FACTORY, emf);

    return context;
  }
Esempio n. 14
0
 private boolean isCompressionAvailable(String codecClassName) {
   try {
     Thread.currentThread().getContextClassLoader().loadClass(codecClassName);
     return true;
   } catch (Exception ex) {
     return false;
   }
 }
Esempio n. 15
0
 @Override
 public String call(Integer i) throws Exception {
   ClassLoader ccl = Thread.currentThread().getContextClassLoader();
   InputStream in = ccl.getResourceAsStream("test.resource");
   byte[] bytes = ByteStreams.toByteArray(in);
   in.close();
   return new String(bytes, 0, bytes.length, "UTF-8");
 }
Esempio n. 16
0
 @Test
 public void testOutput2() throws Exception {
   File file = writeStrintToFile(testOutput2);
   URL expected =
       Thread.currentThread()
           .getContextClassLoader()
           .getResource("utf8writertest/testOutput2Expected.txt");
   CompressorTestsUtil.filesAreIdentical(file.toURI(), expected.toURI());
 }
  @Test
  public void testOnMode() throws InterruptedException {
    ThreadHistoryUtility.INSTANCE.activate();
    for (int i = 0; i < THREADCOUNT; i++) {
      new Thread(new TestThread()).start();
    }

    Thread.currentThread().sleep(1500);
    assertTrue(ThreadHistoryUtility.INSTANCE.getThreadHistoryEvents().size() > 0);
    int oldsize = ThreadHistoryUtility.INSTANCE.getThreadHistoryEvents().size();

    for (int i = 0; i < THREADCOUNT + 1; i++) {
      new Thread(new TestThread()).start();
    }

    Thread.currentThread().sleep(1500);
    assertTrue(oldsize < ThreadHistoryUtility.INSTANCE.getThreadHistoryEvents().size());
  }
  @Before
  public void setUp() throws Exception {
    store.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);
    this.kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();

    this.buildContext = new BuildContext(kBase, kBase.getReteooBuilder().getIdGenerator());
  }
 public void setUp() {
   String testMethodName = Thread.currentThread().getStackTrace()[2].getMethodName();
   if (testMethodName.startsWith("testPersistenceTimer")) {
     context = PersistenceUtil.setupWithPoolingDataSource(JBPM_PERSISTENCE_UNIT_NAME, false);
   } else {
     context = PersistenceUtil.setupWithPoolingDataSource(JBPM_PERSISTENCE_UNIT_NAME);
   }
   env = PersistenceUtil.createEnvironment(context);
 }
Esempio n. 20
0
  @Before
  public void setUp() throws Exception {
    store.setClassFieldAccessorCache(
        new ClassFieldAccessorCache(Thread.currentThread().getContextClassLoader()));
    store.setEagerWire(true);

    this.kBase = (InternalKnowledgeBase) KnowledgeBaseFactory.newKnowledgeBase();
    buildContext = new BuildContext(kBase, new ReteooBuilder.IdGenerator());
    pctxFactory = kBase.getConfiguration().getComponentFactory().getPropagationContextFactory();
  }
  @Test
  public void testOffMode() throws InterruptedException {
    ThreadHistoryUtility.INSTANCE.deactivate();
    for (int i = 0; i < THREADCOUNT; i++) {
      new Thread(new TestThread()).start();
    }

    Thread.currentThread().sleep(1500);

    assertEquals(0, ThreadHistoryUtility.INSTANCE.getThreadHistoryEvents().size());
  }
 @After
 public void tearDown() throws Exception {
   String base = Thread.currentThread().getContextClassLoader().getResource("").getPath();
   File file = new File(base + "/file/" + "wthtest" + 'a' + "dictionary");
   if (!file.exists()) {
     // fail("file not exist");
   }
   if (file.delete() == false) {
     // fail("file delete not succeed!");
   }
 }
 private static Attributes readFromResource(String name, IncludeBulkData includeBulkData)
     throws Exception {
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   DicomInputStream in = new DicomInputStream(new File(cl.getResource(name).toURI()));
   try {
     in.setIncludeBulkData(includeBulkData);
     in.setAddBulkDataReferences(includeBulkData == IncludeBulkData.URI);
     return in.readDataset(-1, -1);
   } finally {
     in.close();
   }
 }
    @Override
    public Void invoke(MockDatabase database, Void object) {
      synchronized (this) {
        this.latch.countDown();

        try {
          this.wait();
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }
      return null;
    }
  @Test
  public void whenAlreadyInterrupted() {
    Thread.currentThread().interrupt();

    barrier = new VetoCommitBarrier();
    try {
      barrier.tryAwaitOpen(1, TimeUnit.DAYS);
      fail();
    } catch (InterruptedException expected) {
    }

    assertTrue(barrier.isClosed());
  }
  @Test
  public void testLoadSortConfigurationAuthorAsc() throws LoadingSortConfigurationException {
    InputStream configFile =
        Thread.currentThread().getContextClassLoader().getResourceAsStream("config/AuthorAsc.xml");
    SortConfiguration sortConfiguration =
        xmlSortConfigurationLoader.loadSortConfiguration(configFile);

    Iterator<SortAttribute> sortAttributeIterator = sortConfiguration.iterator();
    SortAttribute titleAsc = sortAttributeIterator.next();
    assertEquals(SortAttribute.Attribute.AUTHOR, titleAsc.getAttribute());
    assertEquals(SortAttribute.Direction.ASC, titleAsc.getDirection());
    assertFalse(sortAttributeIterator.hasNext());
  }
Esempio n. 27
0
 @Test
 public void testTTL() throws Exception {
   Config config = new Config();
   FactoryImpl mockFactory = mock(FactoryImpl.class);
   // we mocked the node
   // do not forget to shutdown the connectionManager
   // so that server socket can be released.
   Node node = new Node(mockFactory, config);
   node.serviceThread = Thread.currentThread();
   CMap cmap = new CMap(node.concurrentMapManager, "c:myMap");
   Object key = "1";
   Object value = "istanbul";
   Data dKey = toData(key);
   Data dValue = toData(value);
   Request reqPut = newPutRequest(dKey, dValue);
   reqPut.ttl = 3000;
   cmap.put(reqPut);
   assertTrue(cmap.mapRecords.containsKey(toData(key)));
   Data actualValue = cmap.get(newGetRequest(dKey));
   assertThat(toObject(actualValue), equalTo(value));
   assertEquals(1, cmap.mapRecords.size());
   Record record = cmap.getRecord(dKey);
   assertNotNull(record);
   assertTrue(record.isActive());
   assertTrue(record.isValid());
   assertEquals(1, cmap.size());
   assertNotNull(cmap.get(newGetRequest(dKey)));
   assertEquals(dValue, cmap.get(newGetRequest(dKey)));
   assertTrue(record.getRemainingTTL() > 1000);
   Thread.sleep(1000);
   assertTrue(record.getRemainingTTL() < 2100);
   cmap.put(newPutRequest(dKey, dValue));
   assertTrue(record.getRemainingTTL() > 2001);
   assertTrue(record.isActive());
   assertTrue(record.isValid());
   Thread.sleep(1000);
   assertTrue(record.getRemainingTTL() < 2100);
   cmap.put(newPutRequest(dKey, dValue));
   assertTrue(record.getRemainingTTL() > 2001);
   assertTrue(record.isActive());
   assertTrue(record.isValid());
   Thread.sleep(5000);
   assertEquals(0, cmap.size());
   assertTrue(cmap.evict(newEvictRequest(dKey)));
   assertTrue(cmap.shouldPurgeRecord(record, System.currentTimeMillis() + 10000));
   cmap.removeAndPurgeRecord(record);
   assertEquals(0, cmap.mapRecords.size());
   assertEquals(0, cmap.size());
   assertEquals(0, cmap.mapIndexService.size());
   node.connectionManager.shutdown();
 }
Esempio n. 28
0
 public synchronized void publish(LogRecord record) {
   if (!record.getMessage().startsWith("cnt")) {
     return;
   }
   boolean snd = Thread.currentThread().getName().equals("2nd");
   if (runSecond == snd) {
     notify();
     runSecond = !runSecond;
   }
   try {
     wait(500);
   } catch (InterruptedException ex) {
   }
 }
Esempio n. 29
0
 @Test
 public void sleepInterrupted() {
   long start = System.currentTimeMillis();
   final Thread mainThread = Thread.currentThread();
   new Thread() {
     @Override
     public void run() {
       try {
         Thread.sleep(100);
       } catch (InterruptedException e) {
       }
       mainThread.interrupt();
     }
   }.start();
   try {
     Thread.sleep(300);
     fail("Exception expected");
   } catch (InterruptedException e) {
     assertEquals(Thread.currentThread(), mainThread);
     assertFalse(mainThread.isInterrupted());
     assertTrue(System.currentTimeMillis() - start < 150);
   }
 }
 @Override
 protected void doRun() throws Exception {
   while (true) {
     try {
       if (isShutdown()) {
         break;
       }
       //
       System.out.println("T[" + Thread.currentThread().getId() + "] ");
       ThreadHelper.sleep(1000L);
     } catch (Exception ex) {
       // ex.printStackTrace();
     }
   }
 }