/** Implementation of Runnable interface. DO NOT access this method directly. */
 public void run() {
   GUIUtils.setAnimatedFrameIgnoreRepaint(
       true); // animated frames are updated by this thread so no need to repaint
   long sleepTime = delayTime;
   while (animationThread == Thread.currentThread()) {
     long currentTime = System.currentTimeMillis();
     for (int i = 0; i < stepsPerDisplay; i++) {
       doStep();
       stepCounter++;
       if (animationThread != Thread.currentThread()) {
         break; // check for stop condition
       } else {
         Thread.yield(); // give other threads a chance to run if needed
       }
     }
     org.opensourcephysics.display.GUIUtils.renderAnimatedFrames();
     // adjust the sleep time to try and achieve a constant animation rate
     // some VMs will hang if sleep time is less than 10
     sleepTime = Math.max(10, delayTime - (System.currentTimeMillis() - currentTime));
     try {
       Thread.sleep(sleepTime);
     } catch (InterruptedException ie) {
     }
   }
   GUIUtils.setAnimatedFrameIgnoreRepaint(
       false); // animated frames are updated by this thread so no need to repaint
 }
Ejemplo n.º 2
0
  public GameContext getContext() {

    if (allContexts == null) {
      return mainContext;
    }

    synchronized (this) {
      if (allContexts == null) {
        return mainContext;
      }

      ThreadGroup currentThreadGroup = Thread.currentThread().getThreadGroup();
      for (int i = 0; i < allContexts.size(); i++) {
        GameContext context = (GameContext) allContexts.get(i);
        ThreadGroup contextThreadGroup = context.getThreadGroup();
        if (contextThreadGroup == currentThreadGroup
            || contextThreadGroup.parentOf(currentThreadGroup)) {
          return context;
        }
      }

      if (initContext != null && Thread.currentThread() == initContextThread) {
        return initContext;
      }

      return (GameContext) (allContexts.get(GameContext.nextContextID - 1));
    }
  }
Ejemplo n.º 3
0
 @Override
 public void run() {
   /* Legacy UDP location manager daemon.
    */
   DatagramPacket packet;
   while (!Thread.currentThread().isInterrupted()) {
     try {
       packet = new DatagramPacket(new byte[1024], 1024);
       socket.receive(packet);
     } catch (SocketException e) {
       if (!Thread.currentThread().isInterrupted()) {
         LOGGER.warn("Exception in Server receive loop (exiting)", e);
       }
       break;
     } catch (Exception ie) {
       LOGGER.warn("Exception in Server receive loop (exiting)", ie);
       break;
     }
     try {
       process(packet);
       socket.send(packet);
     } catch (Exception se) {
       LOGGER.warn("Exception in send ", se);
     }
   }
   socket.close();
 }
  /**
   * Load the application context using a single classloader
   *
   * @param ac The spring application context
   * @param config a list of configurations represented as List of resources
   * @param loader the classloader to use
   */
  public void loadComponent(
      ConfigurableApplicationContext ac, List<Resource> config, ClassLoader loader) {
    ClassLoader current = Thread.currentThread().getContextClassLoader();

    Thread.currentThread().setContextClassLoader(loader);

    try {

      // make a reader
      XmlBeanDefinitionReader reader =
          new XmlBeanDefinitionReader((BeanDefinitionRegistry) ac.getBeanFactory());

      // In Spring 2, classes aren't loaded during bean parsing unless
      // this
      // classloader property is set.
      reader.setBeanClassLoader(loader);

      reader.loadBeanDefinitions(config.toArray(new Resource[0]));
    } catch (Throwable t) {
      log.warn("loadComponentPackage: exception loading: " + config + " : " + t, t);
    } finally {
      // restore the context loader
      Thread.currentThread().setContextClassLoader(current);
    }
  }
