SmbFileInputStream causing SmbException: SMB URL Syntax? - java

I am trying to create an SmbFileInputStream leading to a directory that does exist on my system. I am using the following code. Every time, I receive an error in the third try-catch that reveals to me the stacktrace below. I believe the error is in the formatting of the SMB URL. If anyone could help point out where I may have erred in the configuration of my domain, server, and user info, or how to escape the special characters below, I would be extremely grateful.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import jcifs.smb.*;
import jcifs.*;
public class jcifsX {
public static void main (String[] args){
System.err.println("*********************************************************** loadWorkbookOrFail was ran");
// create a new file input stream with the input file specified by fileName
jcifs.Config.registerSmbURLHandler();
NtlmPasswordAuthentication npa = null;
try{
npa = new NtlmPasswordAuthentication("myDomain","myUser","myPass");
System.err.println("*********************************************************** NtlmPasswordAuthentication created successfully");
} catch (Exception e) {
System.err.println("*********************************************************** Failed to create NtlmPasswordAuthentication. Stack trace to follow");
e.printStackTrace();
}
SmbFile smbf = null;
try{
smbf = new SmbFile("smb:" + "//myDomain;myUser:myPass#myServer/myShare/" + args, npa);
System.err.println("*********************************************************** SmbFile successfully created");
}
catch (Exception e) {
System.err.println("*********************************************************** Stack trace to follow");
e.printStackTrace();
}
SmbFileInputStream sfin = null;
try{
sfin = new SmbFileInputStream(smbf);
System.err.println("*********************************************************** SmbFileInputStream successfully initiated");
throw new IllegalArgumentException("If you're seeing this, it looks like it worked");
}
catch (Exception e){
System.err.println("*********************************************************** SmbFileInputStream failed: Stack trace to follow. args = " + args);
e.printStackTrace();
}
}
}
The stacktrace I receive upon running this looks like
jcifs.smb.SmbException: The system cannot find the file specified.
at jcifs.smb.SmbTransport.checkStatus(SmbTransport.java:563)
at jcifs.smb.SmbTransport.send(SmbTransport.java:663)
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:989)
at jcifs.smb.SmbFile.open(SmbFile.java:1006)
at jcifs.smb.SmbFileInputStream.<init>(SmbFileInputStream.java:73)
at jcifs.smb.SmbFileInputStream.<init>(SmbFileInputStream.java:65)
at jcifsX.main(jcifsX.java:61)
Thank you in advance to anyone willing to spend any time devoted to this problem. It is greatly appreciated.

You used "smb:" + "//myDomain;myUser:myPass#myServer/myShare/" + args. This will produce string like this smb://myDomain;myUser:myPass#myServer/myShare/[Ljava.lang.String;#470ae2bf.
So use like this "smb:" + "//myDomain;myUser:myPass#myServer/myShare/" + args[0]. Instead of 0 use the proper index.

Related

Java, seemingly randomly, started crashing on FileHandle.class.getResourceAsStream(path);

