java.util.jar.JarFile Scala Examples

The following examples show how to use java.util.jar.JarFile. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: HealthCheckProvider.scala    From wookiee   with Apache License 2.0 5 votes vote down vote up
package com.webtrends.harness.health

import java.util.jar.Attributes.Name
import java.util.jar.{Attributes, JarFile}

import akka.actor.Actor
import akka.pattern._
import akka.util.Timeout
import com.webtrends.harness.HarnessConstants
import com.webtrends.harness.logging.ActorLoggingAdapter
import com.webtrends.harness.service.messages.CheckHealth
import com.webtrends.harness.utils.ConfigUtil
import org.joda.time.DateTime

import scala.collection.mutable
import scala.concurrent.duration._
import scala.concurrent.{Future, Promise}
import scala.util.{Failure, Success}

trait HealthCheckProvider {
  this: Actor with ActorLoggingAdapter =>
  val upTime = DateTime.now
  implicit val timeout =
    ConfigUtil.getDefaultTimeout(context.system.settings.config, HarnessConstants.KeyDefaultTimeout, Timeout(15 seconds))

  val scalaVersion = util.Properties.versionString
  val file = getClass.getProtectionDomain.getCodeSource.getLocation.getFile

  val manifest = file match {
    case _ if file.endsWith(".jar") =>
      new JarFile(file).getManifest
    case _ =>
      val man = new java.util.jar.Manifest()
      man.getMainAttributes.put(Name.IMPLEMENTATION_TITLE, "Webtrends Harness Service")
      man.getMainAttributes.put(Name.IMPLEMENTATION_VERSION, "develop-SNAPSHOT")
      man.getMainAttributes.put(new Attributes.Name("Implementation-Build"), "N/A")
      man
  }

  val application = manifest.getMainAttributes.getValue(Name.IMPLEMENTATION_TITLE)
  val version = manifest.getMainAttributes.getValue(Name.IMPLEMENTATION_VERSION)
  val alerts: mutable.Buffer[ComponentHealth] = mutable.Buffer()

  
  def runChecks: Future[ApplicationHealth] = {

    import context.dispatcher

    // Ask for the health of each component
    val future = (context.actorSelection(HarnessConstants.ActorPrefix) ? CheckHealth).mapTo[Seq[HealthComponent]]
    val p = Promise[ApplicationHealth]

    future.onComplete({
      case Success(checks) =>
        // Rollup alerts for any critical or degraded components
        checks.foreach(checkComponents)
        // Rollup the statuses
        val overallHealth = rollupStatuses(alerts)
        alerts.clear()
        p success ApplicationHealth(application, version, upTime, overallHealth.state, overallHealth.details, checks)
      case Failure(e) =>
        log.error("An error occurred while fetching the health request results", e)
        p success ApplicationHealth(application, version, upTime, ComponentState.CRITICAL, e.getMessage, Nil)
    })

    p.future
  }
} 
Example 2
Source File: ClassScanner.scala    From airframe   with Apache License 2.0 5 votes vote down vote up
package wvlet.airframe.http.codegen
import java.io.File
import java.net.{URL, URLClassLoader}
import java.util.jar.JarFile

import wvlet.log.LogSupport


object ClassScanner extends LogSupport {

  def scanClasses(cl: ClassLoader, targetPackageNames: Seq[String]): Seq[String] = {
    def loop(c: ClassLoader): Seq[URL] = {
      c match {
        case null =>
          Seq.empty
        case u: URLClassLoader =>
          u.getURLs.toSeq ++ loop(u.getParent)
        case _ =>
          loop(c.getParent)
      }
    }

    val urls = loop(cl)
    val b    = Seq.newBuilder[String]

    def findClasses(url: URL): Seq[String] = {
      url match {
        case dir if dir.getProtocol == "file" && { val d = new File(dir.getPath); d.exists() && d.isDirectory } =>
          scanClassesInDirectory(dir.getPath, targetPackageNames)
        case jarFile if jarFile.getProtocol == "file" && jarFile.getPath.endsWith(".jar") =>
          scanClassesInJar(jarFile.getPath, targetPackageNames)
        case _ =>
          Seq.empty
      }
    }

    urls.foreach(x => b ++= findClasses(x))

    b.result().filterNot { x => x.contains("$anon$") }.distinct
  }

  private def toFilePath(packageName: String): String = {
    packageName.replaceAll("\\.", "/") + "/"
  }

