private static int getThreadNum() {
   Matcher matcher =
       Pattern.compile("JobScheduler FJ pool (\\d*)/(\\d*)")
           .matcher(Thread.currentThread().getName());
   String num = matcher.matches() ? matcher.group(1) : null;
   return StringUtil.parseInt(num, 0);
 }
Example #2
0
    protected void await(boolean throwInterrupt) throws InterruptedException {
      if (!signaled.get()) {
        lock.acquired = false;
        sendAwaitConditionRequest(lock.name, lock.owner);
        boolean interrupted = false;
        while (!signaled.get()) {
          parker.set(Thread.currentThread());
          LockSupport.park(this);

          if (Thread.interrupted()) {
            // If we were interrupted and haven't received a response yet then we try to
            // clean up the lock request and throw the exception
            if (!signaled.get()) {
              sendDeleteAwaitConditionRequest(lock.name, lock.owner);
              throw new InterruptedException();
            }
            // In the case that we were signaled and interrupted
            // we want to return the signal but still interrupt
            // our thread
            interrupted = true;
          }
        }
        if (interrupted) Thread.currentThread().interrupt();
      }

      // We set as if this signal was no released.  This way if the
      // condition is reused again, but the client condition isn't lost
      // we won't think we were signaled immediately
      signaled.set(false);
    }
 public JilterStatus eom(JilterEOMActions eomActions, Properties properties) {
   logger.debug("jilter eom()");
   try {
     bos.close(); // close stream
   } catch (IOException io) {
     logger.error("jilter failed to close io stream during eom", io);
   }
   byte[] messageBytes = bos.toByteArray();
   bos = new ByteArrayOutputStream();
   ByteArrayInputStream bis = new ByteArrayInputStream(messageBytes);
   try {
     logger.debug("jilter store callback execute");
     Config.getStopBlockFactory()
         .detectBlock("milter server", Thread.currentThread(), this, IDLE_TIMEOUT);
     callback.store(bis, host);
     logger.debug("jilter store callback finished");
   } catch (ArchiveException e) {
     logger.error("failed to store the message via milter", e);
     if (e.getRecoveryDirective() == ArchiveException.RecoveryDirective.REJECT) {
       logger.debug("jilter reject");
       return JilterStatus.SMFIS_REJECT;
     } else if (e.getRecoveryDirective() == ArchiveException.RecoveryDirective.RETRYLATER) {
       logger.debug("jilter temp fail");
       return JilterStatus.SMFIS_TEMPFAIL;
     }
   } catch (Throwable oome) {
     logger.error("failed to store message:" + oome.getMessage(), oome);
     return JilterStatus.SMFIS_REJECT;
   } finally {
     Config.getStopBlockFactory().endDetectBlock(Thread.currentThread());
   }
   return JilterStatus.SMFIS_CONTINUE;
 }
  protected ClassLoader createTempLoader(
      Collection col, boolean shouldOverrideLoadClassForCollectionMembers) {
    if (!shouldCreateInternalLoader) {
      return Thread.currentThread().getContextClassLoader();
    }

    ClassLoader currentLoader = Thread.currentThread().getContextClassLoader();
    if (!(currentLoader instanceof URLClassLoader)) {
      // we can't create a TempEntityLoader so just use the current one
      // shouldn't be a problem (and should only occur) in JavaSE
      return currentLoader;
    }
    URL[] urlPath = ((URLClassLoader) currentLoader).getURLs();
    ClassLoader tempLoader =
        new TempEntityLoader(
            urlPath, currentLoader, col, shouldOverrideLoadClassForCollectionMembers);

    AbstractSessionLog.getLog().log(SessionLog.FINER, "cmp_init_tempLoader_created", tempLoader);
    AbstractSessionLog.getLog()
        .log(
            SessionLog.FINER,
            "cmp_init_shouldOverrideLoadClassForCollectionMembers",
            new Boolean(shouldOverrideLoadClassForCollectionMembers));

    return tempLoader;
  }
 public void lock() {
   Thread caller = Thread.currentThread();
   synchronized (this) {
     if (owner_ == null) {
       owner_ = caller;
       holds_ = 1;
       return;
     } else if (caller == owner_) {
       incHolds();
       return;
     } else {
       boolean wasInterrupted = Thread.interrupted();
       try {
         while (true) {
           try {
             wait();
           } catch (InterruptedException e) {
             wasInterrupted = true;
             // no need to notify; if we were signalled, we
             // will act as signalled, ignoring the
             // interruption
           }
           if (owner_ == null) {
             owner_ = caller;
             holds_ = 1;
             return;
           }
         }
       } finally {
         if (wasInterrupted) Thread.currentThread().interrupt();
       }
     }
   }
 }
 public void funTime() {
   try {
     defaultPriority = Thread.currentThread().getPriority();
     Thread.currentThread().setPriority(Thread.currentThread().getPriority() + 1);
     Thread.sleep((int) Math.random() * 11000 + 1);
     Thread.currentThread().setPriority(defaultPriority);
   } catch (InterruptedException e) {
   }
 }
