How to extract directory (and sub directories) from jar resource? - jar

I've a dir (with sub dirs) template that is kept as a resource inside a jar file. During run
time I need to extract it (template) to tmp dir change some content and finally publish it as a zipped artifact.
My question is: how to extract this content easily? I was trying getResource() as well as getResourceAsStream()..

Following code works fine here: (Java7)
String s = this.getClass().getResource("").getPath();
if (s.contains("jar!")) {
// we have a jar file
// format: file:/location...jar!...path-in-the-jar
// we only want to have location :)
int excl = s.lastIndexOf("!");
s = s.substring(0, excl);
s = s.substring("file:/".length());
Path workingDirPath = workingDir = Files.createTempDirectory("demo")
try (JarFile jf = new JarFile(s);){
Enumeration<JarEntry> entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry je = entries.nextElement();
String name = je.getName();
if (je.isDirectory()) {
// directory found
Path dir = workingDirPath.resolve(name);
Files.createDirectory(dir);
} else {
Path file = workingDirPath.resolve(name);
try (InputStream is = jf.getInputStream(je);) {
Files.copy(is, file, StandardCopyOption.REPLACE_EXISTING);
}
}
}
}
} else {
// debug mode: no jar
}

Related

create Directory and if exist then rename it

i am developing application in which i want that if user create folder and if it is already present then folder should automatically renamed by appending number to folder name
suppose server has folder with name Time now if user again creates folder than it new folder will be Time1 again user creates folder with same name(Time or Time1) than new Folder should be created with Time2 and so on... This is what i have done so far but recursion always return wrong value.
public string checkIfExist(String path, String ProgramName, int itteration,out string strFolderName)
{
String uploadPath = "";
strFolderName = "";
String Mappath =HttpContext.Current.Server.MapPath(path);
if (Directory.Exists(Mappath))
{
String Path = HttpContext.Current.Server.MapPath((path + "" + ProgramName.Replace(" ", "_")));
// uploadPath += ++itteration ;
if (Directory.Exists(Path))
{
ProgramName += ++itteration;
strFolderName = ProgramName;
uploadPath = checkIfExist(path, ProgramName, itteration,out strFolderName);
}
}
return ProgramName;
}
Perhaps you could adapt this, to your need. I wrote it on the fly based on a piece of code I remember in an old file manager I was using in some projects, so please test it. This doesn't include creation and so on, based on your example I'm sure you can add that yourself but if you need help just comment below.
The idea is to pass the original name of the directory you want, and then return an appropriate new name if it exists, such as Test(1), Test(2), Test(n). Then once you get the name you need, you can create it directly.
protected string GetUniqueDirectoryName(string dirName)
{
string newDirName = dirName;
for (int i = 1; Directory.Exists(Server.MapPath("PATH_HERE") + newDirName); i++)
{
newDirName = string.Format("{0}({1})", dirName, i);
}
return newDirName;
}
Note: You will need to include System.IO and probably use HttpContext.Current.Server.MapPath instead of Server.MapPath
I don't know if I really understand what you are trying to do, but I think using recursion here is a little overkill. Try something like this:
string dirName = "Time";
int counter = 0;
string dir = dirName;
while(Directory.Exists(dir))
{
dir = String.Format("{0}{1}", dirName, (++counter).ToString());
}
Directory.CreateDirectory(dir);

How to copy files from JARs to WAR in Gradle?

