how to get resource in a jar file ? (poi && image) - jar

I am using Poi Apache to generate an excel file, I have to add a picture to my file but the problems is when I export my project to a Runnable Jar, it is not working.
InputStream is = ExcelTools.class.getClassLoader().getResourceAsStream( "./ensao/pfa/opendelib/resources/LogoOpen.jpg" );
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
is.close();
Drawing drawing = sheet.createDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor(40, 10, 65, 20,
(short) 0, 0, (short) 0, 0);
anchor.setAnchorType(1);
Picture pict = drawing.createPicture(anchor, pictureIdx);
pict.resize();
the problem is launched from this line :
byte[] bytes = IOUtils.toByteArray(is);

Problem in bad path to image. Your IDE configured environment ($CLASSPATH, file path, etc) in one manner, but real running operate other environment. For find your working directory do print debug pwd analog.
This links may be useful:
http://www.java-forums.org/new-java/434-how-can-i-get-current-directory.html
http://www.mkyong.com/java/how-to-get-the-current-working-directory-in-java/
Getting the Current Working Directory in Java

Related

Spanned archives with more than 65534 segments are not supported at this time

Our current implementation on our ASP.net website doesn't support Zip64 which it needs to, so we're moving from System.IO.Compression over to DotNetZip:
https://github.com/DinoChiesa/DotNetZip
This small archive:
https://github.com/DinoChiesa/DotNetZip/files/10184907/Zip.zip
Throws the error:
Spanned archives with more than 65534 segments are not supported at this time.
The code sample simply attempts to open the Zip file:
using (var data = new MemoryStream(fileBytes.ToArray()))
{
using (var archive = Ionic.Zip.ZipFile.Read(data))
{
....
}
I'm a little unsure what the issue is here, is there an easy workaround or is there a better altnerative library?
You need to understand what does mean to have spanned zip file. That means that a zip is split into more files.
The file you have linked appears not to be such file:
Archive: Zip.zip
There is no zipfile comment.
End-of-central-directory record:
-------------------------------
Zip archive file size: 646370 (000000000009DCE2h)
Actual end-cent-dir record offset: 646272 (000000000009DC80h)
Expected end-cent-dir record offset: 646272 (000000000009DC80h)
(based on the length of the central directory and its expected offset)
This zipfile constitutes the sole disk of a single-part archive; its
central directory contains 25 entries.
The central directory is 3521 (0000000000000DC1h) bytes long,
and its (expected) offset in bytes from the beginning of the zipfile
is 642751 (000000000009CEBFh).
...
I think the problem is how you try to read the file with fileBytes.ToArray(). The data variable should be a filename and not fileBytes.ToArray().
If you look at the provided example, on how to read zip file, from the git you can see that on line 53 you get ZipFile zip = ZipFile.Read(args[0], options), where args[0] is a zip filename.
Here is the complete example form the git:
/ ReadZip.cs
//
// ----------------------------------------------------------------------
// Copyright (c) 2006-2009 Microsoft Corporation. All rights reserved.
//
// This example is released under the Microsoft Public License .
// See the license.txt file accompanying this release for
// full details.
//
// ----------------------------------------------------------------------
//
// This simple example utility simply reads a zip archive and extracts
// all elements in it, to the specified target directory.
//
// compile with:
// csc /target:exe /r:Ionic.Zip.dll /out:ReadZip.exe ReadZip.cs
//
// Wed, 29 Mar 2006 14:36
//
using System;
using Ionic.Zip;
namespace Ionic.Zip.Examples
{
public class ReadZip
{
private static void Usage()
{
Console.WriteLine("usage:\n ReadZip2 <zipfile> <unpackdirectory>");
Environment.Exit(1);
}
public static void Main(String[] args)
{
if (args.Length != 2) Usage();
if (!System.IO.File.Exists(args[0]))
{
Console.WriteLine("That zip file does not exist!\n");
Usage();
}
try
{
// Specifying Console.Out here causes diagnostic msgs to be sent to the Console
// In a WinForms or WPF or Web app, you could specify nothing, or an alternate
// TextWriter to capture diagnostic messages.
var options = new ReadOptions { StatusMessageWriter = System.Console.Out };
using (ZipFile zip = ZipFile.Read(args[0], options))
{
// This call to ExtractAll() assumes:
// - none of the entries are password-protected.
// - want to extract all entries to current working directory
// - none of the files in the zip already exist in the directory;
// if they do, the method will throw.
zip.ExtractAll(args[1]);
}
}
catch (System.Exception ex1)
{
System.Console.Error.WriteLine("exception: " + ex1);
}
}
}
}
EDIT - the above posted zip file still generates the above error. I have checked the source to find out where is the culprit:
It thinks it is a spanned archive based on this read. It tries to read a 2 bytes (that are converted to 16-bit unsigned integer ) from the block starting at 2nd position. If the converted value is ==0xFFFF then it considers the file as spanning file with more than 65534 segments. Probably there is some bug in the packing of the zip file which makes the DotNetZip fail.
There is the SharpZipLib nuget package you can use as an alternative.
The code below runs successfully with input the file you posted
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
string filename = "../../../Zip.zip";
FileStream fs = File.OpenRead(filename);
ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ICSharpCode.SharpZipLib.Zip.ZipFile(fs);
foreach (ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry in zf)
{
string entryFileName = zipEntry.Name;
Console.WriteLine("File: " + entryFileName);
}
}
Output
Hello, World!
File: scripts/c3runtime.js
File: data.json
File: style.css
File: scripts/offlineclient.js
File: images/shared-0-sheet1.png
File: images/tiledbackground-sheet0.png
File: images/shared-0-sheet0.png
File: appmanifest.json
File: scripts/main.js
File: workermain.js
File: scripts/dispatchworker.js
File: scripts/jobworker.js
File: scripts/supportcheck.js
File: icons/icon-16.png
File: icons/icon-32.png
File: icons/icon-128.png
File: icons/icon-256.png
File: icons/icon-64.png
File: icons/icon-512.png
File: icons/loading-logo.png
File: index.html
File: arcade.json
File: scripts/register-sw.js
File: sw.js
File: offline.json
P.S. I have worked with both libraries in the past and I have found that DotNetZip is easier to work with, but for this case only SharpZipLib works :).