Example #7
0
 private void handleRequest() throws IOException {
   String line = in.readLine();
   if (line == null || line.length() == 0) {
     Log.warn(Thread.currentThread().getName() + ": ignoring empty request.");
     return;
   }
   if (handleCommand(line, out) == false) {
     out.println(
         Thread.currentThread().getName() + ": didn't understand request \"" + line + "\".");
   }
 }
Example #8
0
  /** invokes the given Runnable */
  public void invoke(boolean wait, Runnable r) {
    if (r == null) {
      return;
    }

    if (NativeWindowFactory.isAWTAvailable()) {
      initAWTReflection();

      // handover to AWT MainThread ..
      try {
        if (((Boolean) ReflectionUtil.callMethod(null, mAWTIsDispatchThread, null))
            .booleanValue()) {
          r.run();
          return;
        }
        if (wait) {
          ReflectionUtil.callMethod(null, mAWTInvokeAndWait, new Object[] {r});
        } else {
          ReflectionUtil.callMethod(null, mAWTInvokeLater, new Object[] {r});
        }
      } catch (Exception e) {
        throw new NativeWindowException(e);
      }
      return;
    }

    // if this main thread is not being used or
    // if this is already the main thread .. just execute.
    if (!isRunning() || mainThread == Thread.currentThread()) {
      r.run();
      return;
    }

    boolean doWait = wait && isRunning() && mainThread != Thread.currentThread();
    Object lock = new Object();
    RunnableTask rTask = new RunnableTask(r, doWait ? lock : null, true);
    Throwable throwable = null;
    synchronized (lock) {
      invokeLater(rTask);
      if (doWait) {
        try {
          lock.wait();
        } catch (InterruptedException ie) {
          throwable = ie;
        }
      }
    }
    if (null == throwable) {
      throwable = rTask.getThrowable();
    }
    if (null != throwable) {
      throw new RuntimeException(throwable);
    }
  }
Example #9
0
 public void stop() {
   if (DEBUG)
     System.err.println("MainThread.stop(): " + Thread.currentThread().getName() + " start");
   synchronized (taskWorkerLock) {
     if (isRunning) {
       shouldStop = true;
     }
     taskWorkerLock.notifyAll();
   }
   if (DEBUG)
     System.err.println("MainThread.stop(): " + Thread.currentThread().getName() + " end");
 }