Ejemplo n.º 5
0
 @SuppressWarnings("unchecked")
 private Work openEditor(String editorClassName, WorkDefinition workDefinition) {
   IJavaProject javaProject = getProject();
   if (javaProject != null) {
     try {
       ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
       ClassLoader newLoader = ProjectClassLoader.getProjectClassLoader(javaProject);
       try {
         Thread.currentThread().setContextClassLoader(newLoader);
         Class<WorkEditor> editorClass = (Class<WorkEditor>) newLoader.loadClass(editorClassName);
         Constructor<WorkEditor> constructor = editorClass.getConstructor(Shell.class);
         WorkEditor editor = constructor.newInstance(getViewer().getControl().getShell());
         editor.setWorkDefinition(workDefinition);
         WorkItemNode workItemNode = getWorkItemWrapper().getWorkItemNode();
         editor.setWork(workItemNode.getWork());
         boolean result = editor.show();
         return result ? editor.getWork() : null;
       } finally {
         Thread.currentThread().setContextClassLoader(oldLoader);
       }
     } catch (Exception e) {
       DroolsEclipsePlugin.log(e);
     }
   }
   return null;
 }
    /*
     * Use PIN or PUK to unlock SIM card
     *
     * If PUK is null, unlock SIM card with PIN
     *
     * If PUK is not null, unlock SIM card with PUK and set PIN code
     */
    synchronized boolean unlockSim(String puk, String pin) {

      while (mHandler == null) {
        try {
          wait();
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }
      Message callback = Message.obtain(mHandler, SUPPLY_PIN_COMPLETE);

      if (puk == null) {
        mSimCard.supplyPin(pin, callback);
      } else {
        mSimCard.supplyPuk(puk, pin, callback);
      }

      while (!mDone) {
        try {
          Log.d(LOG_TAG, "wait for done");
          wait();
        } catch (InterruptedException e) {
          // Restore the interrupted status
          Thread.currentThread().interrupt();
        }
      }
      Log.d(LOG_TAG, "done");
      return mResult;
    }
Ejemplo n.º 7
0
  /**
   * Closes all connected clients sockets, then closes the underlying ServerSocketChannel,
   * effectively killing the server socket selectorthread, freeing the port the server was bound to
   * and stops all internal workerthreads.
   *
   * <p>If this method is called before the server is started it will never start.
   *
   * @param timeout Specifies how many milliseconds shall pass between initiating the close
   *     handshakes with the connected clients and closing the servers socket channel.
   * @throws IOException When {@link ServerSocketChannel}.close throws an IOException
   * @throws InterruptedException
   */
  public void stop(int timeout) throws IOException, InterruptedException {
    if (!isclosed.compareAndSet(false, true)) {
      return;
    }

    synchronized (connections) {
      for (WebSocket ws : connections) {
        ws.close(CloseFrame.GOING_AWAY);
      }
    }
    synchronized (this) {
      if (selectorthread != null) {
        if (Thread.currentThread() != selectorthread) {}

        if (selectorthread != Thread.currentThread()) {
          selectorthread.interrupt();
          selectorthread.join();
        }
      }
      if (decoders != null) {
        for (WebSocketWorker w : decoders) {
          w.interrupt();
        }
      }
      if (server != null) {
        server.close();
      }
    }
  }
Ejemplo n.º 8
0
  public void send_request(ClientRequestInfo ri) throws ForwardRequest {
    try {
      org.omg.CORBA.Any any = ri.get_slot(slot_id);

      if (any.type().kind().value() == org.omg.CORBA.TCKind._tk_null) {
        logger.debug(
            "tid="
                + Thread.currentThread().getName()
                + ","
                + "ClientInterceptor.send_request, slot is empty");
      } else {
        logger.debug(
            "tid="
                + Thread.currentThread().getName()
                + ","
                + "ClientInterceptor.send_request, adding ServiceContext");

        ServiceContext ctx = new ServiceContext(SERVICE_ID, codec.encode(any));

        ri.add_request_service_context(ctx, false);
      }
    } catch (Exception e) {
      throw new INTERNAL("Caught " + e);
    }
  }
Ejemplo n.º 9
0
  public void receive_request_service_contexts(ServerRequestInfo ri) {
    ServiceContext ctx;
    try {
      ctx = ri.get_request_service_context(SERVICE_ID);
    } catch (org.omg.CORBA.BAD_PARAM e) {
      logger.debug(
          "tid=" + Thread.currentThread().getName() + "," + "**Service context was not specified");
      return;
    }

    if (null == ctx) {
      logger.debug("tid=" + Thread.currentThread().getName() + "," + "**Service context is null");
      return;
    }

    try {
      Any slotDataAsAny = codec.decode(ctx.context_data);

      // Get the slot data as a string
      String slotDataAsStr;
      if (null == (slotDataAsStr = slotDataAsAny.extract_string())) {
        logger.debug("slotDataAsStr=<null>");
      } else {
        logger.debug("slotDataAsStr=" + slotDataAsStr);
      }

      slotDataAsStr += ":receive_request_service_contexts";

      slotDataAsAny.insert_string(slotDataAsStr);

      ri.set_slot(slot_id, slotDataAsAny);
    } catch (Exception e) {
      throw new INTERNAL("Caught " + e);
    }
  }
 /**
  * the usage of getResponseByParams is disencouraged for the embedded Solr connector. Please use
  * request(SolrParams) instead. Reason: Solr makes a very complex folding/unfolding including data
  * compression for SolrQueryResponses.
  */
 @Override
 public QueryResponse getResponseByParams(ModifiableSolrParams params) throws IOException {
   if (this.server == null) throw new IOException("server disconnected");
   // during the solr query we set the thread name to the query string to get more debugging info
   // in thread dumps
   String threadname = Thread.currentThread().getName();
   String ql = "";
   try {
     ql = URLDecoder.decode(params.toString(), StandardCharsets.UTF_8.name());
   } catch (UnsupportedEncodingException e) {
   }
   Thread.currentThread().setName("solr query: q=" + ql);
   ConcurrentLog.info("EmbeddedSolrConnector.getResponseByParams", "QUERY: " + ql);
   // System.out.println("EmbeddedSolrConnector.getResponseByParams * QUERY: " + ql);
   // System.out.println("STACKTRACE: " + ConcurrentLog.stackTrace());
   QueryResponse rsp;
   try {
     rsp = this.server.query(params);
     Thread.currentThread().setName(threadname);
     if (rsp != null)
       if (log.isFine()) log.fine(rsp.getResults().getNumFound() + " results for " + ql);
     return rsp;
   } catch (final SolrServerException e) {
     throw new IOException(e);
   } catch (final Throwable e) {
     throw new IOException("Error executing query", e);
   }
 }
 /**
  * get the solr document list from a query response This differs from getResponseByParams in such
  * a way that it does only create the fields of the response but never search snippets and there
  * are also no facets generated.
  *
  * @param params
  * @return
  * @throws IOException
  * @throws SolrException
  */
 @Override
 public SolrDocumentList getDocumentListByParams(ModifiableSolrParams params)
     throws IOException, SolrException {
   SolrQueryRequest req = this.request(params);
   SolrQueryResponse response = null;
   String q = params.get(CommonParams.Q);
   String fq = params.get(CommonParams.FQ);
   String sort = params.get(CommonParams.SORT);
   String threadname = Thread.currentThread().getName();
   try {
     if (q != null)
       Thread.currentThread()
           .setName(
               "solr query: q = "
                   + q
                   + (fq == null ? "" : ", fq = " + fq)
                   + (sort == null ? "" : ", sort = " + sort)); // for debugging in Threaddump
     response = this.query(req);
     if (q != null) Thread.currentThread().setName(threadname);
     if (response == null) throw new IOException("response == null");
     return SolrQueryResponse2SolrDocumentList(req, response);
   } finally {
     req.close();
     SolrRequestInfo.clearRequestInfo();
   }
 }
 /**
  * conversion from a SolrQueryResponse (which is a solr-internal data format) to SolrDocumentList
  * (which is a solrj-format) The conversion is done inside the solrj api using the
  * BinaryResponseWriter and a very complex unfolding process via
  * org.apache.solr.common.util.JavaBinCodec.marshal.
  *
  * @param request
  * @param sqr
  * @return
  */
 public SolrDocumentList SolrQueryResponse2SolrDocumentList(
     final SolrQueryRequest req, final SolrQueryResponse rsp) {
   SolrDocumentList sdl = new SolrDocumentList();
   NamedList<?> nl = rsp.getValues();
   ResultContext resultContext = (ResultContext) nl.get("response");
   DocList response =
       resultContext == null
           ? new DocSlice(0, 0, new int[0], new float[0], 0, 0.0f)
           : resultContext.docs;
   sdl.setNumFound(response == null ? 0 : response.matches());
   sdl.setStart(response == null ? 0 : response.offset());
   String originalName = Thread.currentThread().getName();
   if (response != null) {
     try {
       SolrIndexSearcher searcher = req.getSearcher();
       final int responseCount = response.size();
       DocIterator iterator = response.iterator();
       for (int i = 0; i < responseCount; i++) {
         int docid = iterator.nextDoc();
         Thread.currentThread()
             .setName("EmbeddedSolrConnector.SolrQueryResponse2SolrDocumentList: " + docid);
         Document responsedoc = searcher.doc(docid, (Set<String>) null);
         SolrDocument sordoc = doc2SolrDoc(responsedoc);
         sdl.add(sordoc);
       }
     } catch (IOException e) {
       ConcurrentLog.logException(e);
     }
   }
   Thread.currentThread().setName(originalName);
   return sdl;
 }
Ejemplo n.º 13
0
  /*
   * (non-Javadoc)
   * @see de.tuberlin.dima.minidb.io.ResourceManager#writePageToResource(byte[], de.tuberlin.dima.minidb.io.cache.CacheableData)
   */
  @Override
  public void writePageToResource(byte[] buffer, CacheableData wrapper) throws IOException {
    this.writeRequests.add(wrapper.getPageNumber());

    // check if thread is different than the creator
    if (Thread.currentThread() == this.creator) {
      System.out.println(writingSeparateThread);
      throw new IOException(writingSeparateThread);
    }
    // check if writer thread is already set
    if (this.writer == null) {
      this.writer = Thread.currentThread();
    }
    // check if it is always the same writing thread
    if (this.writer != Thread.currentThread()) {
      System.out.println(writingSameThread);
      throw new IOException(writingSameThread);
    }
    // write contents to specified position
    if (wrapper.getPageNumber() < this.pageNumber && wrapper.getPageNumber() >= firstPageNumber) {
      // copy contents to "disk"
      System.arraycopy(
          buffer, 0, this.diskBuffer.get(wrapper.getPageNumber() - 1), 0, buffer.length);
    } else {
      throw new IOException("This page does not exist.");
    }
  }
Ejemplo n.º 14
0
  public synchronized void unlockResource(final String id) {
    logger.debug("unlockResource: {}", id);

    final Entry entry = this.locker.getEntry(id);
    if (entry == null) {
      return;
    }

    boolean wakeup = false;

    if (entry.readers.remove(Thread.currentThread())) {
      wakeup = true;
    }

    if (entry.writer == Thread.currentThread()) {
      entry.writer = null;
      wakeup = true;
    }

    if (checkRemoveEntry(id, entry)) {
      wakeup = true;
    }

    if (wakeup) {
      notifyAll();
    }
  }
  public SurefireProvider createProvider(boolean isInsideFork) {
    ClassLoader systemClassLoader = java.lang.Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(classLoader);

    StartupConfiguration starterConfiguration = startupConfiguration;

    // Note: Duplicated in ForkedBooter#createProviderInCurrentClassloader
    final Object o =
        surefireReflector.createBooterConfiguration(
            classLoader, reporterManagerFactory, isInsideFork);
    surefireReflector.setTestSuiteDefinitionAware(
        o, providerConfiguration.getTestSuiteDefinition());
    surefireReflector.setProviderPropertiesAware(o, providerConfiguration.getProviderProperties());
    surefireReflector.setReporterConfigurationAware(
        o, providerConfiguration.getReporterConfiguration());
    surefireReflector.setTestClassLoaderAware(o, classLoader);
    surefireReflector.setTestArtifactInfoAware(o, providerConfiguration.getTestArtifact());
    surefireReflector.setRunOrderParameters(o, providerConfiguration.getRunOrderParameters());
    surefireReflector.setIfDirScannerAware(o, providerConfiguration.getDirScannerParams());

    Object provider =
        surefireReflector.instantiateProvider(starterConfiguration.getActualClassName(), o);
    Thread.currentThread().setContextClassLoader(systemClassLoader);

    return new ProviderProxy(provider, classLoader);
  }
Ejemplo n.º 16
0
  private void serviceAdded(HttpService service) {
    try {
      DispatcherServlet dispatcherServlet = new DispatcherServlet();
      dispatcherServlet.setContextConfigLocation(CONTEXT_CONFIG_LOCATION);
      dispatcherServlet.setContextClass(OpenMrsApplicationContext.class);
      ClassLoader old = Thread.currentThread().getContextClassLoader();
      try {
        Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
        service.registerServlet(SERVLET_URL_MAPPING, dispatcherServlet, null, null);
        logger.debug("Servlet registered");
      } finally {
        Thread.currentThread().setContextClassLoader(old);
      }

      // register all annotated handlers
      EventAnnotationBeanPostProcessor.registerHandlers(
          BeanFactoryUtils.beansOfTypeIncludingAncestors(
              dispatcherServlet.getWebApplicationContext(), Object.class));
      // create tree objects in the database
      bootStrap();

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 17
0
 static void say() {
   System.out.println("blah");
   System.out.println(
       Thread.currentThread().getName()
           + ":"
           + Arrays.asList(Thread.currentThread().getStackTrace()));
 }
  public static void main(String[] args)
      throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService executor = Executors.newFixedThreadPool(5);
    CompletableFuture<String> task1 =
        CompletableFuture.supplyAsync(
            () -> {
              try {
                System.out.println(Thread.currentThread().getName() + ": firstTask");
                TimeUnit.SECONDS.sleep(2);
              } catch (Exception e) {
              }
              return "1";
            });
    CompletableFuture<String> task2 =
        CompletableFuture.supplyAsync(
            () -> {
              try {
                System.out.println(Thread.currentThread().getName() + ": secondTask");
                TimeUnit.SECONDS.sleep(3);
              } catch (Exception e) {
              }
              return "2";
            });
    // a new thread from the supplied executor will execute third task
    task1.acceptEitherAsync(
        task2,
        (x) -> {
          System.out.println(Thread.currentThread().getName() + ": thirdTask " + x);
        },
        executor);

    TimeUnit.SECONDS.sleep(5);
    System.out.println(Thread.currentThread().getName() + ": " + task1.get());
    executor.shutdown();
  }
Ejemplo n.º 19
0
    @Override
    public void run() {
      while (true) {
        synchronized (shareData) {
          while (shareData.isEmpty()) {
            try {
              System.out.println(Thread.currentThread().getName() + " 数据为空,等待生产...");
              shareData.wait();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }

          Integer obj = shareData.get(0);
          shareData.remove(obj);
          System.out.println(
              Thread.currentThread().getName() + " 消费数据:" + obj + ", 剩余:" + shareData.size());

          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }

          shareData.notifyAll();
        }
      }
    }
Ejemplo n.º 20
0
 protected void initInputClassLoader() {
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   if (buildOnlyOutdatedFiles && getBinaryOutputDirectory() != null) {
     CompilerClassLoader ccl = getCompilerClassLoader(cl);
     if (ccl == null) {
       try {
         Launcher.LOGGER.debug(
             "setting classloader for " + getBinaryOutputDirectory().toURI().toURL());
         Thread.currentThread()
             .setContextClassLoader(
                 new CompilerClassLoader(
                     new URL[] {getBinaryOutputDirectory().toURI().toURL()},
                     factory.getEnvironment().getInputClassLoader()));
       } catch (Exception e) {
         Launcher.LOGGER.error(e.getMessage(), e);
       }
     }
   } else {
     if (!hasClassLoader(
         Thread.currentThread().getContextClassLoader(),
         factory.getEnvironment().getInputClassLoader())) {
       Thread.currentThread()
           .setContextClassLoader(factory.getEnvironment().getInputClassLoader());
     }
   }
 }
Ejemplo n.º 21
0
 private void checkThread() {
   // All ops must always be invoked on same thread
   if (Thread.currentThread() != th) {
     throw new IllegalStateException(
         "Invoked with wrong thread, actual: " + Thread.currentThread() + " expected: " + th);
   }
 }
  /* (non-Javadoc)
   * @see org.jboss.remoting.ServerInvocationHandler#invoke(org.jboss.remoting.InvocationRequest)
   */
  public Object invoke(InvocationRequest invocation) throws Throwable {
    Serializable key = (Serializable) invocation.getRequestPayload().get(OID);
    Remotable remotable = remotables.get(key);
    if (remotable == null)
      throw new IllegalArgumentException("Can't find remotable " + key + " in " + remotables);

    Object parameters[] = (Object[]) invocation.getParameter();
    SerializableMethod method = (SerializableMethod) parameters[0];
    Object args[] = (Object[]) parameters[1];
    ClassLoader loader = remotable.getClassLoader();
    Method realMethod = method.toMethod(loader);
    ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
    try {
      Thread.currentThread().setContextClassLoader(loader);
      return realMethod.invoke(remotable.getTarget(), args);
    } catch (IllegalArgumentException e) {
      throw new IllegalArgumentException(
          "unable to invoke "
              + realMethod
              + " on "
              + remotable.getTarget()
              + " with "
              + Arrays.toString(args),
          e);
    } catch (InvocationTargetException e) {
      throw e.getCause();
    } finally {
      Thread.currentThread().setContextClassLoader(oldLoader);
    }
  }
 @Override
 public String format(
     String projectName,
     String path,
     String revision,
     String abbrRev,
     ConfigSection cfg,
     InputStream raw)
     throws IOException {
   // Docx4J tries to load some resources dynamically. This fails if the Gerrit
   // core classloader is used since it doesn't see the resources that are
   // contained in the plugin jar. To make the resource loading work we
   // must set a context classloader on the current thread.
   ClassLoader loader = Thread.currentThread().getContextClassLoader();
   try {
     Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
     WordprocessingMLPackage p = Docx4J.load(raw);
     HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
     htmlSettings.setWmlPackage(p);
     Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML", true);
     try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
       Docx4J.toHTML(htmlSettings, out, Docx4J.FLAG_EXPORT_PREFER_XSL);
       String html = out.toString(UTF_8.name());
       return util.applyCss(html, NAME, projectName);
     }
   } catch (Docx4JException e) {
     throw new IOException(e);
   } finally {
     Thread.currentThread().setContextClassLoader(loader);
   }
 }
Ejemplo n.º 24
0
  public void testAddManager() throws Exception {
    cacheName = SAMPLE_CACHE1;
    if (manager1.getStatus() != Status.STATUS_SHUTDOWN) manager1.shutdown();

    Thread.currentThread().sleep(1000);
    manager1 =
        new CacheManager(
            AbstractCacheTest.TEST_CONFIG_DIR
                + "distribution/jgroups/ehcache-distributed-jgroups.xml");
    Thread.currentThread().sleep(3000);
    manager2.clearAll();

    Thread.currentThread().sleep(1000);

    manager2.getEhcache(cacheName).put(new Element(new Integer(2), new Date()));
    manager1.getEhcache(cacheName).put(new Element(new Integer(3), new Date()));
    Thread.currentThread().sleep(2000);

    assertTrue(
        manager1.getEhcache(cacheName).getKeys().size()
                == manager2.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager3.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager4.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size() == 2);
  }
  @Test
  public void testTestingClient() throws Exception {
    final TestingClient testingClient;
    testingClient =
        new TestingClient(
            runner, context, new ClassPathResolver(Thread.currentThread().getContextClassLoader()));

    final String baseDirectory = System.getProperty("user.dir");
    final FileSet tests = new FileSet();

    tests.setDirectory(baseDirectory + "/src/test/resources/org/moyrax/");
    tests.addInclude("**/*.html");

    context.setFiles(
        tests.getDirectory(),
        fileSetManager.getIncludedFiles(tests),
        fileSetManager.getExcludedFiles(tests));

    context.setLookupPackages(new String[] {"classpath:/org/moyrax/javascript/common/**"});

    context.setClassLoader(new ContextClassLoader(Thread.currentThread().getContextClassLoader()));

    Shell.setResolver("lib", new LibraryResolver("/org/moyrax/javascript/lib"));
    Shell.setResolver(
        "classpath", new ClassPathResolver(Thread.currentThread().getContextClassLoader()));

    loadContextResources(testingClient);

    testingClient.runTests();
  }
Ejemplo n.º 26
0
  public void testBasicReplication() throws Exception {

    for (int i = 0; i < NBR_ELEMENTS; i++) {
      manager1.getEhcache(cacheName).put(new Element(new Integer(i), "testdat"));
      // Thread.currentThread().sleep(2);
    }
    Thread.currentThread().sleep(3000);

    LOG.debug(
        manager1.getEhcache(cacheName).getKeys().size()
            + "  "
            + manager2.getEhcache(cacheName).getKeys().size()
            + " "
            + manager3.getEhcache(cacheName).getKeys().size());
    assertTrue(
        manager1.getEhcache(cacheName).getKeys().size()
                == manager2.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager3.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager4.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size() == NBR_ELEMENTS);

    manager1.getEhcache(cacheName).removeAll();
    Thread.currentThread().sleep(1000);
    assertTrue(
        manager1.getEhcache(cacheName).getKeys().size()
                == manager2.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager3.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size()
                == manager4.getEhcache(cacheName).getKeys().size()
            && manager1.getEhcache(cacheName).getKeys().size() == 0);
  }
Ejemplo n.º 27
0
 /**
  * Enable sharing of the class-loader with 3rd party (e.g. digester).
  *
  * @return the class-loader user be the helper.
  */
 public ClassLoader getClassLoader() {
   log.debug(
       "Class classloader: {} Thread classloader: {}",
       this.getClass().getClassLoader(),
       Thread.currentThread().getContextClassLoader());
   return Thread.currentThread().getContextClassLoader();
 }
Ejemplo n.º 28
0
  /**
   * Process a single row (this is repeated for all rows on input). On the first row, we do the
   * following:
   *
   * <ul>
   *   <li>Setup a class loader that contains the Transformer jar file
   *   <li>Use this class loader to create a new instance of the transformer
   *   <li>The transformer will be reused for all subsequent rows
   *   <li>Open the zos file
   *   <li>Process the first row (classloader will find custom code if needed)
   *   <li>Restore the context class loader to avoid interference with PDI
   * </ul>
   *
   * Here we also keep track of how many bytes from the file record were actually consumed by the
   * transformers. This allows the leftover to be processed on the next call to this method.
   *
   * @param smi Step meta
   * @param sdi Step data
   * @throws KettleException if something goes wrong
   */
  public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (ZosFileInputMeta) smi;
    data = (ZosFileInputData) sdi;

    if (first) {
      first = false;

      data.outputRowMeta = new RowMeta();
      meta.getFields(data.outputRowMeta, getStepname(), null, null, this);

      ClassLoader tccl = Thread.currentThread().getContextClassLoader();
      try {
        Cob2Pdi.setTransformerClassLoader(
            getClass(), Cob2Pdi.getJarFileName(data.compositeJaxbClassName));
        data.cobolBinding =
            Cob2Pdi.newCobolBinding(Cob2Pdi.getJaxbClassName(data.compositeJaxbClassName));
        data.fis = ZosFileInputStreamFactory.create(meta, new File(data.filename));
        data.hostRecord = Cob2Pdi.newHostRecord(data.cobolBinding);
        data.hostCharset = meta.getHostCharset();
        data.status = new HostTransformStatus();
        logBasic(BaseMessages.getString(PKG, "ZosFileInput.FileOpened.Message", data.filename));

        return processRow();

      } catch (FileNotFoundException e) {
        throw new KettleException(e);
      } finally {
        Thread.currentThread().setContextClassLoader(tccl);
      }

    } else {
      return processRow();
    }
  }