How to authorize or delerate JAAS security context with native libs (SSPI or MIT or Heimdal)

I need to perform authorization or rights delegation within Active Directory on a chain JAAS (Java) -> Native APP with ODBC (C++) -> MS SQL Server. Any variant will do:
check if the user is valid and find out who it is;
delegate the users rights and access MSDB through ODBC.
Initially I receive a ticket created with this code:
Oid KERB_V5_OID = new Oid("1.2.840.113554.1.2.2");
Oid KRB5_PRINCIPAL_NAME_OID = new Oid("1.2.840.113554.1.2.2.1");
KerberosPrincipal kerberosPrincipal;
GSSManager gssManager = GSSManager.getInstance();
String remoteSpnName = this.url + "#" + kerberosPrincipal.getRealm();
String localSpnName = kerberosPrincipal.getName();
GSSName remoteGssName = gssManager.createName (remoteSpnName, KRB5_PRINCIPAL_NAME_OID);
GSSName localGssName = gssManager.createName (localSpnName, KRB5_PRINCIPAL_NAME_OID);
GSSCredential localCreds = gssManager.createCredential(localGssName, 0, KERB_V5_OID, 1);
GSSContext gssContext = gssManager.createContext (remoteGssName, KERB_V5_OID, localCreds, 0);
gssContext.requestMutualAuth(false);
gssContext.requestConf(false);
gssContext.requestInteg(false);
byte[] ticket = gssContext.initSecContext(new byte[0], 0, 0);
It looks like I should use SSPI because I'm working on MS platform but I failed accepting the ticket. It seems that SSPI and JAAS use different formats.
Also I tried MIT library because of its open soure nature, so I can always look inside its code. Accepting the ticket with gss_accept_security_context gives me "unknown error FF 161".
I feel like I'm executing wrong call sequence trying to accept it.
All help appreciated. Thank you.