Example #10
0
    public void receive(Message msg) {
      if (!msg.isFlagSet(Message.OOB)) {
        try {
          System.out.println(Thread.currentThread() + ": waiting on latch");
          latch.await(25000, TimeUnit.MILLISECONDS);
          System.out.println(Thread.currentThread() + ": DONE waiting on latch");
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }

      msgs.add((Integer) msg.getObject());
    }
Example #11
0
 static void registerJars(List<String> newJars) throws IllegalArgumentException {
   LogHelper console = getConsole();
   try {
     ClassLoader loader = Thread.currentThread().getContextClassLoader();
     ClassLoader newLoader = Utilities.addToClassPath(loader, newJars.toArray(new String[0]));
     Thread.currentThread().setContextClassLoader(newLoader);
     SessionState.get().getConf().setClassLoader(newLoader);
     console.printInfo("Added " + newJars + " to class path");
   } catch (Exception e) {
     String message = "Unable to register " + newJars;
     throw new IllegalArgumentException(message, e);
   }
 }
 protected synchronized boolean startWrite() {
   if (activeWriter_ == Thread.currentThread()) { // already held; re-acquire
     ++writeHolds_;
     return true;
   } else if (writeHolds_ == 0) {
     if (activeReaders_ == 0
         || (readers_.size() == 1 && readers_.get(Thread.currentThread()) != null)) {
       activeWriter_ = Thread.currentThread();
       writeHolds_ = 1;
       return true;
     } else return false;
   } else return false;
 }
  public boolean closeProject(
      @NotNull final Project project,
      final boolean save,
      final boolean dispose,
      boolean checkCanClose) {
    if (isLight(project)) {
      throw new AssertionError("must not close light project");
    }
    if (!isProjectOpened(project)) return true;
    if (checkCanClose && !canClose(project)) return false;
    final ShutDownTracker shutDownTracker = ShutDownTracker.getInstance();
    shutDownTracker.registerStopperThread(Thread.currentThread());
    try {
      if (save) {
        FileDocumentManager.getInstance().saveAllDocuments();
        project.save();
      }

      if (checkCanClose && !ensureCouldCloseIfUnableToSave(project)) {
        return false;
      }

      fireProjectClosing(project); // somebody can start progress here, do not wrap in write action

      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  synchronized (myOpenProjects) {
                    myOpenProjects.remove(project);
                    cacheOpenProjects();
                    myTestProjects.remove(project);
                  }

                  myChangedProjectFiles.remove(project);

                  fireProjectClosed(project);

                  if (dispose) {
                    Disposer.dispose(project);
                  }
                }
              });
    } finally {
      shutDownTracker.unregisterStopperThread(Thread.currentThread());
    }

    return true;
  }
 private SortedBugCollection readXml(final InputStream file)
     throws IOException, DocumentException {
   SaxSetup sax = new SaxSetup();
   ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
   try {
     Thread.currentThread().setContextClassLoader(FindBugsParser.class.getClassLoader());
     SortedBugCollection collection = new SortedBugCollection();
     collection.readXML(file);
     return collection;
   } finally {
     Thread.currentThread().setContextClassLoader(contextClassLoader);
     sax.cleanup();
   }
 }
 public DesignCIManifestRfcTouple call() {
   String oldThreadName = Thread.currentThread().getName();
   try {
     Thread.currentThread().setName(getProcessingThreadName(oldThreadName, env.getCiId()));
     ManifestRfcContainer manifestPlatformRfcs =
         manifestRfcProcessor.processPlatform(
             platRelation.getToCi(), env, nsPath, userId, availMode);
     DesignCIManifestRfcTouple touple =
         new DesignCIManifestRfcTouple(platRelation.getToCi().getCiId(), manifestPlatformRfcs);
     return touple;
   } finally {
     countDownLatch.countDown();
     Thread.currentThread().setName(oldThreadName);
   }
 }
  /** {@inheritDoc} */
  @Override
  public void loadCache(GridBiInClosure<K, V> c, @Nullable Object... args) throws GridException {
    ExecutorService exec =
        new ThreadPoolExecutor(
            threadsCnt,
            threadsCnt,
            0L,
            MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(batchQueueSize),
            new BlockingRejectedExecutionHandler());

    Iterator<I> iter = inputIterator(args);

    Collection<I> buf = new ArrayList<>(batchSize);

    try {
      while (iter.hasNext()) {
        if (Thread.currentThread().isInterrupted()) {
          U.warn(log, "Working thread was interrupted while loading data.");

          break;
        }

        buf.add(iter.next());

        if (buf.size() == batchSize) {
          exec.submit(new Worker(c, buf, args));

          buf = new ArrayList<>(batchSize);
        }
      }

      if (!buf.isEmpty()) exec.submit(new Worker(c, buf, args));
    } catch (RejectedExecutionException ignored) {
      // Because of custom RejectedExecutionHandler.
      assert false : "RejectedExecutionException was thrown while it shouldn't.";
    } finally {
      exec.shutdown();

      try {
        exec.awaitTermination(Long.MAX_VALUE, MILLISECONDS);
      } catch (InterruptedException ignored) {
        U.warn(log, "Working thread was interrupted while waiting for put operations to complete.");

        Thread.currentThread().interrupt();
      }
    }
  }