Ejemplo n.º 29
0
  /** run do the work. */
  public void run() {
    int percent = 0;
    String msg = "";
    System.out.println(
        "SimpleWorker.run : Thread " + Thread.currentThread().getName() + " started");

    eventQueue = Toolkit.getDefaultToolkit().getSystemEventQueue();

    //        while (running) {
    //            count++;
    //            if (count >= MAXWORK) {
    //                running = false;
    //            }
    //
    //            msg = "Message from " + Thread.currentThread().getName()
    //                    + " : " + count;
    //
    //            eventQueue.postEvent(new EventSearchWorker(target, msg, count));
    //
    //            try {
    //                this.sleep(800);
    //            } catch (Exception e) {
    //                System.out.println("E:run : " + e.toString());
    //            }
    //        }
    //        eventQueue.postEvent(new EventSearchWorker(target, "deneme\n", count));
    search(searchEngine);
    target.dispatchEvent(
        new EventSearchWorker(target, "", count, this.searchEngine.getName() + " completed.."));

    //        eventQueue.postEvent(new EventSearchWorker(target, "Work done..", count));
    System.out.println("SimpleWorker.run : Thread " + Thread.currentThread().getName() + " stoped");
  } // run
Ejemplo n.º 30
0
  /**
   * Verifies that a client timeout will be detected by a Nailgun NGInputStream reading from a
   * blocking heartbeat stream.
   */
  @Test(expected = InterruptedException.class)
  public void whenClientTimeoutDetectedThenMainThreadIsInterrupted()
      throws InterruptedException, IOException {
    final long timeoutMillis = 100;
    final long intervalMillis = timeoutMillis * 2; // Interval > timeout to trigger disconnection.
    final ProjectWorkspace workspace =
        TestDataHelper.createProjectWorkspaceForScenario(this, "exclusive_execution", tmp);
    workspace.setUp();

    // Build an NGContext connected to an NGInputStream reading from a stream that will timeout.
    Thread.currentThread().setName("Test");
    try (TestContext context =
        new TestContext(
            ImmutableMap.copyOf(System.getenv()),
            TestContext.createHeartBeatStream(intervalMillis),
            timeoutMillis)) {
      final Thread commandThread = Thread.currentThread();
      context.addClientListener(
          new NGClientListener() {
            @Override
            public void clientDisconnected() throws InterruptedException {
              commandThread.interrupt();
            }
          });
      Thread.sleep(1000);
      fail("Should have been interrupted.");
    }
  }