Fortify Unreleased Resource: Streams try with resource in loop - loops

Fortify find "Unreleased Resource: Streams" error for my script that I've already use try with resource :
public static void zipFiles(List<FileZipObject> fileList, File outFile) throws IOException {
try (FileOutputStream fileOutputStream = new FileOutputStream(outFile);
ZipOutputStream zipOut = new ZipOutputStream(fileOutputStream)) {
for (FileZipObject fileZipObject : fileList) {
try (FileInputStream fis = new FileInputStream(fileZipObject.getFilePath())) { // <------ This line
ZipEntry zipEntry = new ZipEntry(genEntryName(fileZipObject.getFileName()));
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
}
}
}
}
Please help me to fix this problem

public static void zipFiles(List<FileZipObject> fileList, File outFile) throws IOException {
FileOutputStream fileOutputStream = null;
ZipOutputStream zipOut = null;
try {
fileOutputStream = new FileOutputStream(outFile);
zipOut = new ZipOutputStream(fileOutputStream);
for (FileZipObject fileZipObject : fileList) {
FileInputStream fis = null;
try {
fis = new FileInputStream(fileZipObject.getFilePath());
ZipEntry zipEntry = new ZipEntry(genEntryName(fileZipObject.getFileName()));
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
} finally {
if (fis != null) {
fis.close();
}
}
}
} finally {
if (zipOut != null) {
zipOut.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
}

Related

Share a TXT file between two android application Android 11 and Android 12

I developed two application, one is a LAUNCHER the other one is the MAIN-APP.
I my MAIN-APP the user can choose the language.
I would like to change automatically the language also in my LAUNCHER.
I would like to create a txt file in Documents folder from my MAIN-APP, so the LAUNCHER can read this file and set the same language.
But now in Android 11 seems impossible to create a file TXT in the Documents folder and read this file from another application.
I tried with MediaStore:
MAIN APP :
private static void saveLanguageOnFile(String lang, String country){
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
File folderDocuments = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
boolean success;
if (!folderDocuments.exists()) {
try {
folderDocuments.mkdir();
} catch (Exception ex) {
ex.printStackTrace();
}
}
success = folderDocuments.exists();
if (success) {
try {
FileOutputStream fos = new FileOutputStream(new File(folderDocuments, "language.txt"));
fos.write((lang + "-" + country).getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Uri contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
ContentResolver contentResolver = ActivitiesManager.getInstance().getTopActivity().getApplication().getApplicationContext().getContentResolver();
String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?";
String[] selectionArgs = new String[]{Environment.DIRECTORY_DOCUMENTS+"/"};
Cursor cursor = contentResolver.query(contentUri, null, selection, selectionArgs, null);
long idFile = -1;
if (cursor != null && cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
int columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
if (columnIndexDisplayName > 0 && columnIndexId > 0) {
String fileName = cursor.getString(columnIndexDisplayName);
if (fileName.equals("language.txt")) {
idFile = cursor.getLong(columnIndexId);
break;
}
}
}
cursor.close();
}
Uri uriFile;
if (idFile > -1) {
uriFile = ContentUris.withAppendedId(contentUri, idFile);
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "language.txt"); // file name
values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS);
uriFile = contentResolver.insert(contentUri, values);
}
try {
if (uriFile != null) {
OutputStream outputStream = contentResolver.openOutputStream(uriFile, "rwt");
if (outputStream != null) {
outputStream.write((lang + "-" + country).getBytes());
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
ANDROID LAUNCHER APP :
private fun setLanguage() {
var lang = Locale.getDefault().language
var country = Locale.getDefault().country
val previousLang = lang
val previousCountry = country
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
val language = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),"language.txt")
if (language.exists()) {
try {
val br = BufferedReader(FileReader(language))
var st: StringTokenizer
var line: String?
while (br.readLine().also { line = it } != null) {
st = StringTokenizer(line, "-")
lang = st.nextToken()
country = st.nextToken()
}
br.close()
} catch (e: IOException) {
Log.e("LauncherDMD", ".loadFile: err: " + e.message)
}
}
} else {
val contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val contentResolver: ContentResolver = application.applicationContext.contentResolver
val selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?"
val selectionArgs = arrayOf(Environment.DIRECTORY_DOCUMENTS+"/")
val orderBy = MediaStore.MediaColumns.DATE_ADDED + " DESC"
val cursor = contentResolver.query(contentUri, null, selection, selectionArgs, orderBy)
var idFile: Long = -1
if (cursor != null && cursor.count > 0) {
while (cursor.moveToNext()) {
val columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
val columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
if (columnIndexDisplayName > 0 && columnIndexId > 0) {
val fileName = cursor.getString(columnIndexDisplayName)
if (fileName.contains("language")) {
idFile = cursor.getLong(columnIndexId)
break
}
}
}
cursor.close()
}
val uriFile: Uri
if (idFile > -1) {
uriFile = ContentUris.withAppendedId(contentUri, idFile)
try {
val br = BufferedReader(InputStreamReader(getContentResolver().openInputStream(uriFile), "UTF-8"))
var st: StringTokenizer
var line: String?
while (br.readLine().also { line = it } != null) {
st = StringTokenizer(line, "-")
lang = st.nextToken()
country = st.nextToken()
}
br.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
}
val locale = Locale(lang,country)
Lingver.getInstance().setLocale(this.applicationContext, locale)
if(!previousCountry.equals(country) && !previousLang.equals(lang)){
recreate()
}
Log.i("LauncherDMD", "Utility: Nuova lingua impostata: $lang")
Log.i("LauncherDMD", "Utility: Nuova nazione impostata: $country")
}
This solution works BUT the problem is that every time the MAIN-APP is uninstalled and installed again (sometimes it happens), it cannot access to the language file previously created by itself and instead it create a duplicate.
I obviously I cannot delete the old language file before creating new ones.
I also know that I cannot use the special permission "MANAGE_EXTERNAL_STORAGE" because I have to publish the app on the play store.
Thanks in advance!

Is there any way to pass Observable<String> into AbstractInputStreamContent?

I'm working on uploading a text file to Google Drive
ByteArrayContent content = new ByteArrayContent("text/csv", fileContent.getBytes(Charset.forName("UTF-8")));
Drive.Files.Insert request = drive.files().insert(file, content);
where type(fileContent) = String
I'd like to refactor and change type of fileContent to Observable<String>, is there any nice workaround to pass it to that insert() function (which takes AbstractInputStreamContent as a second argument)?
Thanks
Here is a general Flowable -> InputStream bridge you can delegate to:
import java.io.*;
import java.nio.charset.Charset;
import java.util.concurrent.atomic.AtomicReference;
import org.reactivestreams.*;
import io.reactivex.FlowableSubscriber;
import io.reactivex.internal.subscriptions.SubscriptionHelper;
public final class FlowableStringInputStream {
private FlowableStringInputStream() {
throw new IllegalStateException("No instances!");
}
public static InputStream createInputStream(
Publisher<String> source, Charset charset) {
StringInputStream parent = new StringInputStream(charset);
source.subscribe(parent);
return parent;
}
static final class StringInputStream extends InputStream
implements FlowableSubscriber<String> {
final AtomicReference<Subscription> upstream;
final Charset charset;
volatile byte[] bytes;
int index;
volatile boolean done;
Throwable error;
StringInputStream(Charset charset) {
this.charset = charset;
upstream = new AtomicReference<>();
}
#Override
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.setOnce(upstream, s)) {
s.request(1);
}
}
#Override
public void onNext(String t) {
bytes = t.getBytes(charset);
synchronized (this) {
notifyAll();
}
}
#Override
public void onError(Throwable t) {
error = t;
done = true;
synchronized (this) {
notifyAll();
}
}
#Override
public void onComplete() {
done = true;
synchronized (this) {
notifyAll();
}
}
#Override
public int read() throws IOException {
for (;;) {
byte[] a = awaitBufferIfNecessary();
if (a == null) {
Throwable ex = error;
if (ex != null) {
if (ex instanceof IOException) {
throw (IOException)ex;
}
throw new IOException(ex);
}
return -1;
}
int idx = index;
if (idx == a.length) {
index = 0;
bytes = null;
upstream.get().request(1);
} else {
int result = a[idx] & 0xFF;
index = idx + 1;
return result;
}
}
}
byte[] awaitBufferIfNecessary() throws IOException {
byte[] a = bytes;
if (a == null) {
synchronized (this) {
for (;;) {
boolean d = done;
a = bytes;
if (a != null) {
break;
}
if (d || upstream.get() == SubscriptionHelper.CANCELLED) {
break;
}
try {
wait();
} catch (InterruptedException ex) {
if (upstream.get() != SubscriptionHelper.CANCELLED) {
InterruptedIOException exc = new InterruptedIOException();
exc.initCause(ex);
throw exc;
}
break;
}
}
}
}
return a;
}
#Override
public int read(byte[] b, int off, int len) throws IOException {
if (off < 0 || len < 0 || off >= b.length || off + len > b.length) {
throw new IndexOutOfBoundsException(
"b.length=" + b.length + ", off=" + off + ", len=" + len);
}
for (;;) {
byte[] a = awaitBufferIfNecessary();
if (a == null) {
Throwable ex = error;
if (ex != null) {
if (ex instanceof IOException) {
throw (IOException)ex;
}
throw new IOException(ex);
}
return -1;
}
int idx = index;
if (idx == a.length) {
index = 0;
bytes = null;
upstream.get().request(1);
} else {
int r = 0;
while (idx < a.length && len > 0) {
b[off] = a[idx];
idx++;
off++;
r++;
len--;
}
index = idx;
return r;
}
}
}
#Override
public int available() throws IOException {
byte[] a = bytes;
int idx = index;
return a != null ? Math.max(0, a.length - idx) : 0;
}
#Override
public void close() throws IOException {
SubscriptionHelper.cancel(upstream);
synchronized (this) {
notifyAll();
}
}
}
}
Usage:
#Test(timeout = 10000)
public void async() throws Exception {
AtomicInteger calls = new AtomicInteger();
Flowable<String> f = Flowable.range(100, 10).map(Object::toString)
.doOnCancel(() -> calls.incrementAndGet())
.subscribeOn(Schedulers.computation())
.delay(10, TimeUnit.MILLISECONDS);
try (InputStream is = FlowableStringInputStream.createInputStream(f, utf8)) {
assertEquals('1', is.read());
assertEquals('0', is.read());
assertEquals('0', is.read());
byte[] buf = new byte[3];
assertEquals(3, is.read(buf));
assertArrayEquals("101".getBytes(utf8), buf);
}
assertEquals(1, calls.get());
}

LZH in Byte Array Decompress in .NET?

An LZH archive is embedded within a file. The file was read into a byte[], and the LZH part is identified as a smaller byte[].
How can the embedded LZH bytes be decompressed into another byte[] using .NET Framework 4.6 (C#)? I have only see http://www.infoq.com/news/2008/06/7-Zip-from-.NET which doesn't exactly do what I need.
Thanks.
the code snippet that follows is taken from the sample program from this article
http://www.codeproject.com/Articles/27148/C-NET-Interface-for-Zip-Archive-DLLs
There are no significant changes: instead of reading and writing files, it reads and write byte arrays. Changes are marked by comments
Run with sevenzip.exe e "C:\temp\gwo0.11-sample-win32.lzh" 3 for example
https://dl.dropboxusercontent.com/u/71459360/7z.zip
using System;
using System.Collections.Generic;
using System.Text;
using Nomad.Archive.SevenZip;
using System.IO;
using System.Runtime.InteropServices;
using System.Reflection;
namespace SevenZip
{
class Program
{
private static void ShowHelp()
{
Console.WriteLine("SevenZip");
Console.WriteLine("SevenZip l {ArchiveName}");
Console.WriteLine("SevenZip e {ArchiveName} {FileNumber}");
}
static void Main(string[] args)
{
if (args.Length < 2)
{
ShowHelp();
return;
}
try
{
string ArchiveName;
uint FileNumber = 0xFFFFFFFF;
bool Extract;
switch (args[0])
{
case "l":
ArchiveName = args[1];
Extract = false;
break;
case "e":
ArchiveName = args[1];
Extract = true;
if ((args.Length < 3) || !uint.TryParse(args[2], out FileNumber))
{
ShowHelp();
return;
}
break;
default:
ShowHelp();
return;
}
using (SevenZipFormat Format = new SevenZipFormat(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "7z.dll")))
{
IInArchive Archive = Format.CreateInArchive(SevenZipFormat.GetClassIdFromKnownFormat(KnownSevenZipFormat.Lzh));
if (Archive == null)
{
ShowHelp();
return;
}
try
{
//the byte array is provided by you. here it's coming from a file
byte[] data;
using (var stream = File.OpenRead(ArchiveName))
{
data = new byte[stream.Length];
stream.Read(data, 0, data.Length);
}
using (InStreamWrapper ArchiveStream = new InStreamWrapper(new MemoryStream(data))) //modified here
{
ulong CheckPos = 32 * 1024;
if (Archive.Open(ArchiveStream, ref CheckPos, null) != 0)
ShowHelp();
Console.Write("Archive: ");
Console.WriteLine(ArchiveName);
if (Extract)
{
PropVariant Name = new PropVariant();
Archive.GetProperty(FileNumber, ItemPropId.kpidPath, ref Name);
string FileName = (string) Name.GetObject();
Console.Write("Extracting: ");
Console.Write(FileName);
Console.Write(' ');
MemoryStream ms = new MemoryStream();
Archive.Extract(new uint[] { FileNumber }, 1, 0, new ArchiveMemoryCallback(FileNumber, ms)); //modified here
byte[] output = ms.ToArray(); //here you have the output byte array
output.ToString();
}
else
{
Console.WriteLine("List:");
uint Count = Archive.GetNumberOfItems();
for (uint I = 0; I < Count; I++)
{
PropVariant Name = new PropVariant();
Archive.GetProperty(I, ItemPropId.kpidPath, ref Name);
Console.Write(I);
Console.Write(' ');
Console.WriteLine(Name.GetObject());
}
}
}
}
finally
{
Marshal.ReleaseComObject(Archive);
}
}
}
catch (Exception e)
{
Console.Write("Error: ");
Console.WriteLine(e.Message);
}
}
}
class ArchiveCallback : IArchiveExtractCallback
{
private uint FileNumber;
private string FileName;
private OutStreamWrapper FileStream;
public ArchiveCallback(uint fileNumber, string fileName)
{
this.FileNumber = fileNumber;
this.FileName = fileName;
}
#region IArchiveExtractCallback Members
public void SetTotal(ulong total)
{
}
public void SetCompleted(ref ulong completeValue)
{
}
public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
{
if ((index == FileNumber) && (askExtractMode == AskMode.kExtract))
{
string FileDir = Path.GetDirectoryName(FileName);
if (!string.IsNullOrEmpty(FileDir))
Directory.CreateDirectory(FileDir);
FileStream = new OutStreamWrapper(File.Create(FileName));
outStream = FileStream;
}
else
outStream = null;
return 0;
}
public void PrepareOperation(AskMode askExtractMode)
{
}
public void SetOperationResult(OperationResult resultEOperationResult)
{
FileStream.Dispose();
Console.WriteLine(resultEOperationResult);
}
#endregion
}
//new
class ArchiveMemoryCallback : IArchiveExtractCallback
{
private uint FileNumber;
private Stream stream;
private OutStreamWrapper FileStream;
public ArchiveMemoryCallback(uint fileNumber, Stream stream)
{
this.FileNumber = fileNumber;
this.stream = stream;
}
#region IArchiveExtractCallback Members
public void SetTotal(ulong total)
{
}
public void SetCompleted(ref ulong completeValue)
{
}
public int GetStream(uint index, out ISequentialOutStream outStream, AskMode askExtractMode)
{
if ((index == FileNumber) && (askExtractMode == AskMode.kExtract))
{
FileStream = new OutStreamWrapper(stream);
outStream = FileStream;
}
else
outStream = null;
return 0;
}
public void PrepareOperation(AskMode askExtractMode)
{
}
public void SetOperationResult(OperationResult resultEOperationResult)
{
FileStream.Dispose();
Console.WriteLine(resultEOperationResult);
}
#endregion
}
}

getting an empty file when downloading : jsf

I want to download a file stored in system directory but when downloading the file in jsf page I get it empty.
This is my xhtml page :
<h:form>
<h:commandButton value="Download" action="#{helloBean.downloadFile}" />
</h:form>
and my managed bean :
#ManagedBean
#SessionScoped
public class HelloBean {
public void downloadFile() {
File file = new File("C:\\data\\contacts.doc");
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setHeader("Content-Disposition", "attachment;filename=contacts.doc");
response.setContentLength((int) file.length());
ServletOutputStream out = null;
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
out = response.getOutputStream();
int i = 0;
while ((i = input.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
FacesContext.getCurrentInstance().getResponseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
}
}
so How to solve it? Thanks in advance.
I think this code solve your problem.
public void download() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context
.getExternalContext().getResponse();
File file = new File(filePath);
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType("application/octet-stream");
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "attachment;filename=\""
+ file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file),
DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(),
DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
input.close();
output.close();
}
context.responseComplete();
}

How to save image into photo gallery of samsung,Lg,Nokia mobiles using j2me [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to save an image into photo gallery using j2me
I am working on an application in which i want to download an image from internet and save it to photo gallery of every mobile. Please provide me suggestion.
Thanks,
private void downloadImage(String folder, String photoName, String url) throws IOException
{
byte[] rawImg = null;
try
{
String imageData = getDataFromUrl(url);
rawImg = imageData.getBytes();
putPhotoToPhone(rawImg, folder, photoName);
}
catch(Exception e1) {
e1.printStackTrace();
}
}
private String getDataFromUrl(String url) throws IOException {
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
long len = 0 ;
int ch = 0;
c = (HttpConnection)Connector.open(url);
is = c.openInputStream();
len = c.getLength();
if( len != -1)
{
for(int i =0 ; i < len ; i++ )
{
if((ch = is.read()) != -1)
{
b.append((char) ch);
}
}
}
else
{
while ((ch = is.read()) != -1)
{
len = is.available() ;
b.append((char)ch);
}
}
is.close();
c.close();
return b.toString();
}
private void putPhotoToPhone(byte[] rawImg, String photoDir, String imageName)
{
FileConnection fcDir, fcFile;
String pRoot = "Phone:/";
OutputStream os;
if (rawImg != null)
{
try
{
fcDir = (FileConnection) Connector.open("file:///"+pRoot+photoDir+"/", Connector.READ_WRITE);
if (!fcDir.exists())
fcDir.mkdir();
fcFile = (FileConnection) Connector.open("file:///"+pRoot+photoDir+"/"+imageName, Connector.READ_WRITE);
if (fcFile.exists())
fcFile.delete();
fcFile.create();
os = fcFile.openOutputStream();
os.write(rawImg);
os.flush();
os.close();
fcFile.close();
fcDir.close();
}
catch (Exception e) {}
}
}

Resources