So, I'm working on a program that allows you to import animations in the form of JSON files into Minecraft, and, when working on a completely different part of the program, my import code stopped working.
I'm using eclipse, and this is how my import code looks:
package com.github.sam54123.mc_animation.utils;
import java.io.InputStream;
public class FileHandle
{
public static InputStream inputStreamFromFile(String path)
{
try
{
InputStream inputStream = FileHandle.class.getResourceAsStream(path);
return inputStream;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
new file
package com.github.sam54123.mc_animation.utils;
import java.io.File;
import java.io.InputStream;
import java.util.Scanner;
import org.json.JSONObject;
public class JSONUtils
{
public static String getJSONStringFromFile(String path)
{
// Open file
Scanner scanner;
try
{
InputStream in = FileHandle.inputStreamFromFile(path);
scanner = new Scanner(in);
// Get JSON as string without spaces or newlines
String json = scanner.useDelimiter("\\Z").next();
// Close file
scanner.close();
return json;
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
return null;
}
}
public static JSONObject getJSONObjectFromFile(String path)
{
File file = new File(path);
if (!file.exists())
{
System.out.println("Invalid Path");
return null;
}
String string = getJSONStringFromFile(path);
return new JSONObject(string);
}
}
And I proceed to do some more fancy pampering of the file later on. This used to work reliably, until I made this in a completely different and un-related class:
String command = getCommand(object);
if (command != null && command.length() > 0)
{
commands.add(new AnimCommand(command, i));
}
And then it started throwing this error:
[Ljava.lang.StackTraceElement;#7852e922
Exception in thread "main" java.lang.NullPointerException
at java.io.StringReader.<init>(Unknown Source)
at org.json.JSONTokener.<init>(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:406)
at com.github.sam54123.mc_animation.utils.JSONUtils.getJSONObjectFromFile(JSONUtils.java:47)
at com.github.sam54123.mc_animation.system.Animation.<init>(Animation.java:20)
at com.github.sam54123.mc_animation.testing.Tester.main(Tester.java:13)
I've double checked that the file hasn't changed, and I tried deleting that section of code, restarting Eclipse, the whole deal, and nothing seems to fix it. The code is even able to recognize that the file is valid using the File class, but nothing seems to change. Does anyone have some insight on how this might be fixed? Here is the rest of my code: https://github.com/Sam54123/mc-animation/
EDIT
Okay, I've just done some more debugging, and it looks like it's the
return new JSONObject(string);
on line 47 of the second file that's crashing. No idea why, as the risky stuff of reading a file off disk is okay.
EDIT 2
It looks looks like it's failing because
InputStream in = FileHandle.inputStreamFromFile(path);
is returning null, which makes sense because of the try catch statement
InputStream inputStream = FileHandle.class.getResourceAsStream(path);
is in. Why that's failing beats me though, because the validity of the file is verified elsewhere in the code. It also used to work, and I haven't changed anything about the layout of the files.
EDIT 3
Interesting, a couple System.out.printlns reveal the catch is not actually getting activated, and therefore getResourceAsStream() must actually be returning null. I've confirmed this by printing it out before I return it.

Java Current Directory Returns `null`

I'm trying to use the printWorkingDirectory() from Apache Commons FTP but it's only returning null. I can't navigate directories, list files, etc.
Log in pass all is success but how ever I try I can not change current directory.
I use this following code:
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FTPDownloadFileDemo {
public static void main(String[] args) {
String server = "FTP server Address";
int port = portNo;
String user = "User Name";
String pass = "Pasword";
FTPClient ftpClient = new FTPClient();
String dir = "stocks/";
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
System.out.println( ftpClient.printWorkingDirectory());//Always null
//change current directory
ftpClient.changeWorkingDirectory(dir);
boolean success = ftpClient.changeWorkingDirectory(dir);
// showServerReply(ftpClient);
if (success)// never success
System.out.println("Successfully changed working directory.");
System.out.println(ftpClient.printWorkingDirectory());// Always null
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
ex.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This is rather old question that deserves an answer. This issue is likely a result of using FTPClient when secure connection is required. You may have to switch to FTPSClient if that is, indeed, the case. Further, output the response from the server with the following code snippet to troubleshoot the issue if secure client doesn't solve the it:
ftpClient.addProtocolCommandListener(
new PrintCommandListener(
new PrintWriter(new OutputStreamWriter(System.out, "UTF-8")), true));
Also, a server can reject your login attempt if your IP address is not white listed. So, being able to see the logs is imperative. The reason you see null when printing current working directory is because you are not logged in. Login method will not throw an exception but rather return a boolean value indicating if the operation succeeded. You are checking for success when changing a directory but not doing so when logging in.
boolean success = ftpClient.login(user, pass);
I faced the same, but I came across with a simple step.
Just added this.
boolean success = ftpClient.changeWorkingDirectory(dir);
ftpClient.printWorkingDirectory(); //add this line after changing the working directory
System.out.println(ftpClient.printWorkingDirectory()); //wont be getting null
Here I have the code and the console output
FTPClient.changeWorkingDirectory - Unknown parser type: "/Path" is current directory
I know I replied too soon ;-P, but I saw this post recently. Hope this helps to future searchers ;-)

java flickr and flickrj download user pictures

Hi I am new to flickrj library.
Have foundational java knowledge though.
The project that I am working on requires me to authenticate into flickr and then download geo-tagged images into a folder in local hard drive. The program will be Desktop application program.
I am approaching the program by breaking down into 3 steps.
1.Proper authentication to be completed.(which i have succeeded)
2.Try to download all the photos that user has when authenticated.
3.Try to alter the code a little so that it will only download geo-tagged images.
My problems is on step 2. I cant download logged-in user images let alone geo-tagged ones.
I am trying the code provided by Daniel Cukier here
But I am running into problem.
My netbeans simply strike off at the line 77 on .getOriginalAsStream() part, with the error "java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.io.ByteArrayOutputStream.write"
From my understanding netbeans striking off a line means , it is depreciated but shouldnt it still work? What is holding this whole problem back?
I have tried researching and basically I have to admit , it is beyond my capability to trouble shoot. If anyone has any idea on what i am doing wrong , I would be so grateful.
Ps: I am not looking to be spoon fed but please answer me in idiot-friendly way as I am still a student and my java isn't the greatest.
This code is what I have so far.
import com.aetrion.flickr.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Properties;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.photos.Photo;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.util.IOUtilities;
import java.io.*;
import java.util.Iterator;
import org.apache.commons.io.FileUtils;
public class authenticate {
Flickr f;
RequestContext requestContext;
String frob = "";
String token = "";
Properties properties = null;
public authenticate() throws ParserConfigurationException, IOException, SAXException {
InputStream in = null;
try {
in = getClass().getResourceAsStream("/setup.properties");
properties = new Properties();
properties.load(in);
} finally {
IOUtilities.close(in);
}
f = new Flickr(
properties.getProperty("apiKey"),
properties.getProperty("secret"),
new REST()
);
Flickr.debugStream = false;
requestContext = RequestContext.getRequestContext();
AuthInterface authInterface = f.getAuthInterface();
try {
frob = authInterface.getFrob();
} catch (FlickrException e) {
e.printStackTrace();
}
System.out.println("frob: " + frob);
URL url = authInterface.buildAuthenticationUrl(Permission.DELETE, frob);
System.out.println("Press return after you granted access at this URL:");
System.out.println(url.toExternalForm());
BufferedReader infile =
new BufferedReader ( new InputStreamReader (System.in) );
String line = infile.readLine();
try {
Auth auth = authInterface.getToken(frob);
System.out.println("Authentication success");
// This token can be used until the user revokes it.
System.out.println("Token: " + auth.getToken());
System.out.println("nsid: " + auth.getUser().getId());
System.out.println("Realname: " + auth.getUser().getRealName());
System.out.println("Username: " + auth.getUser().getUsername());
System.out.println("Permission: " + auth.getPermission().getType());
PhotoList list = f.getPhotosetsInterface().getPhotos("72157629794698308", 100, 1);
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Photo photo = (Photo) iterator.next();
File file = new File("/tmp/" + photo.getId() + ".jpg");
ByteArrayOutputStream b = new ByteArrayOutputStream();
b.write(photo.getOriginalAsStream());
FileUtils.writeByteArrayToFile(file, b.toByteArray());
}
} catch (FlickrException e) {
System.out.println("Authentication failed");
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
authenticate t = new authenticate();
} catch(Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
You are correct in your interpretation of the strikeout that getOriginalAsStream() is deprecated. It looks like you might want to rework your code to use PhotosInterface.getImageAsStream(), passing the ORIGINAL size as one of the arguments.
To adjust NetBeans' behavior with respect to deprecated methods, you can follow the link recommended by #AljoshaBre as well as this one.
If you want download all your photos from Flickr, this is possible if you have a mac computer.
Download Aperture program on Apple Store and install it.
After to install, open the Aperture.
Go on preferences.
Click on 'Accounts' tab.
Click on plus sign (+) on bottom left to add a photo service.
Add the Flicker option.
Follow the login and authorization instructions.
Done! All your photos will be synchronized in you aperture library locate on ~/images/
I hope I have helped.

Eclipse IDE java equivalent of PHP include?

I've been digging around but can't find anything useful.
I'm working on an Android App.
Basically I have a package and there are three java files in it so far; my main screen page, a settings page and what I have called my 'subs.java' where I am putting useful functions, routines.
What I am trying to do is create this 'subs.java' file where routines that get used in more than one place can be stored.
So I have my main app page and I have a settings page. Both of these 'pages' need to use these common functions.
So I was going to put them in my 'subs.java' so I don't end up doubling up code.
Where I am stuck is now I have this subs.java file how do I link to it ?
In PHP if I want to use another file I just include it and I have access to all it's functions.
I suppose I am trying to build up a library, but Java is new to me.
How then would I do this in Eclipse/Java please ?
Here's my subs file, with some useful functions that I found else where :
package com.example.helloandroid;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class Subs extends Activity {
// Read settings
public String ReadSettings(Context context){
FileInputStream fIn = null;
InputStreamReader isr = null;
char[] inputBuffer = new char[255];
String data = null;
try {
fIn = openFileInput("settings.dat");
isr = new InputStreamReader(fIn);
isr.read(inputBuffer);
data = new String(inputBuffer);
Toast.makeText(context, "Settings read",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not read",Toast.LENGTH_SHORT).show();
}
finally {
try {
isr.close();
fIn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
// Save settings
public void WriteSettings(Context context, String data){
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try {
fOut = openFileOutput("settings.dat",MODE_PRIVATE);
osw = new OutputStreamWriter(fOut);
osw.write(data);
osw.flush();
Toast.makeText(context, "Settings saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Settings not saved",Toast.LENGTH_SHORT).show();
}
finally {
try {
osw.close();
fOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
The closest thing to PHP's include in Java is import. Read more about using import and package in Java.
If you've created a project as a package then any class using that package can access any other ones. So if you had SomeFileA.java and it uses package com.something.me, and SomeFileB.java that uses package com.something.me then they can reference each other. Typically Eclipse will auto-add any imports if you just flat out write SomeFileB b = new SomeFileB(); inside SomeFileA. If not you can just do use
import com.something.me.SomeFileB;
You would use the import statement to import your subs class. Then you can refer to any function in the subs class as subs.functionName()
If subs.java is in the same folder as your other java files, you can simply type import subs.
Read more about packages and imports at http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter05/packagesImport.html
What about "import" ? You can import a simple class, not only a library...
Put your common routines as static methods in a class ("MyAppHelper" for example), and call them in your "screens" :
MyAppHelper.function1(...)

FTPClient (commons net) Upload problem

I use the following piece of code to upload a photo to a ftp host. But the photo seems to be corrupted after being uploaded:
There are narrow gray lines at the bottom of the photo.
The size of gray lines could be decreased by decreasing the Buffer Size of the FTPClient object.
import java.io.File;
import java.io.FileInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.net.ftp.FTPClient;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;
import sun.misc.Cleaner;
public class FtpConnectDemo1 {
public static void main(String[] args) {
FTPClient client = new FTPClient();
try {
client.connect("ftp.ftpsite.com");
//
// When login success the login method returns true.
//
boolean login = client.login("user#ftpsite.com", "pass");
if (login) {
System.out.println("Login success...");
int replay = client.getReplyCode();
if (FTPReply.isPositiveCompletion(replay)) {
File file = new File("C:\\Users\\e.behravesh\\Pictures\\me2_rect.jpg");
FileInputStream input = new FileInputStream(file);
client.setFileType(FTP.BINARY_FILE_TYPE);
if (!client.storeFile(file.getName(), input)) {
System.out.println("upload failed!");
}
input.close();
}
//
// When logout success the logout method returns true.
//
boolean logout = client.logout();
if (logout) {
System.out.println("Logout from FTP server...");
}
} else {
System.out.println("Login fail...");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
//
// Closes the connection to the FTP server
//
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
this is known error resolved in newest version of library:
http://commons.apache.org/net/changes-report.html#a3.0.1
Never ever heard of corruption of that type, but: are you uploading from behind a firewall? Try doing client.enterLocalPassiveMode(); before calling storeFile.
I've just tried your code on my local computer and it works. I didn't see any gray lines.
So I guess this is either a passive mode thing as Femi suggest or some network/firewall/lower-level problem.
probably late, but it could help somone to avoid waste time.
Check conf file and permitions!! In Unix using vsftp check that
write_enable=YES
stay uncomment.
Check with another FTP client if it posible to upload files.
FTP file sending is not atomic meaning that if there was a crash in the connection only partial file has been send. i would offer add change name to know when transfer is completed in the end of file send.

Categories

Resources