Applets Jar cant find resource - java

I've made applet, Here's files from its jar.
In my classes I've call ffmpeg.exe, and I have all privileges like self-signed applet and make call via Access Controller. So I've getting error in program, It's can't be find *my ffmpeg lib*.
This should be very easy Q: where should I place my ffmpeg.exe file ?
And I've get exception as:
Cannot run program "ffmpeg": CreateProcess error=2, ?? ??? ??? ????? ????
The code are following as:
public class DtpVideoApplet extends Applet
{
public String startRecording() throws IOException
{
try
{
return(String) AccessController.doPrivileged(new PrivilegedAction<String>()
{
public String run()
{
try
{
Runtime.getRuntime()
.exec("ffmpeg -y -f dshow -i video=\"screen-capture-recorder\" output.flv");
return "Entered";
}
catch (Exception e)
{
// TODO Auto-generated catch block
return e.getMessage();
}
}
});
}
catch (Exception e)
{
return e.getMessage();
}
}
}

I never run an .exe from an applet, however I'm load some .dlls from an applet resource, to do this first I copy my applet resources to temp path and then I load it from this path. The dlls are located inside the jar how is showed below:
loadLib method copies .dlls to disc and then load it, this method receive as parameters the directory and the name of the file (in my case the method call is loadLib("/sun/security/mscapi/","sunmscapi_x32.dll"); )
public static void loadLib(String libraryPath, String libraryName) throws IOException, InterruptedException{
System.out.println(libraryPath + "---------------------");
URL inputStreamLibURL = AddSunMSCAPIProvider.class.getResource(libraryPath);
if(inputStreamLibURL==null){
throw new IOException("Resource not found: " + libraryPath);
}
String tempPath = System.getProperty("java.io.tmpdir", NOT_FOUND);
if(tempPath.equals(NOT_FOUND)){
throw new IOException("Temporary File not found");
}
File tempDir = new File(tempPath);
//first try to overwrite the default file
File defaultFile = new File(tempPath, libraryName);
boolean useDefaultFile = false;
if(defaultFile.exists()){
try{
useDefaultFile = defaultFile.delete();
//return false if the library cannot be deleted (locked)
}catch(Exception e){
e.printStackTrace();
useDefaultFile = false;
}
}else{
useDefaultFile = true;
}
File tempFile;
if(useDefaultFile){
tempFile = defaultFile;
}else{
tempFile = File.createTempFile(libraryName, "", tempDir);
}
copy(inputStreamLibURL.openStream() ,tempFile, 0);
Runtime.getRuntime().load(tempFile.getAbsolutePath());
}
/**
* File copy
* #param src
* #param dest
* #param bufferSize
* #throws IOException
*/
private static void copy(InputStream src, File dest, int bufferSize) throws IOException{
if(bufferSize<=0){
bufferSize = 2000; //default bytebuffer
}
InputStream is = src;
OutputStream os = new BufferedOutputStream(new FileOutputStream(dest));
byte[] buffer = new byte[bufferSize];
int c;
while((c = is.read(buffer))!= -1){
os.write(buffer, 0, c);
}
is.close();
os.close();
return;
}
Of course in order to do this operations, the applet must be correct signed and necessary MANIFEST permissions added.
Hope this helps,

Related

problem when upload file in play framework