Example #17
0
  /** Your new java application main entry, which pipelines your application */
  public static void main(String[] args) {
    useMainThread = MAIN_THREAD_CRITERIA;

    if (DEBUG)
      System.err.println(
          "MainThread.main(): "
              + Thread.currentThread().getName()
              + " useMainThread "
              + useMainThread);

    if (args.length == 0) {
      return;
    }

    String mainClassName = args[0];
    String[] mainClassArgs = new String[args.length - 1];
    if (args.length > 1) {
      System.arraycopy(args, 1, mainClassArgs, 0, args.length - 1);
    }

    NEWTJNILibLoader.loadNEWT();

    mainAction = new MainAction(mainClassName, mainClassArgs);

    if (NativeWindowFactory.TYPE_MACOSX.equals(NativeWindowFactory.getNativeWindowType(false))) {
      ReflectionUtil.callStaticMethod(
          "com.jogamp.newt.impl.macosx.MacDisplay",
          "initSingleton",
          null,
          null,
          MainThread.class.getClassLoader());
    }

    if (useMainThread) {
      shouldStop = false;
      tasks = new ArrayList();
      mainThread = Thread.currentThread();

      // dispatch user's main thread ..
      mainAction.start();

      // do our main thread task scheduling
      singletonMainThread.run();
    } else {
      // run user's main in this thread
      mainAction.run();
    }
  }
  /** JNDI object factory so the proxy can be used as a resource. */
  public Object getObjectInstance(
      Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
    Reference ref = (Reference) obj;

    String api = null;
    String url = null;
    String user = null;
    String password = null;

    for (int i = 0; i < ref.size(); i++) {
      RefAddr addr = ref.get(i);

      String type = addr.getType();
      String value = (String) addr.getContent();

      if (type.equals("type")) api = value;
      else if (type.equals("url")) url = value;
      else if (type.equals("user")) setUser(value);
      else if (type.equals("password")) setPassword(value);
    }

    if (url == null) throw new NamingException("`url' must be configured for HessianProxyFactory.");
    // XXX: could use meta protocol to grab this
    if (api == null)
      throw new NamingException("`type' must be configured for HessianProxyFactory.");

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    Class apiClass = Class.forName(api, false, loader);

    return create(apiClass, url);
  }
Example #19
0
 public ConnectionContext(Exception excp, String ip, String uri, Map<String, String[]> params) {
   this.exception = excp;
   this.params = params;
   this.thread = Thread.currentThread().getName();
   this.uri = uri;
   this.ip = ip;
 }
Example #20
0
 public void run() {
   if (Thread.currentThread() != this.mt)
     throw (new RuntimeException("MainFrame is being run from an invalid context"));
   Thread ui = new HackThread(p, "Haven UI thread");
   ui.start();
   try {
     try {
       Session sess = null;
       while (true) {
         UI.Runner fun;
         if (sess == null) {
           Bootstrap bill = new Bootstrap(Config.defserv, Config.mainport);
           if ((Config.authuser != null) && (Config.authck != null)) {
             bill.setinitcookie(Config.authuser, Config.authck);
             Config.authck = null;
           }
           fun = bill;
           setTitle(String.format("Amish Paradise %s", version));
         } else {
           fun = new RemoteUI(sess);
           setTitle(String.format("Amish Paradise %s \u2013 %s", version, sess.username));
         }
         sess = fun.run(p.newui(sess));
       }
     } catch (InterruptedException e) {
     }
     savewndstate();
   } finally {
     ui.interrupt();
     dispose();
   }
 }
  public void testMultiThreadAddsAndRemoves() {
    int size = TOTAL_THREADS + REMOVE_THREADS;
    ArrayList threadList = new ArrayList(size);
    for (int i = MIN_TRANS; i <= MAX_TRANS; i++) {
      int index = i - MIN_TRANS;
      threadList.add(new TransformerThread("Trans" + prettyNum(index, 2), i));
    }

    int factor = (int) Math.floor(TOTAL_THREADS / REMOVE_THREADS);
    for (int i = 0; i < REMOVE_THREADS; i++) {
      threadList.add(factor * i, new RemoveThread("Remove" + i));
    }

    Thread[] threads = (Thread[]) threadList.toArray(new Thread[size]);
    setExecThread(new ExecuteTransformersThread());
    getExecThread().start();
    for (int i = threads.length - 1; i >= 0; i--) {
      threads[i].start();
    }

    while (!testCompleted()) {
      Thread.currentThread().yield();
    }
    assertTrue(finalCheck());

    // printTransformers();
  }
 public RunnableScheduledFuture<?> take() throws InterruptedException {
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       RunnableScheduledFuture<?> first = queue[0];
       if (first == null) available.await();
       else {
         long delay = first.getDelay(NANOSECONDS);
         if (delay <= 0) return finishPoll(first);
         else if (leader != null) available.await();
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             available.awaitNanos(delay);
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && queue[0] != null) available.signal();
     lock.unlock();
   }
 }
 public RunnableScheduledFuture<?> poll(long timeout, TimeUnit unit)
     throws InterruptedException {
   long nanos = unit.toNanos(timeout);
   final ReentrantLock lock = this.lock;
   lock.lockInterruptibly();
   try {
     for (; ; ) {
       RunnableScheduledFuture<?> first = queue[0];
       if (first == null) {
         if (nanos <= 0) return null;
         else nanos = available.awaitNanos(nanos);
       } else {
         long delay = first.getDelay(NANOSECONDS);
         if (delay <= 0) return finishPoll(first);
         if (nanos <= 0) return null;
         if (nanos < delay || leader != null) nanos = available.awaitNanos(nanos);
         else {
           Thread thisThread = Thread.currentThread();
           leader = thisThread;
           try {
             long timeLeft = available.awaitNanos(delay);
             nanos -= delay - timeLeft;
           } finally {
             if (leader == thisThread) leader = null;
           }
         }
       }
     }
   } finally {
     if (leader == null && queue[0] != null) available.signal();
     lock.unlock();
   }
 }
