下面列出了java.util.jar.JarEntry#isDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
static void generateLargeJar(File result, File source) throws IOException {
if (result.exists()) {
result.delete();
}
try (JarOutputStream copyTo = new JarOutputStream(new FileOutputStream(result));
JarFile srcJar = new JarFile(source)) {
for (JarEntry je : Collections.list(srcJar.entries())) {
copyTo.putNextEntry(je);
if (!je.isDirectory()) {
copyStream(srcJar.getInputStream(je), copyTo);
}
copyTo.closeEntry();
}
int many = Short.MAX_VALUE * 2 + 2;
for (int i = 0 ; i < many ; i++) {
JarEntry e = new JarEntry("F-" + i + ".txt");
copyTo.putNextEntry(e);
}
copyTo.flush();
copyTo.close();
}
}
/** 在 jar 包里查找目标 */
private static void doScanByJar(String path, JarFile jar, String suffix, Set<String> urls) {
Enumeration<JarEntry> entry = jar.entries();
while (entry.hasMoreElements()) {
JarEntry e = entry.nextElement();
String n = e.getName();
if (n.charAt(0) == '/') {
n = n.substring(1);
}
if (e.isDirectory() || !n.startsWith(path) || !n.endsWith(suffix)) {
// 非指定包路径, 非目标后缀
continue;
}
urls.add(n);
}
}
private static void readJarEntries(final URL location, final String basePath, final Map<String, URL> resources) throws IOException {
final JarURLConnection conn = (JarURLConnection) location.openConnection();
final JarFile jarfile = conn.getJarFile();
final Enumeration<JarEntry> entries = jarfile.entries();
while (entries != null && entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
String name = entry.getName();
if (entry.isDirectory() || !name.startsWith(basePath) || name.length() == basePath.length()) {
continue;
}
name = name.substring(basePath.length());
if (name.contains("/")) {
continue;
}
final URL resource = new URL(location, name);
resources.put(name, resource);
}
}
private static void loadClassNamesFromJarInputStream(JarInputStream jarIn, String directory,
Location location, Multimap<String, Location> newClassNameLocations)
throws IOException {
JarEntry jarEntry;
while ((jarEntry = jarIn.getNextJarEntry()) != null) {
if (jarEntry.isDirectory()) {
continue;
}
String name = jarEntry.getName();
if (name.startsWith(directory) && name.endsWith(".class")) {
name = name.substring(directory.length());
String className = name.substring(0, name.lastIndexOf('.')).replace('/', '.');
newClassNameLocations.put(className, location);
}
}
}
private void unJar(JarFile jarFile, File targetDirectory) throws IOException {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
File output = new File(targetDirectory, entry.getName());
if (entry.isDirectory()) {
output.mkdirs();
} else {
output.getParentFile().mkdirs();
try (
OutputStream os = new FileOutputStream(output);
InputStream is = jarFile.getInputStream(entry)
) {
ByteStreams.copy(is, os);
}
}
}
}
/**
* Extract the source {@link JarFile} to target directory with specified {@link JarEntryFilter}
*
* @param jarResourceURL
* The resource URL of {@link JarFile} or {@link JarEntry}
* @param targetDirectory
* target directory
* @param jarEntryFilter
* {@link JarEntryFilter}
* @throws IOException
* When the source jar file is an invalid {@link JarFile}
*/
public static void extract(URL jarResourceURL, File targetDirectory, JarEntryFilter jarEntryFilter) throws IOException {
final JarFile jarFile = JarUtils.toJarFile(jarResourceURL);
final String relativePath = JarUtils.resolveRelativePath(jarResourceURL);
final JarEntry jarEntry = jarFile.getJarEntry(relativePath);
final boolean isDirectory = jarEntry.isDirectory();
List<JarEntry> jarEntriesList = filter(jarFile, new JarEntryFilter() {
@Override
public boolean accept(JarEntry filteredObject) {
String name = filteredObject.getName();
if (isDirectory && name.equals(relativePath)) {
return true;
} else if (name.startsWith(relativePath)) {
return true;
}
return false;
}
});
jarEntriesList = doFilter(jarEntriesList, jarEntryFilter);
doExtract(jarFile, jarEntriesList, targetDirectory);
}
/**
* Finds native library entry.
*
* @param sLib Library name. For example for the library name "Native"
* - Windows returns entry "Native.dll"
* - Linux returns entry "libNative.so"
* - Mac returns entry "libNative.jnilib" or "libNative.dylib"
* (depending on Apple or Oracle JDK and/or JDK version)
* @return Native library entry.
*/
private JarEntryInfo findJarNativeEntry(String sLib) {
String sName = System.mapLibraryName(sLib);
for (JarFileInfo jarFileInfo : lstJarFile) {
JarFile jarFile = jarFileInfo.jarFile;
Enumeration<JarEntry> en = jarFile.entries();
while (en.hasMoreElements()) {
JarEntry je = en.nextElement();
if (je.isDirectory()) {
continue;
}
// Example: sName is "Native.dll"
String sEntry = je.getName(); // "Native.dll" or "abc/xyz/Native.dll"
// sName "Native.dll" could be found, for example
// - in the path: abc/Native.dll/xyz/my.dll <-- do not load this one!
// - in the partial name: abc/aNative.dll <-- do not load this one!
String[] token = sEntry.split("/"); // the last token is library name
if (token.length > 0 && token[token.length - 1].equals(sName)) {
logInfo(LogArea.NATIVE, "Loading native library '%s' found as '%s' in JAR %s",
sLib, sEntry, jarFileInfo.simpleName);
return new JarEntryInfo(jarFileInfo, je);
}
}
}
return null;
}
private static void list(String pathToJar) throws IOException, ClassNotFoundException {
JarFile jarFile = new JarFile(pathToJar);
URL[] urls = { new URL("jar:file:" + pathToJar + "!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);
for (JarEntry entry : Collections.list(jarFile.entries())) {
if (entry.isDirectory()
|| !entry.getName().endsWith(".class")
|| !entry.getName().startsWith("io/cassandrareaper/")) {
continue;
}
// -6 because of ".class"
String className = entry.getName().substring(0, entry.getName().length() - 6).replace('/', '.');
LOG.info(pathToJar + "!/" + className);
cl.loadClass(className);
}
}
private Set<String> findInJar(JarFile localJarFile, String packageName) {
Set<String> classFiles = new HashSet<String>();
Enumeration<JarEntry> entries = localJarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement();
String entryName = jarEntry.getName();
if (!jarEntry.isDirectory() && (packageName == null || entryName.startsWith(packageName)) && entryName.endsWith(".class")) {
String className = entryName.replaceAll("/", ".").substring(0, entryName.length() - 6);
classFiles.add(className);
}
}
return classFiles;
}
private boolean unzipJarAlt(String pathJar, String pathDir) {
try {
FileInputStream fileStream = new FileInputStream(File.separator + pathJar);
JarInputStream jarStream = new JarInputStream(fileStream);
JarEntry entry = jarStream.getNextJarEntry();
while (entry != null) {
File fileEntry = new File(File.separator + pathDir + File.separator + entry.getName());
if (entry.isDirectory()) {
fileEntry.mkdirs();
}
else {
FileOutputStream os = new FileOutputStream(fileEntry);
while (jarStream.available() > 0) {
os.write(jarStream.read());
}
os.close();
}
entry = jarStream.getNextJarEntry();
}
jarStream.close();
return true;
}
catch (IOException e) {
e.printStackTrace();
}
return false;
}
public static void extractJar(JarFile jf, File where) throws Exception {
for (JarEntry file : Collections.list(jf.entries())) {
File out = new File(where, file.getName());
if (file.isDirectory()) {
out.mkdirs();
continue;
}
File parent = out.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
InputStream is = null;
OutputStream os = null;
try {
is = jf.getInputStream(file);
os = new FileOutputStream(out);
while (is.available() > 0) {
os.write(is.read());
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
}
}
private static String installJars(final File m2Root, final boolean forceOverwrite) {
String mainGav = null;
try (final JarInputStream jar =
new JarInputStream(new BufferedInputStream(new FileInputStream(jarLocation(CarMain.class))))) {
JarEntry entry;
while ((entry = jar.getNextJarEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
if (entry.getName().startsWith("MAVEN-INF/repository/")) {
final String path = entry.getName().substring("MAVEN-INF/repository/".length());
final File output = new File(m2Root, path);
if (!output.getCanonicalPath().startsWith(m2Root.getCanonicalPath())) {
throw new IOException("The output file is not contained in the destination directory");
}
if (!output.exists() || forceOverwrite) {
output.getParentFile().mkdirs();
Files.copy(jar, output.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
} else if ("TALEND-INF/metadata.properties".equals(entry.getName())) {
// mainGav
final Properties properties = new Properties();
properties.load(jar);
mainGav = properties.getProperty("component_coordinates");
}
}
} catch (final IOException e) {
throw new IllegalArgumentException(e);
}
if (mainGav == null || mainGav.trim().isEmpty()) {
throw new IllegalArgumentException("Didn't find the component coordinates");
}
return mainGav;
}
public static void extractJar(JarFile jf, File where) throws Exception {
for (JarEntry file : Collections.list(jf.entries())) {
File out = new File(where, file.getName());
if (file.isDirectory()) {
out.mkdirs();
continue;
}
File parent = out.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
InputStream is = null;
OutputStream os = null;
try {
is = jf.getInputStream(file);
os = new FileOutputStream(out);
while (is.available() > 0) {
os.write(is.read());
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
}
}
/**
* Locate all Webjars Maven pom.properties files on the classpath.
*
* @return a list of Maven pom.properties files on the classpath
*/
private List<String> locatePomProperties() {
List<String> propertiesFiles = new ArrayList<>();
List<URL> packageUrls = ClasspathUtils.getResources(getResourceBasePath());
for (URL packageUrl : packageUrls) {
if (packageUrl.getProtocol().equals("jar")) {
// We only care about Webjars jar files
log.debug("Scanning {}", packageUrl);
try {
String jar = packageUrl.toString().substring("jar:".length()).split("!")[0];
File file = new File(new URI(jar));
try (JarInputStream is = new JarInputStream(new FileInputStream(file))) {
JarEntry entry = null;
while ((entry = is.getNextJarEntry()) != null) {
if (!entry.isDirectory() && entry.getName().endsWith("pom.properties")) {
propertiesFiles.add(entry.getName());
}
}
}
} catch (URISyntaxException | IOException e) {
throw new PippoRuntimeException("Failed to get classes for package '{}'", packageUrl);
}
}
}
return propertiesFiles;
}
@Override
public void guide(URLVisitor v, boolean recurse, boolean strip) {
try {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (!entry.isDirectory()) { // skip just directory paths
String name = entry.getName();
if (name.startsWith(prefix)) {
name = name.substring(prefix.length());
int ix = name.lastIndexOf('/');
if (ix > 0 && !recurse) {
continue;
}
if (strip && ix != -1) {
name = name.substring(ix+1);
}
v.visit(name);
}
}
}
}
catch (Exception e) {
if (DEBUG) System.err.println("icurb jar error: " + e);
}
}
private boolean copyJarResources(final File destDir, final JarFile jarFile,
final JarEntry entry) throws IOException {
String filename = entry.getName();
final File f = new File(destDir, filename);
if (!entry.isDirectory()) {
InputStream entryInputStream = null;
try {
entryInputStream = jarFile.getInputStream(entry);
if (!copyStream(entryInputStream, f)) {
return false;
}
if (filename.indexOf("htfconf") != -1 || filename.indexOf(".properties") != -1
|| filename.indexOf(".yaml") != -1) {
DEBUG_FILE_LOGGER.debug("Replacing placeholders for [" + filename + "]");
replacePlaceHolders(f, FoundPaths);
}
} finally {
if (entryInputStream != null) {
entryInputStream.close();
}
}
} else {
if (!ensureDirectoryExists(f)) {
throw new IOException("Error occurred while extracting : " + f.getAbsolutePath());
}
}
return true;
}
/**
* In this case we are dealing with facts which are not on the systems classpath.
*/
@Test
public void testSerializabilityWithJarFacts() throws Exception {
MapBackedClassLoader loader = new MapBackedClassLoader( this.getClass().getClassLoader() );
JarInputStream jis = new JarInputStream( this.getClass().getResourceAsStream( "/billasurf.jar" ) );
JarEntry entry = null;
byte[] buf = new byte[1024];
int len = 0;
while ( (entry = jis.getNextJarEntry()) != null ) {
if ( !entry.isDirectory() ) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ( (len = jis.read( buf )) >= 0 ) {
out.write( buf,
0,
len );
}
loader.addResource( entry.getName(),
out.toByteArray() );
}
}
String drl = "package foo.bar \n" +
"import com.billasurf.Board\n" +
"rule 'MyGoodRule' \n dialect 'mvel' \n when " +
" Board() " +
"then \n" +
" System.err.println(42); \n" +
"end\n";
KnowledgeBuilderConfiguration kbuilderConf = KnowledgeBuilderFactory.newKnowledgeBuilderConfiguration(null, loader);
Collection<KiePackage> kpkgs = loadKnowledgePackagesFromString(kbuilderConf, drl);
kpkgs = SerializationHelper.serializeObject( kpkgs, loader );
}
private void loadModulesFromJar(HashMap<String,Class<Encoder>> module_list) throws Exception
{
File[] files = new File(DEFAULT_PLUGIN_DIR).listFiles();
if(null==files){
return;
}
for(File file:files){
if(!file.isFile() || !"jar".equals(FilenameUtils.getExtension(file.getName()))){
continue;
}
URLClassLoader urlClassLoader = URLClassLoader.newInstance(new URL[]{file.toURI().toURL()});
JarFile jarFile = new JarFile(file.getPath());
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); )
{
//Jar filter
JarEntry jarEntry = entries.nextElement();
if (jarEntry.isDirectory()) continue;
// class filter
String fileName = jarEntry.getName();
if (!fileName.endsWith(".class")) continue;
Class<?> klass;
try {
//jar内のクラスファイルの階層がパッケージに準拠している必要がある
//例: packetproxy.plugin.EncodeHTTPSample
//-> packetproxy/plugin/EncodeHTTPSample.class
String encode_class_path = fileName.replaceAll("\\.class.*$", "").replaceAll("/",".");
klass = urlClassLoader.loadClass(encode_class_path);
} catch (Exception e) {
e.printStackTrace();
continue;
}
// Encode Classを継承しているか
if (!encode_class.isAssignableFrom(klass)) continue;
if (Modifier.isAbstract(klass.getModifiers())) continue;
@SuppressWarnings("unchecked")
Encoder encoder = createInstance((Class<Encoder>)klass, null);
String encoderName = encoder.getName();
if(module_list.containsKey(encoderName)){
isDuplicated = true;
encoderName += "-" + file.getName();
}
module_list.put(encoderName, (Class<Encoder>)klass);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isFile(final JarEntry entry) {
return !entry.isDirectory();
}
public ValidationResult afterSelectClass() {
List<String> driverClasses = new ArrayList<>();
AllSetting setting = new AllSetting();
setting.setDriverPaths(driverTable.drivers.getValue());
List<String> jar_maven_paths = setting.getDriverPaths();
try {
List<URL> urls = new ArrayList<>();
for (String maven_path : jar_maven_paths) {
URL url = new URL(removeQuote(maven_path));
urls.add(url);
}
URLClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[0]), this.getClass().getClassLoader());
for (URL jarUrl : urls) {
try (JarInputStream jarInputStream = new JarInputStream(jarUrl.openStream())) {
JarEntry nextJarEntry = jarInputStream.getNextJarEntry();
while (nextJarEntry != null) {
boolean isFile = !nextJarEntry.isDirectory();
if (isFile) {
String name = nextJarEntry.getName();
if (name != null && name.toLowerCase().endsWith(".class")) {
String className = changeFileNameToClassName(name);
try {
Class clazz = classLoader.loadClass(className);
if (Driver.class.isAssignableFrom(clazz)) {
driverClasses.add(clazz.getName());
}
} catch (Throwable th) {
// ignore all the exceptions, especially the class not found exception when look up a class
// outside the jar
}
}
}
nextJarEntry = jarInputStream.getNextJarEntry();
}
}
}
} catch (Exception ex) {
return new ValidationResult(ValidationResult.Result.ERROR, ex.getMessage());
}
if (driverClasses.isEmpty()) {
return new ValidationResult(ValidationResult.Result.ERROR,
"not found any Driver class, please make sure the jar is right");
}
driverClass.setPossibleValues(driverClasses);
driverClass.setValue(driverClasses.get(0));
return ValidationResult.OK;
}