  private def scanClassesInDirectory(dir: String, targetPackageNames: Seq[String]): Seq[String] = {
    val classes = Seq.newBuilder[String]

    def loop(baseDir: File, f: File): Unit = {
      f match {
        case d: File if f.isDirectory =>
          val files = d.listFiles()
          if (files != null) {
            files.foreach(loop(baseDir, _))
          }
        case f: File if f.getPath.endsWith(".class") =>
          val className = f.getPath
            .stripSuffix(".class").replaceAllLiterally(baseDir.getPath, "").replaceFirst("\\/", "")
            .replaceAll("\\/", ".")

          classes += className
        case _ =>
      }
    }

    val baseDir = new File(dir)
    if (baseDir.exists() && baseDir.isDirectory) {
      val dirs = targetPackageNames.map(toFilePath).map { path => new File(baseDir, path) }
      dirs.foreach(x => loop(baseDir, x))
    }

    classes.result()
  }

  private def scanClassesInJar(jarFile: String, targetPackageNames: Seq[String]): Seq[String] = {
    val jf: JarFile = new JarFile(jarFile)
    val entryEnum   = jf.entries

    val targetPaths = targetPackageNames.map(toFilePath)

    val classes = Seq.newBuilder[String]

    while (entryEnum.hasMoreElements) {
      val jarEntry  = entryEnum.nextElement
      val entryName = jarEntry.getName
      if (entryName.endsWith(".class") && targetPaths.exists(p => entryName.startsWith(p))) {
        val clsName = entryName
          .stripSuffix(".class")
          .replaceAll("\\/", ".")
        classes += clsName
      }
    }

    classes.result()
  }
} 
Example 3
Source File: MergeRule.scala    From coursier   with Apache License 2.0 5 votes vote down vote up
package coursier.launcher

import java.util.jar.JarFile
import java.util.regex.Pattern
import dataclass.data

sealed abstract class MergeRule extends Product with Serializable

object MergeRule {
  sealed abstract class PathRule extends MergeRule {
    def path: String
  }

  @data class Exclude(path: String) extends PathRule
  @data class ExcludePattern(path: Pattern) extends MergeRule

  object ExcludePattern {
    def apply(s: String): ExcludePattern =
      ExcludePattern(Pattern.compile(s))
  }

  // TODO Accept a separator: Array[Byte] argument in these
  // (to separate content with a line return in particular)
  @data class Append(path: String) extends PathRule
  @data class AppendPattern(path: Pattern) extends MergeRule

  object AppendPattern {
    def apply(s: String): AppendPattern =
      AppendPattern(Pattern.compile(s))
  }

  val default = Seq(
    MergeRule.Append("reference.conf"),
    MergeRule.AppendPattern("META-INF/services/.*"),
    MergeRule.Exclude("log4j.properties"),
    MergeRule.Exclude(JarFile.MANIFEST_NAME),
    MergeRule.ExcludePattern("META-INF/.*\\.[sS][fF]"),
    MergeRule.ExcludePattern("META-INF/.*\\.[dD][sS][aA]"),
    MergeRule.ExcludePattern("META-INF/.*\\.[rR][sS][aA]")
  )
} 
Example 4
Source File: Using.scala    From Argus-SAF   with Apache License 2.0 5 votes vote down vote up
package org.argus.jawa.core.compiler.compile.io

import java.io.{Closeable, FileInputStream, FileOutputStream, InputStream, OutputStream, File => JavaFile}
import java.io.{BufferedInputStream, BufferedOutputStream, InputStreamReader, OutputStreamWriter}
import java.io.{BufferedReader, BufferedWriter}
import java.util.zip.GZIPInputStream
import java.net.URL
import java.nio.channels.FileChannel
import java.nio.charset.Charset
import java.util.jar.{JarFile, JarInputStream, JarOutputStream}
import java.util.zip.{GZIPOutputStream, ZipEntry, ZipFile, ZipInputStream, ZipOutputStream}

import ErrorHandling.translate

import scala.reflect.{Manifest => SManifest}

abstract class Using[Source, T]
{
  protected def open(src: Source): T
  def apply[R](src: Source)(f: T => R): R =
  {
    val resource = open(src)
    try { f(resource) }
    finally { close(resource) }
  }
  protected def close(out: T): Unit
}
abstract class WrapUsing[Source, T](implicit srcMf: SManifest[Source], targetMf: SManifest[T]) extends Using[Source, T]
{
  protected def label[S](m: SManifest[S]): String = m.runtimeClass.getSimpleName
  protected def openImpl(source: Source): T
  protected final def open(source: Source): T =
    translate("Error wrapping " + label(srcMf) + " in " + label(targetMf) + ": ") { openImpl(source) }
}
trait OpenFile[T] extends Using[JavaFile, T]
{
  protected def openImpl(file: JavaFile): T
  protected final def open(file: JavaFile): T =
  {
    val parent = file.getParentFile
    if(parent != null)
      IO.createDirectory(parent)
    openImpl(file)
  }
}
object Using
{
  def wrap[Source, T<: Closeable](openF: Source => T)(implicit srcMf: SManifest[Source], targetMf: SManifest[T]): Using[Source,T] =
    wrap(openF, closeCloseable)
  def wrap[Source, T](openF: Source => T, closeF: T => Unit)(implicit srcMf: SManifest[Source], targetMf: SManifest[T]): Using[Source,T] =
    new WrapUsing[Source, T]
    {
      def openImpl(source: Source): T = openF(source)
      def close(t: T): Unit = closeF(t)
    }