Example #24
0
 public boolean isCurrentThreadEDT() {
   if (NativeWindowFactory.isAWTAvailable()) {
     initAWTReflection();
     return ((Boolean) ReflectionUtil.callMethod(null, mAWTIsDispatchThread, null)).booleanValue();
   }
   return isRunning() && mainThread == Thread.currentThread();
 }
  /**
   * Returns the clone of <code>o_</code>. It calls <code>o_.clone()</code>, if possible, and either
   * raises an exception or returns null if fails.
   *
   * @param raiseException_ set to true if one wishes to get exception instead of receiving null
   *     when this method fails to call <code>o_.clone()</code>.
   */
  public static Object clone(Object o_, boolean raiseException_) {
    if (o_ == null) return null;
    if (o_ instanceof String) return o_;

    try {
      if (o_ instanceof drcl.ObjectCloneable) return ((drcl.ObjectCloneable) o_).clone();
      if (o_.getClass().isArray()) {
        int length_ = Array.getLength(o_);
        Class componentType_ = o_.getClass().getComponentType();
        Object that_ = Array.newInstance(componentType_, length_);
        if (componentType_.isPrimitive()) System.arraycopy(o_, 0, that_, 0, length_);
        else {
          for (int i = 0; i < length_; i++)
            Array.set(that_, i, clone(Array.get(o_, i), raiseException_));
        }
        return that_;
      }
      Method m_ = o_.getClass().getMethod("clone", null);
      return m_.invoke(o_, null);
    } catch (Exception e_) {
      if (raiseException_) {
        Thread t_ = Thread.currentThread();
        t_.getThreadGroup().uncaughtException(t_, e_);
      }
      return null;
    }
  }
Example #26
0
 /**
  * @return if <0, then this pipe should be stopped. If ==0, it should not wait. If >0, if it
  *     should wait
  */
 int execute() {
   if (!lock.tryAcquire()) return 1; // currently being accessed
   Thread myThread = Thread.currentThread();
   int threadIndex = -1;
   for (int i = 0; i < threads.length; i++) {
     if (threads[i] == null) {
       threads[i] = myThread;
       threadIndex = i;
       break;
     }
     if (myThread != threads[i]) continue;
     threadIndex = i;
     break;
   }
   Signal signal;
   if (threadIndex < 0) {
     signal = dummySignal;
   } else {
     SignalImpl s = signals[threadIndex];
     s.threadIndex = threadIndex;
     s.signaled = false;
     signal = s;
   }
   boolean hasData;
   try {
     hasData = poll(signal, null);
   } finally {
     signal.signal();
     if (threadIndex < 0) lock.release();
   }
   return 0;
 }
Example #27
0
  /**
   * 扫描包
   *
   * @param basePackage 基础包
   * @param recursive 是否递归搜索子包
   */
  public Set<Class<?>> getPackageAllClasses(String basePackage, boolean recursive) {
    Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
    String packageName = basePackage;
    if (packageName.endsWith(".")) {
      packageName = packageName.substring(0, packageName.lastIndexOf('.'));
    }
    String package2Path = packageName.replace('.', '/');

    Enumeration<URL> dirs;
    try {
      dirs = Thread.currentThread().getContextClassLoader().getResources(package2Path);
      while (dirs.hasMoreElements()) {
        URL url = dirs.nextElement();
        String protocol = url.getProtocol();
        if ("file".equals(protocol)) {
          logger.info("扫描file类型的class文件....");
          String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
          doScanPackageClassesByFile(classes, packageName, filePath, recursive);
        } else if ("jar".equals(protocol)) {
          logger.info("扫描jar文件中的类....");
          doScanPackageClassesByJar(packageName, url, recursive, classes);
        }
      }
    } catch (IOException e) {
      logger.error("IOException error:", e);
    }

    return classes;
  }
