How to download a jar from artifactory with gradle to project directory? - gradle

What is the correct way to write a gradle task which downloads a .jar(or any other) file from artifactory to project directory(if file does not already exists)?
For example, I have a project with path /root/project with file /root/project/build.gradle inside. I want to download generator.jar from artifactory (com/company/project/generator/1.0) to /root/project directory if /root/project/generator.jar is not present.

tasks.register("downloadGeneratorJar") {
group = 'Download'
description = 'Downloads generator.jar'
doLast {
def f = new File('generator.jar')
if (!f.exists()) {
URL artifactoryUrl = new URL('myurl')
HttpURLConnection myURLConnection = (HttpURLConnection)artifactoryUrl.openConnection()
String userCredentials = gradle.ext.developerUser + ":" + gradle.ext.developerPassword
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()))
myURLConnection.setRequestProperty ("Authorization", basicAuth)
InputStream is = myURLConnection.getInputStream()
new FileOutputStream(f).withCloseable { outputStream ->
int read
byte[] bytes = new byte[1024]
while ((read = is.read(bytes)) != -1) {
outputStream.write(bytes, 0, read)
}
}
}
}
}

Related

Kotlin : copy image to gallery

I am trying to copy an image that is stored in my application folder to a predefined folder in my gallery.
I started from an image sharing code..
This is my code :
val extension = when (requireNotNull(pictureResult).format) {
PictureFormat.JPEG -> "jpg"
PictureFormat.DNG -> "dng"
else -> throw RuntimeException("Unknown format.")
}
val timestamp = System.currentTimeMillis()
val namePhoto = "picture_"+timestamp+"."+extension;
val destFile = File(filesDir, namePhoto)
val folder = "/CustomFolder"
CameraUtils.writeToFile(requireNotNull(pictureResult?.data), destFile) { file ->
if (file != null) {
// Code to share - it works
/*
val context = this#PicturePreviewActivity
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*"
val uri = FileProvider.getUriForFile(context, context.packageName + ".provider", file)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(intent)
*/
*/
// Code to save image to gallery - doesn't work :(
val photoDirectory = File(Environment.DIRECTORY_PICTURES+folder, namePhoto)
val sourcePath = Paths.get(file.toURI())
Log.i("LOG","sourcePath : "+sourcePath.toString()) // /data/user/0/com.app.demo/files/picture_1663772068143.jpg
val targetPath = Paths.get(photoDirectory.toURI())
Log.i("LOG","targetPath : "+targetPath.toString()) // /Pictures/CustomFolder/picture_1663772068143.jpg
Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING)
// Error here but I don't know why
} else {
Toast.makeText(this#PicturePreviewActivity, "Error while writing file.", Toast.LENGTH_SHORT).show()
}
}
How do I copy the image to a predefined folder?
Ok, I did it !
Solution :
val folder = "/CustomFolder/" // name of your folder
val timestamp = System.currentTimeMillis()
val namePicture = "picture_"+timestamp+"."+extension;
try {
val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+folder);
if (!path.exists()) {
path.mkdir();
}
val pathImage = File(path,namePicture)
val stream = FileOutputStream(pathImage)
stream.write(imageByteArray).run {
stream.flush()
stream.close()
}
} catch (e: FileNotFoundException) {
e.printStackTrace()
}

Unable to upload files greater than 7KB via ajax call to servlet over https