I tried uploading a file, and placed the file in the "public / images" directory and it worked, but the file I uploaded was zero in size and certainly couldn't be opened
public Result upload() throws IOException {
Http.MultipartFormData<File> requestBody = request().body().asMultipartFormData();
Http.MultipartFormData.FilePart<File> profile_pic = requestBody.getFile("profile_pic");
String dirPath = "public/images/";
if(profile_pic != null) {
String name = profile_pic.getFilename();
File file = profile_pic.getFile();
System.out.println(file);
File theDir = new File(dirPath);
if (!theDir.exists()) {
boolean result = false;
try {
theDir.mkdirs();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
try {
File filex = new File(dirPath + name.toLowerCase());
filex.createNewFile();
file.renameTo(filex);
}catch (Exception e) {
// TODO: handle exception
}
return ok("File uploaded ");
}else {
return badRequest("Eroor");
}
}
this is my file after upload
I think creating a new file and renaming your old file to that name may cause trouble. I would recommend using the move method, see docs here.
Does your System.out.println(file); print what looks like a normal png file?

jcifs.smb.SmbException: Access is Denied

I have a requirement where i have to copy a file from my local workspace to a network drive. i have all working credentials to open up the network drive and see, i am using JCIF methods to achieve this but unfortunately when i run the below code am getting the access denied exception
public static void main(String[] args) {
File file = new File("D:\\sampletext.txt");
try {
createCopyOnNetwork("prestige", "sannayalap", "Ci**#***", "D:\\sampletext.txt", "smb://10.28.41.**//d$//CDSBatches//test");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static boolean createCopyOnNetwork(String domain,String username,String password,String src, String dest) throws Exception
{
SmbFileOutputStream out = null;
BufferedInputStream inBuf = null;
try{
NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication(domain,username,password); // replace with actual values
SmbFile file = new SmbFile(dest, authentication); // note the different format
inBuf = new BufferedInputStream(new FileInputStream(src));
out = (SmbFileOutputStream)file.getOutputStream();
byte[] buf = new byte[5242880];
int len;
while ((len = inBuf.read(buf)) > 0){
out.write(buf, 0, len);
}
}
catch(Exception ex)
{
throw ex;
}
finally{
try{
if(inBuf!=null)
inBuf.close();
if(out!=null)
out.close();
}
catch(Exception ex)
{}
}
System.out.print("\n File copied to destination");
return true;
}
when i run this am getting this exception
jcifs.smb.SmbException: Access is denied.
at jcifs.smb.SmbTransport.checkStatus(SmbTransport.java:563)
at jcifs.smb.SmbTransport.send(SmbTransport.java:664)
at jcifs.smb.SmbSession.send(SmbSession.java:238)
at jcifs.smb.SmbTree.send(SmbTree.java:119)
at jcifs.smb.SmbFile.send(SmbFile.java:775)
at jcifs.smb.SmbFile.open0(SmbFile.java:992)
at jcifs.smb.SmbFile.open(SmbFile.java:1009)
at jcifs.smb.SmbFileOutputStream.<init>(SmbFileOutputStream.java:142)
at jcifs.smb.SmbFileOutputStream.<init>(SmbFileOutputStream.java:97)
at jcifs.smb.SmbFileOutputStream.<init>(SmbFileOutputStream.java:67)
at jcifs.smb.SmbFile.getOutputStream(SmbFile.java:2856)
at dev.copyFileRemote.createCopyOnNetwork(copyFileRemote.java:36)
at dev.copyFileRemote.main(copyFileRemote.java:141)
if any one have any idea on how to copy files to network drive then please help in this. also please suggest if you know any other alternative approaches to acheive this.

Writing with an OutputStream to a DocumentFile: data seem to be written but file ends up empty

The application KDE Connect allows remotely browsing an Android device from a desktop computer through SFTP. Since Android 4.4, developers don't have write permission to SD cards directly through the filesystem anymore. So I am trying to port the SFTP module using the Storage Access Framework (DocumentFile, etc.)
I am taking the permission with an Intent.ACTION_OPEN_DOCUMENT_TREE and FLAG_GRANT_WRITE_URI_PERMISSION and passing the context to my classes.
I am able to create new empty files, rename files and delete files on the SD card inside my class so I believe I am getting the necessary permissions. However, transferring a file results in an empty file (0 bytes) being created. I can see the transfer taking a certain time and a progress bar on the desktop side, so it doesn't just abort.
Here is the relevant part of the SftpSubsystem class from the Apache SSHD library (see doc here) with my own comments to explain what's going on:
public class SftpSubsystem implements Command, Runnable, SessionAware, FileSystemAware {
// This method receives a buffer from an InputStream and processes it
// according to its type. In this situation, it would also contain
// a block of the file being transferred (4096 bytes)
protected void process(Buffer buffer) {
int type = buffer.getByte();
switch (type) {
case WRITE:
FileHandle fh = getHandleFromString(buffer.getString());
long offset = buffer.getLong();
byte[] data = buffer.getBytes();
fh.write(data, offset);
break;
// other cases
}
}
// This class is a handle to a file (duh) with
// an OutputStream to write and InputStream to read
protected static class FileHandle {
SshFile file;
OutputStream output;
long outputPos;
InputStream input;
long inputPos;
// Method called inside process()
public void write(byte[] data, long offset) throws IOException {
if (output != null && offset != outputPos) {
IoUtils.closeQuietly(output);
output = null;
}
if (output == null) {
// This is called once at the start of the transfer.
// This is what I think I need to rewrite to make
// it work with DocumentFile objects.
output = file.createOutputStream(offset);
}
output.write(data);
outputPos += data.length;
}
}
}
The original implementation of createOutputStream() that I want to rewrite because RandomAccessFile doesn't work with DocumentFile:
public class NativeSshFile implements SshFile {
private File file;
public OutputStream createOutputStream(final long offset)
throws IOException {
// permission check
if (!isWritable()) {
throw new IOException("No write permission : " + file.getName());
}
// move to the appropriate offset and create output stream
final RandomAccessFile raf = new RandomAccessFile(file, "rw");
try {
raf.setLength(offset);
raf.seek(offset);
// The IBM jre needs to have both the stream and the random access file
// objects closed to actually close the file
return new FileOutputStream(raf.getFD()) {
public void close() throws IOException {
super.close();
raf.close();
}
};
} catch (IOException e) {
raf.close();
throw e;
}
}
}
One of the ways I tried to implement it:
class SimpleSftpServer {
static class AndroidSshFile extends NativeSshFile {
// This is the DocumentFile that is stored after
// create() created the empty file
private DocumentFile docFile;
public OutputStream createOutputStream(final long offset) throws IOException {
// permission check
if (!isWritable()) {
throw new IOException("No write permission : " + docFile.getName());
}
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(docFile.getUri(), "rw");
FileDescriptor fd = pfd.getFileDescriptor();
try {
android.system.Os.lseek(fd, offset, OsConstants.SEEK_SET);
} catch (ErrnoException e) {
Log.e("SimpleSftpServer", "" + e);
return null;
}
return new FileOutputstream(fd, offset);
}
}
}
I also tried a simple (the offset is ignored but it's just a test):
public OutputStream createOutputStream(final long offset) throws IOException {
// permission check
if (!isWritable()) {
throw new IOException("No write permission : " + docFile.getName());
}
return context.getContentResolver().openOutputStream(docFile.getUri());
}
I also tried with a FileChannel and to flush and sync the FileOutputStream.
Any idea why I end up with an empty file?
EDIT: here is a small example of a test I did to just write a new file from an existing file. It works, but this is not what I actually want to do (see code above) but I thought I'd provide an example to show that I understand the basics of how to write to an OutputStream.
private void createDocumentFileFromFile() {
File fileToRead = new File("/storage/0123-4567/lady.m4a");
File fileToWrite = new File("/storage/0123-4567/lady2.m4a");
File dir = fileToWrite.getParentFile();
DocumentFile docDir = DocumentFile.fromTreeUri(context, SimpleSftpServer.externalStorageUri);
try {
DocumentFile createdFile = docDir.createFile(null, fileToWrite.getName());
Uri uriToRead = Uri.fromFile(fileToRead);
InputStream in = context.getContentResolver().openInputStream(uriToRead);
OutputStream out = context.getContentResolver().openOutputStream(createdFile.getUri());
try {
int nbOfBytes = 0;
final int BLOCKSIZE = 4096;
byte[] bytesRead = new byte[BLOCKSIZE];
while (true) {
nbOfBytes = in.read(bytesRead);
if (nbOfBytes == -1) {
break;
}
out.write(bytesRead, 0, nbOfBytes);
}
} finally {
in.close();
out.close();
}
} catch (IOException e) {
}
}
"When using ACTION_OPEN_DOCUMENT_TREE, your app gains access only to the files in the directory that the user selects. You don't have access to other apps' files that reside outside this user-selected directory.
This user-controlled access allows users to choose exactly what content they're comfortable sharing with your app."
This means, you can only read/write/delete the content/meta data of already existing files or in sub directories in the selected directory, the scope that the user accept to be "comfortable" with.
Actually the user granted permmision to a list of Uri's in this folder for ea file/sub directory there is seperate uri permmision.
Now for example if I will try to create new file in the selected Uri using DocumentFile Ill success but if i will try to outputatream new data to this file I will fail because the user did not grant permision to write to this newly created file.
He only granted to write in the directory path level, means create new file here.
So same happens when you try to move/transfer file to other path that does not have permission from the user.
Path can be folder or file and for ea new path the user needs to grant new access.
move file = new path
write to just created file = new path

Can't load sound files LibGdx

I would like to load files directly from expansion OBB file by using AssetManager. I implemented my own FileHandleResolver
public class CustomFileHandleResolver implements FileHandleResolver
{
#Override
public FileHandle resolve(String fileName) {
return new CustomFileHandle(fileName);
}
}
I set it to my AssetManager. I created my own FileHandle and I override read() function
#Override
public InputStream read()
{
InputStream input = null;
try {
input = GameInfo.expansionFile.getInputStream(file.getPath().replace('\\', '/'));
} catch (IOException e) {
e.printStackTrace();
}
return input;
}
It loads all the files like .PNG, .PACK, .FNT, except .OGG files, so I guess that all sound files won't be loaded. I'm getting this error:
com.badlogic.gdx.utils.GdxRuntimeException: com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load dependencies of asset: SFx/button_click.ogg
And this error:
com.badlogic.gdx.utils.GdxRuntimeException: java.lang.ClassCastException: com.solidgamesstudio.threedefendersn.framework.CustomFileHandle cannot be cast to com.badlogic.gdx.backends.android.AndroidFileHandle
I read that zip can not be compressed. In 7zip I selected compression to "Store" so that it's not compressed at all, but still this problem occurs.
I traversed what is happening when files are being loaded and I found that AssetManager calls my CustomFileHandleResolver which creates CustomFileHandle. For every file that is not .OGG it calls InputStream read(). In this function it loads the file from the zip and it's fine. But as I said when it comes to loading .OGG it doesn't call this function. So it's not even trying yet to get the file from the zip. Question is, why .OGG file doesn't call InputStream read() in CustomFileHandle()?
UPDATE
I traversed more and I found out that it won't call InputStream read() because it can't create a Sound from FileHandle somehow. Clue to this is
CustomFileHandle cannot be cast to AndroidFileHandle
While to create a sound you need to pass fileHandle.
public Sound newSound (FileHandle fileHandle);
This is called from SoundLoader
#Override
public void loadAsync (AssetManager manager, String fileName, FileHandle file, SoundParameter parameter) {
sound = Gdx.audio.newSound(file);
}
And that soundLoader uses my CustomFileHandleResolver. I don't know if Sounds are handled differently then other types of files. But by default AssetManager uses
public class InternalFileHandleResolver implements FileHandleResolver {
#Override
public FileHandle resolve (String fileName) {
return Gdx.files.internal(fileName);
}
}
I can't get into Gdx.files.internal to see if there are any special handling for Sounds.
UPDATE
Further analysis give me clue that the main problem is this as mentioned before.
CustomFileHandle cannot be cast to AndroidFileHandle
I don't know why it's casting my FileHandle to AndroidFileHandle while loading OGG file. If it loads fine other type of files, that probably means it doesn't do casting for them. That means that OGG is special and it needs casting. Any clues?
I have not found a way to load sound files from the zip file. Problem is that AssetManager loads sound files differently than other file types. Problem was that it is casting FileHandle to AndroidFileHandle, and since CustomFileHandle extends FileHandle it's impossible to cast it to AndroidFileHandle. I found no way to go around this, because it's deeply rooted.
CustomFileHandle cannot be cast to AndroidFileHandle
In this situation I had to take out all sound files from the OBB file and put them together with the app. I created another instance of AssetManager just for loading sounds. So, sounds are loaded normally as you would with AssetManager and for any other type of file I used AssetManager that uses my own FileHandlerResolver which uses my own FileHandle class that returns a file from the zip. The only problem with this approach is that you are limited to having sounds files only up to 50 MB.
I solved this problem extracting the zip to a specific folder,
and then reading from that external folder.
The extraction of the zip is done by these methods:
public void extract(){
String packageName = getPackageName();
File root = Environment.getExternalStorageDirectory();
File expPath = new File(root.toString() + "/Android/obb/" + packageName);
if (expPath.exists()) {
String strMainPath = null;
try {
strMainPath = expPath + File.separator + "main."
+ getPackageManager().getPackageInfo(
getPackageName(), 0).versionCode + "."
+ packageName + ".obb";
Log.e("Extract File path", "===>"+strMainPath);
File f=new File(strMainPath);
if(f.exists()){
Log.e("Extract From File path", "===> not exist");
}
else
{
Log.e("Extract From File path", "===> exist");
}
String pathToExtract = Environment.getExternalStorageDirectory()+"/"+Cons.FOLDERNAME;
Log.e("Extract to path", "===>"+pathToExtract);
flag = extractZip(strMainPath,pathToExtract);
Log.e("After Extract Zip", "===>"+flag);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
}
private boolean extractZip(String pathOfZip,String pathToExtract)
{
int BUFFER_SIZE = 1024;
int size;
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(pathToExtract);
if(!f.isDirectory()) {
f.mkdirs();
}
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(pathOfZip), BUFFER_SIZE));
fileNum=0;
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = pathToExtract +"/"+ ze.getName();
if (ze.isDirectory()) {
File unzipFile = new File(path);
if(!unzipFile.isDirectory()) {
unzipFile.mkdirs();
}
}
else {
updateFileNum();
FileOutputStream out = new FileOutputStream(path, false);
BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE);
try {
while ( (size = zin.read(buffer, 0, BUFFER_SIZE)) != -1 ) {
fout.write(buffer, 0, size);
}
zin.closeEntry();
}catch (Exception e) {
Log.e("Exception", "Unzip exception 1:" + e.toString());
}
finally {
fout.flush();
fout.close();
}
}
}
}catch (Exception e) {
Log.e("Exception", "Unzip exception2 :" + e.toString());
}
finally {
zin.close();
}
return true;
}
catch (Exception e) {
Log.e("Exception", "Unzip exception :" + e.toString());
}
return false;
}
Note: Extract it to .Android folder, otherwhise users will have direct acces to the assets. For example they will see the images in the Gallery app.
Well, I'm doing this currently. Whenever you need to get a real FileHandle in order for the sound loading mechanism to work (or in any other case were the casting to AndroidFileHandle is bothering you), unzip that file to a local directory and reuse it if needed:
public static FileHandle getRealFileHandle(String zipEntryPath, ZipFile zipFile) {
if (Gdx.files.local(zipEntryPath).exists()) {
return Gdx.files.local(zipEntryPath);
} else {
Gdx.app.log(TAG, "Unzipping file '" + zipEntryPath + "'...");
try {
FileHandle unzippedFile;
ZipEntry entry = zipFile.getEntry(zipEntryPath);
if (entry != null) {
unzippedFile = Gdx.files.local(zipEntryPath);
InputStream is = zipFile.getInputStream(entry);
byte[] buffer = new byte[65536];
int readLength;
while ((readLength = is.read(buffer)) >= 0) {
unzippedFile.writeBytes(buffer, 0, readLength, true);
}
return unzippedFile;
} else {
Gdx.app.error(TAG, "Entry '" + zipEntryPath + "' not found inside zip file.");
}
} catch (IOException ioe) {
Gdx.app.error(TAG, "A problem occurred while writing to the local file.");
}
}
return null;
}

Trying to create a file to save an image Java

I get the following exception when trying to create a file on windows 7 using Java. An example of a path is "C:/g-ecx/images-amazon/com/images/G/01/gno/images/orangeBlue/navPackedSprites-US-22.V183711641.png". If I hard code in a path it does work however. I've been banging my head for two hours, can anyone help.
mkdir fails but doesn't through an exception, create file throws the exception.
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processImage(ImageProcessingBehavior.java:125)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.loadImages(ImageProcessingBehavior.java:99)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processNodes(ImageProcessingBehavior.java:66)
at org.willmanning.mtt.html.processingbehavior.ImageProcessingBehavior.processRootNode(ImageProcessingBehavior.java:34)
at org.willmanning.mtt.html.ParsingFacade.processURL(ParsingFacade.java:38)
at org.willmanning.mtt.App.main(App.java:45)
/**
*
* #param image
* #param url
*/
public void processImage(BufferedImage image, URL url) {
StringBuilder path = new StringBuilder();
path.append("C:/Users/will/Documents/");
path.append(url.getHost().replace('.', '/'));
path.append(url.getFile());
path.replace(path.lastIndexOf("."), path.length(), ".txt");
File file = new File(path.toString());
boolean mkdir = file.mkdir();
boolean isNew = false;
try {
isNew = file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/*
* only create the file if it doesn't exist
*/
if (isNew) {
try {
ImageIO.write(image, "jpg", file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try using
boolean mkdir = file.mkdirs();
instead of
boolean mkdir = file.mkdir();
mkdirs() creates the whole parent path/directories if needed:

Categories