Example #28
0
  private final String readMSG(final int len)
      throws IOException, InterruptedException, MessagingNetworkException {
    if (len > 65000)
      ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes");
    byte[] b = new byte[len];
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;

      while (ofs < len) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int read = is.read(b, ofs, len - ofs);
        if (read < 0) read = 0;
        ofs += read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }

      String msg = new String(b, 0, len, "UTF-8");
      return msg;
    }
  }
Example #29
0
  public static LinkedHashSet<String> findJars(LogicalPlan dag, Class<?>[] defaultClasses) {
    List<Class<?>> jarClasses = new ArrayList<Class<?>>();

    for (String className : dag.getClassNames()) {
      try {
        Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        jarClasses.add(clazz);
      } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException("Failed to load class " + className, e);
      }
    }

    for (Class<?> clazz : Lists.newArrayList(jarClasses)) {
      // process class and super classes (super does not require deploy annotation)
      for (Class<?> c = clazz; c != Object.class && c != null; c = c.getSuperclass()) {
        // LOG.debug("checking " + c);
        jarClasses.add(c);
        jarClasses.addAll(Arrays.asList(c.getInterfaces()));
      }
    }

    jarClasses.addAll(Arrays.asList(defaultClasses));

    if (dag.isDebug()) {
      LOG.debug("Deploy dependencies: {}", jarClasses);
    }

    LinkedHashSet<String> localJarFiles = new LinkedHashSet<String>(); // avoid duplicates
    HashMap<String, String> sourceToJar = new HashMap<String, String>();

    for (Class<?> jarClass : jarClasses) {
      if (jarClass.getProtectionDomain().getCodeSource() == null) {
        // system class
        continue;
      }
      String sourceLocation =
          jarClass.getProtectionDomain().getCodeSource().getLocation().toString();
      String jar = sourceToJar.get(sourceLocation);
      if (jar == null) {
        // don't create jar file from folders multiple times
        jar = JarFinder.getJar(jarClass);
        sourceToJar.put(sourceLocation, jar);
        LOG.debug("added sourceLocation {} as {}", sourceLocation, jar);
      }
      if (jar == null) {
        throw new AssertionError("Cannot resolve jar file for " + jarClass);
      }
      localJarFiles.add(jar);
    }

    String libJarsPath = dag.getValue(LogicalPlan.LIBRARY_JARS);
    if (!StringUtils.isEmpty(libJarsPath)) {
      String[] libJars = StringUtils.splitByWholeSeparator(libJarsPath, LIB_JARS_SEP);
      localJarFiles.addAll(Arrays.asList(libJars));
    }

    LOG.info("Local jar file dependencies: " + localJarFiles);

    return localJarFiles;
  }
  public void testGetAttributesForThisTestClass() throws IOException {
    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
      System.out.println("WARNING: Unsupported OS, skipping test");
      return;
    }

    URL resource =
        Thread.currentThread()
            .getContextClassLoader()
            .getResource(getClass().getName().replace('.', '/') + ".class");

    if (resource == null) {
      throw new IllegalStateException(
          "SOMETHING IS VERY WRONG. CANNOT FIND THIS TEST CLASS IN THE CLASSLOADER.");
    }

    File f = new File(resource.getPath().replaceAll("%20", " "));

    Map attrs =
        PlexusIoResourceAttributeUtils.getFileAttributesByPath(
            f, new ConsoleLogger(Logger.LEVEL_INFO, "test"), Logger.LEVEL_DEBUG);

    PlexusIoResourceAttributes fileAttrs =
        (PlexusIoResourceAttributes) attrs.get(f.getAbsolutePath());

    System.out.println("Got attributes for: " + f.getAbsolutePath() + fileAttrs);

    assertNotNull(fileAttrs);
    assertTrue(fileAttrs.isOwnerReadable());
    assertEquals(System.getProperty("user.name"), fileAttrs.getUserName());
  }