I am running JBoss 6.3 portal and have deployed a war file containing following two files
1) DocUpload.jsp
Containing following code snippet making an ajax call to send the mentioned fields in data2 along with file object fd.
fd.append('file', document.getElementById('file1').files[0]);
data2 = encodeURIComponent(document.getElementById("lob").value)+'#'+encodeURIComponent(document.getElementById("loantype").value)+
'#'+encodeURIComponent(document.getElementById('docType').value)+'#'+encodeURIComponent(document.getElementById('docName').value)+
'#'+encodeURIComponent(document.getElementById('entity').value)+'#'+encodeURIComponent(document.getElementById('userName').value)+
'#'+encodeURIComponent(document.getElementById('PartyName').value)+'#'+encodeURIComponent(document.getElementById('loanAccount').value)+
'#'+encodeURIComponent(document.getElementById('LoanAmount').value)+'#'+encodeURIComponent(e4)+'#'+encodeURIComponent(document.getElementById('hiddenWIName').value)+'#'+encodeURIComponent(e3);
alert("data2 "+data2);
var ret = doPostAjax("${pageContext.request.contextPath}/AddDocumentsServlet?data="+data2,fd);
2) AddDocumentsServlet.java
Containing code for handling the request
File path = new File(RootFolderPath + File.separator + "Portal_TmpDoc" + File.separator + todayAsString + File.separator + lMilliSecondsCurrent);
UploadPath = path.getAbsolutePath();
if (!path.isDirectory()) {
path.mkdirs();
}
if (isMultipart) {
System.out.println("Inside if isMultipart");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(MEMORY_THRESHOLD);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
try {
//List multiparts = upload.parseRequest(request);
System.out.println("Before parsing request");
List<FileItem> multiparts = upload.parseRequest(request);
System.out.println("multiparts :::"+multiparts);
for (Iterator iterator = multiparts.iterator(); iterator.hasNext();) {
FileItem item = (FileItem) iterator.next();
logger.info(item);
if (!item.isFormField()) {
String fileobject = item.getFieldName();
System.out.println(request.getParameter("data"));
String[] fileArray = request.getParameter("data").split("#");
name = new File(item.getName()).getName();
name = name.substring(name.lastIndexOf(File.separatorChar) + 1);
ext = name.substring(name.lastIndexOf(".") + 1);
logger.info(name);
File directory = new File(UploadPath);
File[] afile;
int j = (afile = directory.listFiles()).length;
for (int i = 0; i < j; i++) {
File f = afile[i];
if (f.getName().startsWith(filename))
f.delete();
}
item.write(new File(UploadPath + File.separator + filename + "." + ext));
System.out.println("File Uploaded");
}
}
My problem is when I use http connection for the above requests and getting session the program runs just fine. But while using https and uploading file greater than 7 KB the page becomes unresponsive.
On further analysis I found that the program flow gets stuck on this line
List<FileItem> multiparts = upload.parseRequest(request);
and despite having this line in a try block no exception is caught.

Unzip a file in kotlin script [.kts]

I was toying with the idea of rewriting some existing bash scripts in kotlin script.
One of the scripts has a section that unzips all the files in a directory. In bash:
unzip *.zip
Is there a nice way to unzip a file(s) in kotlin script?
The easiest way is to just use exec unzip (assuming that the name of your zip file is stored in zipFileName variable):
ProcessBuilder()
.command("unzip", zipFileName)
.redirectError(ProcessBuilder.Redirect.INHERIT)
.redirectOutput(ProcessBuilder.Redirect.INHERIT)
.start()
.waitFor()
The different approach, that is more portable (it will run on any OS and does not require unzip executable to be present), but somewhat less feature-full (it will not restore Unix permissions), is to do unzipping in code:
import java.io.File
import java.util.zip.ZipFile
ZipFile(zipFileName).use { zip ->
zip.entries().asSequence().forEach { entry ->
zip.getInputStream(entry).use { input ->
File(entry.name).outputStream().use { output ->
input.copyTo(output)
}
}
}
}
If you need to scan all *.zip file, then you can do it like this:
File(".").list { _, name -> name.endsWith(".zip") }?.forEach { zipFileName ->
// any of the above approaches
}
or like this:
import java.nio.file.*
Files.newDirectoryStream(Paths.get("."), "*.zip").forEach { path ->
val zipFileName = path.toString()
// any of the above approaches
}
this code is for unziping from Assets
1.for unzping first u need InputStream
2.put it in ZipInputStream
3.if directory is not exist u have to make by .mkdirs()
private val BUFFER_SIZE = 8192//2048;
private val SDPath = Environment.getExternalStorageDirectory().absolutePath
private val unzipPath = "$SDPath/temp/zipunzipFile/unzip/"
var count: Int
val buffer = ByteArray(BUFFER_SIZE)
val context: Context = this
val am = context.getAssets()
val stream = context.getAssets().open("raw.zip")
try {
ZipInputStream(stream).use { zis ->
var ze: ZipEntry
while (zis.nextEntry.also { ze = it } != null) {
var fileName = ze.name
fileName = fileName.substring(fileName.indexOf("/") + 1)
val file = File(unzipPath, fileName)
val dir = if (ze.isDirectory) file else file.getParentFile()
if (!dir.isDirectory() && !dir.mkdirs())
throw FileNotFoundException("Invalid path: " + dir.getAbsolutePath())
if (ze.isDirectory) continue
val fout = FileOutputStream(file)
try {
while ( zis.read(buffer).also { count = it } != -1)
fout.write(buffer, 0, count)
} finally {
val fout : FileOutputStream =openFileOutput(fileName, Context.MODE_PRIVATE)
fout.close()
}
}
for unziping from externalStorage:
private val sourceFile= "$SDPath/unzipFile/data/"
ZipInputStream zis = null;
try {
zis = new ZipInputStream(new BufferedInputStream(new
FileInputStream(sourceFile)));
ZipEntry ze;
int count;
byte[] buffer = new byte[BUFFER_SIZE];
while ((ze = zis.getNextEntry()) != null) {
String fileName = ze.getName();
fileName = fileName.substring(fileName.indexOf("/") + 1);
File file = new File(destinationFolder, fileName);
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Invalid path: " +
dir.getAbsolutePath());
if (ze.isDirectory()) continue;
FileOutputStream fout = new FileOutputStream(file);
try {
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally {
fout.close();
}
}
} catch (IOException ioe) {
Log.d(TAG, ioe.getMessage());
return false;
} finally {
if (zis != null)
try {
zis.close();
} catch (IOException e) {
}
}
return true;

how to add a folder in the apk

I wanna to know how to add a folder in the apk.don't give me a solution about using the compress software directly. The apk was recompiled by the 'apktool.jar'. I need some code to achieve this problem. Hope one can solve my question as soon as possible.Thank you~
public static int zipMetaInfFolderToApk(String apkName, String folderName) throws IOException {
if(!new File(apkName).exists()){
return ConstantValue.ISQUESTION;
}
String zipName = apkName.substring(0, apkName.lastIndexOf(".")) + "."
+ "zip";
String bak_zipName = apkName.substring(0, apkName.lastIndexOf("."))
+ "_bak." + "zip";
FileUtils.renameFile(apkName, zipName);
ZipFile war = new ZipFile(zipName);
ZipOutputStream append = new ZipOutputStream(new FileOutputStream(
bak_zipName));
Enumeration<? extends ZipEntry> entries = war.entries();
while (entries.hasMoreElements()) {
ZipEntry e = entries.nextElement();
System.out.println("copy: " + e.getName());
append.putNextEntry(e);
if (!e.isDirectory()) {
copy(war.getInputStream(e), append);
}
append.closeEntry();
}
String name = "";
if(folderName.equals("")){
name = "META-INF/" + folderName;
}else{
name = "META-INF/" + folderName + "/";
}
ZipEntry e = new ZipEntry(name);
try{
append.putNextEntry(e);
}catch(ZipException e1){
append.closeEntry();
war.close();
append.close();
FileUtils.renameFile(zipName,apkName);
FileUtils.deleteFolder(bak_zipName);
e1.printStackTrace();
return ConstantValue.ISQUESTION;
}
append.closeEntry();
war.close();
append.close();
FileUtils.deleteFolder(zipName);
FileUtils.renameFile(bak_zipName, apkName);
return ConstantValue.ISNORMAL;
}

How to extract dot app(.app) mac file from a zip programmatically?

I am working on a Unity project & facing an issue.
I have a zip file containing mybuild.app (mac) file.
I am using SharpZipLib to uncompress the zip file. Issue is, when lib uncompressing, it actually taking mybuild.app as a folder & create a directory with same name & its sub files & folders. After uncompressing mybuild.app is not being able to start.
I think the issue is with .app signature or something. I shouldn't extract .app file content separately.
Please tell me how can i get mybuild.app file from zip which actually works.
I am using Unity 3.5.6 on mac.
Here is my code:
using (ZipInputStream s = new ZipInputStream(File.OpenRead(a_filePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
Console.WriteLine(theEntry.Name);
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
// create directory
if (directoryName.Length > 0)
{
Debug.Log("Creating Director: " + directoryName);
Directory.CreateDirectory(directoryName);
}
if (fileName != String.Empty)
{
string filename = a_extractPath;
filename += theEntry.Name;
Debug.Log("Unzipping: " + filename);
using (FileStream streamWriter = File.Create(filename))
{
int size = 2048;
byte[] fdata = new byte[2048];
while (true)
{
size = s.Read(fdata, 0, fdata.Length);
if (size > 0)
{
streamWriter.Write(fdata, 0, size);
}
else
{
break;
}
}
}
}
}
}

Resources