I need to copy specific files that are in JARs into specific directory in WAR, using Gradle.
My code:
war.doFirst {
for(file in classpath) {
FileTree tree = zipTree(file)
FileTree treeResources = tree.matching { include "META-INF/resources/*" }
String folderName = 'destinationFolder'
{
treeResources.each {
File resources -> copy {
from resources
String dest = war.destinationDir.name + "/" + war.archiveName + "/" + folderName
into dest
}
}
}
}
Problem: the "dest" value is incorrect, instead of being in the created WAR file, it is something like "libs/mywar-1.0.war/destinationFolder".
You'll want something like:
war {
into("destinationFolder") {
from { classpath.collect { zipTree(it) } }
include "META-INF/resources/**"
}
}

FileStatus use to recurse directory

I have following directory structure,
Dir1
|___Dir2
|___Dir3
|___Dir4
|___File1.gz
|___File2.gz
|___File3.gz
The subdirectories are just nested and donot contain any files
I am trying to use the following for recursing through a directory on HDFS.If its a directory I append /* to the path and addInputPath
arg[0] = "path/to/Dir1"; // given at command line
FileStatus fs = new FileStatus();
Path q = new Path(args[0]);
FileInputFormat.addInputPath(job,q);
Path p = new Path(q.toString()+"/*");
fs.setPath(p);
while(fs.isDirectory())
{
fs.setPath(new Path(p.toString()+"/*"));
FileInputFormat.addInputPath(job,fs.getPath());
}
But the code doesnt seem to go in the while loop and I get not a File Exception
Where is the if statement you are referring to?
Anyway, you may have a look at these utility methods which add all files within a directory to a job's input:
Utils:
public static Path[] getRecursivePaths(FileSystem fs, String basePath)
throws IOException, URISyntaxException {
List<Path> result = new ArrayList<Path>();
basePath = fs.getUri() + basePath;
FileStatus[] listStatus = fs.globStatus(new Path(basePath+"/*"));
for (FileStatus fstat : listStatus) {
readSubDirectory(fstat, basePath, fs, result);
}
return (Path[]) result.toArray(new Path[result.size()]);
}
private static void readSubDirectory(FileStatus fileStatus, String basePath,
FileSystem fs, List<Path> paths) throws IOException, URISyntaxException {
if (!fileStatus.isDir()) {
paths.add(fileStatus.getPath());
}
else {
String subPath = fileStatus.getPath().toString();
FileStatus[] listStatus = fs.globStatus(new Path(subPath + "/*"));
if (listStatus.length == 0) {
paths.add(fileStatus.getPath());
}
for (FileStatus fst : listStatus) {
readSubDirectory(fst, subPath, fs, paths);
}
}
}
Use it in your job runner class:
...
Path[] inputPaths = Utils.getRecursivePaths(fs, inputPath);
FileInputFormat.setInputPaths(job, inputPaths);
...

How do I do "git show sha1:file" using JGit

I clone a repository as bare on my local disk using JGit. Now, I need to read the contents of a file at any given commit id (SHA1). How do I do this ?
The comment of RĂ¼diger Herrmann in this answer contains the relevant hints; but to make it easier for the friends of copy & paste solutions here my complete self-contained example code of a junit test that creates a revision of a file and then retrieves the contents of this revision. Works with jGit 4.2.0.
#Test
public void test() throws IOException, GitAPIException
{
//
// init the git repository in a temporary directory
//
File repoDir = Files.createTempDirectory("jgit-test").toFile();
Git git = Git.init().setDirectory(repoDir).call();
//
// add file with simple text content
//
String testFileName = "testFile.txt";
File testFile = new File(repoDir, testFileName);
writeContent(testFile, "initial content");
git.add().addFilepattern(testFileName).call();
RevCommit firstCommit = git.commit().setMessage("initial commit").call();
//
// given the "firstCommit": use its "tree" and
// localize the test file by its name with the help of a tree parser
//
Repository repository = git.getRepository();
try (ObjectReader reader = repository.newObjectReader())
{
CanonicalTreeParser treeParser = new CanonicalTreeParser(null, reader, firstCommit.getTree());
boolean haveFile = treeParser.findFile(testFileName);
assertTrue("test file in commit", haveFile);
assertEquals(testFileName, treeParser.getEntryPathString());
ObjectId objectForInitialVersionOfFile = treeParser.getEntryObjectId();
// now we have the object id of the file in the commit:
// open and read it from the reader
ObjectLoader oLoader = reader.open(objectForInitialVersionOfFile);
ByteArrayOutputStream contentToBytes = new ByteArrayOutputStream();
oLoader.copyTo(contentToBytes);
assertEquals("initial content", new String(contentToBytes.toByteArray(), "utf-8"));
}
git.close();
}
// simple helper to keep the main code shorter
private void writeContent(File testFile, String content) throws IOException
{
try (OutputStreamWriter wr = new OutputStreamWriter(new FileOutputStream(testFile), Charset.forName("utf-8")))
{
wr.append(content);
}
}
Edit to add: another, probably better example is at https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/api/ReadFileFromCommit.java
By using this. Iterable<RevCommit> gitLog = gitRepo.log().call(); you can get all the commit hash from that object.

How to remove folder path in zip file

I am generating the zip file from this folder "D:\Nagaraj\Dotnet\Zipfile\Zipfile\Filebuild\Hi" within that "Hi" folder has 2 txt files. .....yes Now generating the Hi.zip file.But problem is Within that zip file has this particular path "D:\Nagaraj\Dotnet\Zipfile\Zipfile\Filebuild\Hi" and within that hi folder has 2 txt fils. Now I need to remove this path "D:\Nagaraj\Dotnet\Zipfile\Zipfile\Filebuild\Hi" and directly generate that Hi.zip file and within that 2 txt file......thanks ....in advance
I am using sharpziplib library enter code here
protected void Page_Load(object sender, EventArgs e)
{
StartZip("D:/Nagaraj/Dotnet/Zipfile/Zipfile/Filebuild/Hi",".zip");
}
public void StartZip(string directory, string zipFileName)
{
ZipFile z = ZipFile.Create(directory + zipFileName);
z.BeginUpdate();
string[] filenames = Directory.GetFiles(directory);
foreach (string filename in filenames)
{
z.Add(filename);
}
z.CommitUpdate();
z.Close();
}
From the help file, where you add your files, you say how to do you like to show inside the zip.
public void StartZip(string directory, string zipFileName)
{
using(ZipFile z = ZipFile.Create(directory + zipFileName))
{
z.BeginUpdate();
// Create a reference to the directory.
DirectoryInfo di = new DirectoryInfo(directory);
// Create an array representing the files in the current directory.
FileInfo[] fi = di.GetFiles();
// here the entryName is the name that you like to show inside zip
foreach (FileInfo fiTemp in fi)
z.Add(fiTemp.FullName, fiTemp.Name);
z.CommitUpdate();
z.Close();
}
}

Resources