  def resource[Source, T <: Closeable](openF: Source => T): Using[Source,T] =
    resource(openF, closeCloseable)
  def resource[Source, T](openF: Source => T, closeF: T => Unit): Using[Source,T] =
    new Using[Source,T]
    {
      def open(s: Source): T = openF(s)
      def close(s: T): Unit = closeF(s)
    }
  def file[T <: Closeable](openF: JavaFile => T): OpenFile[T] = file(openF, closeCloseable)
  def file[T](openF: JavaFile => T, closeF: T => Unit): OpenFile[T] =
    new OpenFile[T]
    {
      def openImpl(file: JavaFile): T = openF(file)
      def close(t: T): Unit = closeF(t)
    }
  private def closeCloseable[T <: Closeable]: T => Unit = _.close()

  def bufferedOutputStream: Using[OutputStream, BufferedOutputStream] = wrap((out: OutputStream) => new BufferedOutputStream(out) )
  def bufferedInputStream: Using[InputStream, BufferedInputStream] = wrap((in: InputStream) => new BufferedInputStream(in) )
  def fileOutputStream(append: Boolean = false): OpenFile[BufferedOutputStream] = file(f => new BufferedOutputStream(new FileOutputStream(f, append)))
  def fileInputStream: OpenFile[BufferedInputStream] = file(f => new BufferedInputStream(new FileInputStream(f)))
  def urlInputStream: Using[URL, BufferedInputStream] = resource((u: URL) => translate("Error opening " + u + ": ")(new BufferedInputStream(u.openStream)))
  def fileOutputChannel: OpenFile[FileChannel] = file(f => new FileOutputStream(f).getChannel)
  def fileInputChannel: OpenFile[FileChannel] = file(f => new FileInputStream(f).getChannel)
  def fileWriter(charset: Charset = IO.utf8, append: Boolean = false): OpenFile[BufferedWriter] =
    file(f => new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, append), charset)) )
  def fileReader(charset: Charset): OpenFile[BufferedReader] = file(f => new BufferedReader(new InputStreamReader(new FileInputStream(f), charset)) )
  def urlReader(charset: Charset): Using[URL, BufferedReader] = resource((u: URL) => new BufferedReader(new InputStreamReader(u.openStream, charset)))
  def jarFile(verify: Boolean): OpenFile[JarFile] = file(f => new JarFile(f, verify), (_: JarFile).close())
  def zipFile: OpenFile[ZipFile] = file(f => new ZipFile(f), (_: ZipFile).close())
  def streamReader: Using[(InputStream, Charset), InputStreamReader] = wrap{ (_: (InputStream, Charset)) match { case (in, charset) => new InputStreamReader(in, charset) } }
  def gzipInputStream: Using[InputStream, GZIPInputStream] = wrap((in: InputStream) => new GZIPInputStream(in, 8192) )
  def zipInputStream: Using[InputStream, ZipInputStream] = wrap((in: InputStream) => new ZipInputStream(in))
  def zipOutputStream: Using[OutputStream, ZipOutputStream] = wrap((out: OutputStream) => new ZipOutputStream(out))
  def gzipOutputStream: Using[OutputStream, GZIPOutputStream] = wrap((out: OutputStream) => new GZIPOutputStream(out, 8192), (_: GZIPOutputStream).finish())
  def jarOutputStream: Using[OutputStream, JarOutputStream] = wrap((out: OutputStream) => new JarOutputStream(out))
  def jarInputStream: Using[InputStream, JarInputStream] = wrap((in: InputStream) => new JarInputStream(in))
  def zipEntry(zip: ZipFile): Using[ZipEntry, InputStream] = resource((entry: ZipEntry) =>
    translate("Error opening " + entry.getName + " in " + zip + ": ") { zip.getInputStream(entry) } )
} 
Example 5
Source File: ContainerInfo.scala    From service-container   with Apache License 2.0 5 votes vote down vote up
package com.github.vonnagy.service.container.health

import java.net.InetAddress
import java.util.jar.Attributes.Name
import java.util.jar.{Attributes, JarFile, Manifest}