React Native [Android] URI from Google Drive w/ 'React-Native-Document-Picker' & 'react-native-get-real-path'

React Native [Android]
Samsung Phone
Libraries :
react-native-document-picker [ returns our URI]
react-native-get-real-path [ converts URI to real path]
Able to :
Get a URI from local files and get real path including images
Able to get URI from Google Drive when I select a file
Unable :
Convert Google Drive URI to real path
DocumentPicker.show({filetype: [DocumentPickerUtil.allFiles()],},(error,res) => {
RNGRP.getRealPathFromURI(path).then(function(androidPath){
console.log('AndroidPath : ', androidPath);
})
}
my URI from google drive is like so :
content://com.google.android.apps.docs.storage/document/acc%3D2%3Bdoc%3D1
Fixed bug to get absolute path of Google Drive File.
So it turns out that we cannot directly get the absolute path from the URI that has been returned by selecting Google Drive File. Hence we need to apply some sort of hack to solve the problem.
What I did was, I forked the react-native-get-real-path repo into our own and then changed few things in GRP.java file.
I basically created InputStream from obtained google drive file's URI and then, using that stream, copied the file into the app's cache directory and returned the absolute path to that file and voila.
Here is the code snippet for the solution:
input = context.getContentResolver().openInputStream(uri);
/* save stream to temp file */
/* displayName is obtained from the URI */
File file = new File(context.getCacheDir(), displayName);
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4 * 1024]; // or other buffer size
int read;
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
final String outputPath = file.getAbsolutePath();
return outputPath;
You can clone the git repository. Reference of https://github.com/Wraptime/react-native-get-real-path/pull/8.

X509Certificate2 constructor issues

I have a pfx file. When I use the file stream to read this pfx file.
When I create the X509Certificate2 with just giving the raw bytes, it works.
But when I try to create the X509Certificate2 with the password and the flags I get an exception saying "The specified network password is incorrect".
The second X509Certificate2 construction fails with the exception : "The specified network password is incorrect" though the password is correct.
using (FileStream stream = new FileStream(#"D:\MyKey.pfx", FileMode.Open))
{
int length = (int)stream.Length;
byte[] certBytes = new byte[length];
stream.Read(certBytes, 0, length);
X509Certificate2 finalCert0 = new X509Certificate2(certBytes);
X509Certificate2 finalCert1 = new X509Certificate2(certBytes, "venki", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
}
Just had the same experience, I deleted the certificate file and re-copied the file over and it worked. I restored the old file and it failed in the same way. Comparing the files revealed the files were drastically different, some how the file had been corrupted.

openWithDefaultApplication fails on files in application folder

I'll ONLY recieve an "Error #3000: Illegal path name" if I try to open a file which is placed inside the app-folder of the air. If the file is somewhere else outside of the app-folder it works.
private var file:File = File.documentsDirectory;
public function download():void{
var pdfFilter:FileFilter = new FileFilter("PDF Files", "*.pdf");
file.browseForOpen("Open", [pdfFilter]);
file.addEventListener(Event.SELECT, fileSelected);
}
private function fileSelected(e:Event):void
{
var destination:File = File.applicationDirectory
destination = destination.resolvePath("test.pdf");
/*
//This works, also if the file to copy is placed inside the appfolder
file.copyTo(destination, true);
*/
/*This Throws me an Error #3000, but ONLY if the file is located in
the App folder*/
file.openWithDefaultApplication();
}
When i try to get the same file and copy it to another place it's doing fine.
Why that? Something special to do if i wanna open files which are inside the appfolder?
It also don't work in debug mode - bin-debug.
Regards, Temo
After reading the document a few times i saw that this is not possible (it's not a bug, it's a feature!?!)
Opening files with the default system application
You cannot use the openWithDefaultApplication() method with files located in the application directory.
So I do this instead:
file.copyTo(tempFile);
tempFile.openWithDefaultApplication();
Not so nice, but it works.

Resources