import com.github.vonnagy.service.container.log.LoggingAdapter


  private[health] def getMainClass: Option[Class[_]] = {
    import scala.collection.JavaConverters._

    def checkStack(elem: StackTraceElement): Option[Class[_]] = try {
      if (elem.getMethodName.equals("main")) Some(Class.forName(elem.getClassName)) else None
    } catch {
      case _: ClassNotFoundException => {
        // Swallow the exception
        None
      }
    }

    Thread.getAllStackTraces.asScala.values.flatMap(currStack => {
      if (!currStack.isEmpty)
        checkStack(currStack.last)
      else
        None
    }).headOption match {
      case None =>
        sys.props.get("sun.java.command") match {
          case Some(command) if !command.isEmpty =>
            try {
              Some(Class.forName(command))
            } catch {
              // Swallow the exception
              case _: ClassNotFoundException =>
                None
            }

          // Nothing could be located
          case _ => None
        }
      case c => c
    }
  }

  private[health] def getManifest(clazz: Class[_]): Manifest = {
    val file: String = clazz.getProtectionDomain.getCodeSource.getLocation.getFile

    try {
      if (file.endsWith(".jar")) {
        new JarFile(file).getManifest
      }
      else {
        val manifest: Manifest = new Manifest
        manifest.getMainAttributes.put(Name.IMPLEMENTATION_TITLE, "Container Service")
        manifest.getMainAttributes.put(Name.IMPLEMENTATION_VERSION, "1.0.0")
        manifest.getMainAttributes.put(new Attributes.Name("Implementation-Build"), "N/A")
        manifest
      }
    }
    catch {
      case _: Exception => {
        val manifest: Manifest = new Manifest
        manifest.getMainAttributes.put(Name.IMPLEMENTATION_TITLE, "Container Service")
        manifest.getMainAttributes.put(Name.IMPLEMENTATION_VERSION, "1.0.0")
        manifest.getMainAttributes.put(new Attributes.Name("Implementation-Build"), "N/A")
        manifest
      }
    }
  }
} 
Example 6
Source File: Launcher.scala    From PackUpdate   with Apache License 2.0 5 votes vote down vote up
package at.chaosfield.packupdate.server

import java.io.File
import java.net.{URL, URLClassLoader}
import java.util.jar.{Attributes, JarFile, Manifest}

import scala.collection.JavaConverters._

object Launcher {
  def launchServer(file: File, args: Array[String]): Unit = {
    val manifest = new JarFile(file).getManifest
    val cp = manifest.getMainAttributes.getValue("Class-Path").split(' ').map(path => new File("libraries", path).toURI.toURL)
    val loader = new URLClassLoader(cp ++ Array(file.toURI.toURL))
    val klass = Class.forName(manifest.getMainAttributes.getValue("Main-Class"), true, loader)
    val m = klass.getDeclaredMethod("main", classOf[Array[String]])
    m.invoke(null, args)
  }
} 
Example 7
Source File: JarManifest.scala    From kafka-connect-common   with Apache License 2.0 5 votes vote down vote up
package com.datamountaineer.streamreactor.connect.utils

import java.io.File
import java.net.URL
import java.util.jar.JarFile

import scala.collection.mutable

case class JarManifest(location: URL) {

  val map = mutable.Map.empty[String, String]

  var msg = "unknown"
  try {
    val file = new File(location.toURI)
    if (file.isFile) {
      val jarFile = new JarFile(file)
      val manifest = jarFile.getManifest
      val attributes = manifest.getMainAttributes
      map += "StreamReactor-Version" -> attributes.getValue("StreamReactor-Version")
      map += "Kafka-Version" -> attributes.getValue("Kafka-Version")
      map += "Git-Repo" -> attributes.getValue("Git-Repo")
      map += "Git-Commit-Hash" -> attributes.getValue("Git-Commit-Hash")
      map += "Git-Tag" -> attributes.getValue("Git-Tag")
      map += "StreamReactor-Docs" -> attributes.getValue("StreamReactor-Docs")
    }
  }
  catch {
    case t: Throwable => msg = t.getMessage
  }


  def version(): String = map.getOrElse("StreamReactor-Version", "")

  def printManifest(): String = {
    val msg = "unknown"

    s"""
       |StreamReactor-Version:       ${map.getOrElse("StreamReactor-Version", msg)}
       |Kafka-Version:               ${map.getOrElse("Kafka-Version", msg)}
       |Git-Repo:                    ${map.getOrElse("Git-Repo", msg)}
       |Git-Commit-Hash:             ${map.getOrElse("Git-Commit-Hash", msg)}
       |Git-Tag:                     ${map.getOrElse("Git-Tag", msg)}
       |StreamReactor-Docs:          ${map.getOrElse("StreamReactor-Docs", msg)}
      """.
      stripMargin
  }
}