Connecting to PC to view shared folders from Android device - java

I am working on a samba client for Android. Given an IP address it should connect to it and browse the shared folders.
For this I use JCIFS. I dropped the jar in my Android project and added following code to connect to PC and get the list of files:
private void connectToPC() throws IOException {
String ip = "x.x.x.x";
String user = Constants.username + ":" + Constants.password;
String url = "smb://" + ip;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
SmbFile root= new SmbFile(url, auth);
String[] files = root.list();
for (String fileName : files) {
Log.d("GREC", "File: " + fileName);
}
}
And I get in return: jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password.
But the credentials are correct. I also tried with another samba client from the android market that uses JCIFS and it successfully connected to that ip, so obviously I am doing something wrong here but don't know what especially.
Any help is highly appreciated.

In the end I managed successfully to connect to PC. The issue turned out to be in the NtlmPasswordAuthentication(); constructor.
So, instead of this:
String user = Constants.username + ":" + Constants.password;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
I changed to this:
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",
Constants.username, Constants.password);
I don't know why, perhaps it's because of ":" special character, perhaps because of Android, but passing an empty domain name, the user name, and password separately to the constructor, solved the issue.

Since some people will get to this topic if they got a similar problem with android and JCIFS,
these are other common problems when trying to make it work:
*Put the .jar specifically in /libs folder of your android project (not just via "build path")
*Be sure that your project has internet permission What permission do I need to access Internet from an android application?
*Also be sure that your JCIFS code is running in a separate thread from the UI (in other words, use AsyncTask class) how to use method in AsyncTask in android?
*Code:
protected String doInBackground(String... params) {
SmbFile[] domains;
String username = USERNAME;
String password = PASSWORD;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",
username, password);
try {
SmbFile sm = new SmbFile(SMB_URL, auth);
domains = sm.listFiles();
for (int i = 0; i < domains.length; i++) {
SmbFile[] servers = domains[i].listFiles();
for (int j = 0; j < servers.length; j++) {
Log.w(" Files ", "\t"+servers[j]);
}
}
} catch (SmbException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "";
}
these were the problems i encounter while trying to make work JCIFS on android, hope to help anyone, regards.

maybe i can help other people too.
I had the problem that i used thread.run() instead of thread.start() to execute the Smb-Code in a Runnable. I searched a lot of time for an answer but nothing fixed my problem.
But then a friend explained me the different between thread.run() and thread.start():
run(): Execute the Methode (for example the run() Methode of a Runnable) like a normal Method (synchronous)
start(): Start the Thread with the Runnable in an own task (asynchronous)
And for Smb you need a asynchronous Thread. Because of this you need to call thread.start()!
Maybe someone make the same mistake as i did.

Related

EC2 UserData not working with Java SDK

I am trying to send some userData while spawning a new instance but unfortunately it is not working. The code is:
For debugging purposes, I have just used an echo statement, but I cannot find any new file generated on the machine. I also checked the cloud-init logs in /var/log folder, but none of them are present.
Can anyone help me to figure out a way to debug this problem or is there something crucial that I am missing?
I am using C4.8xLarge instances for the reference.
public static String getUserData() throws UnsupportedEncodingException {
String userData = "";
userData = userData + "#!/bin/bash" + "\n";
userData += "echo hello > hello" + "\n";
String base64UserData = null;
try {
base64UserData = new String(Base64.encodeBase64(userData.getBytes("UTF-8")), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return base64UserData;
}
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
runInstancesRequest.setImageId(AMI_ID);
runInstancesRequest.setEbsOptimized(true);
runInstancesRequest.setInstanceType(INSTANCE_TYPE);
runInstancesRequest.setMinCount(1);
runInstancesRequest.setMaxCount(1);
runInstancesRequest.withSecurityGroups("JavaSecurityGroup1");
runInstancesRequest.withUserData(getUserData());
List<BlockDeviceMapping> map = new ArrayList<>();
map.add(new BlockDeviceMapping().withEbs(new EbsBlockDevice().withSnapshotId("snap-af8s67ef").withIops(9000).withVolumeSize(300).withVolumeType("io1")).withDeviceName("/dev/sdf"));
runInstancesRequest.withBlockDeviceMappings(map);
RunInstancesResult runInsRes = ec2.runInstances(runInstancesRequest);
Thanks!
After creating an instance, go into the EC2 web console and view the user data on the instance. You should be able to view it as plain text in the web console. If it isn't there, or if it contains something other than the two lines you are trying to set as the user data, then you will know there is an issue with the way you are setting the user data.
If it is there and looks correct, then you will need to look into the cloud-init service log /var/log/cloud-init-output.log on the created instance to see what the error is.
Edit: I just noticed you said the cloud-init logs are not present on the machine. What OS are you using for this server? It may not have the cloud-init service.

Catch the download link automatically like IDM?

Here is my code for downloading a file I am passing a URL, but I want to make my download manager catch the link automatically
private void button1_Click_1(object sender, EventArgs e)
{
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
string []filename;
string fn ; fn=textBox1.Text;
int i;
filename =fn.Split('/');
for (i = 1; i <= filename.Length; i++) ;
string oname=filename[i-2];
//////// Starts the download
client.DownloadFileAsync(new Uri("http://dinirah.wen.ru/Internet-k-zariye-musalmano-gumrah-kia-ja-raha.mp3"), textBox2.Text+"\\"+oname);
//////// the above i passed the url to download.
label4.Text = i.ToString();
button1.Text = "Download In Process";
button1.Enabled = false;
}
Now I want to make my downloader automatically get the download url, and store it in a string which it then passes as an URL later.
You should develop browser extension(s) and then you would be able to intercept the file download process.
The other way is to monitor your computer's network connections and intercept when a desired file type is being requested. I have found that IDM intercepts my downloads even if I am downloading it using my programs (If enabled in IDM to intercept any download). Be careful with windows update files, diagnostic files and any other unknown file.

Insert variables into SAS using JAVA (IOM Bridge). Should i use CORBA stubs and JDBC or is there any other alternative?

This is part of my code snippet
WorkspaceConnector connector = null;
WorkspaceFactory workspaceFactory = null;
String variableListString = null;
Properties sasServerProperties = new Properties();
sasServerProperties.put("host", host);
sasServerProperties.put("port", port);
sasServerProperties.put("userName", userName);
sasServerProperties.put("password", password);
Properties[] sasServerPropertiesList = { sasServerProperties };
workspaceFactory = new WorkspaceFactory(sasServerPropertiesList, null, logWriter);
connector = workspaceFactory.getWorkspaceConnector(0L);
IWorkspace sasWorkspace = connector.getWorkspace();
ILanguageService sasLanguage = sasWorkspace.LanguageService();
//send variable list string
//continued
I need to send the "variableListString" to the SAS server through IOM bridge. Java SAS API doesn't give explicit ways to do it. Using CORBA and JDBC is the best way to do it?? Give me a hint how to do it. Is there any alternative method to do it??
This was asked a while back but useful in case anyone is still looking to do the same.
One way to do this is build a string of sas code and submit it to the server. We use this method for setting up variables on the host for the connected session. You can also use this technique to include sas code using code like %include "path to my code/my sas code.sas";:
...continue from code in the question...
langService = iWorkspace.LanguageService();
StringBuilder sb = new StringBuilder();
sb.append("%let mysasvar=" + javalocalvar);
... more variables
try {
langService.Submit(sb.toString());
} catch (GenericError e) {
e.printStackTrace();
}

Suggestion about detecting Private Ip Address with an applet

I'm having some troubles to detect client's private ip that conect to a web application I built.
Take a look at my tests results(In machines that runs windows):
1-In some machines(from different location ,countries..) the applet give me the correct ip but
2-In others I've obtained ip=127.0.0.1 :
What have I tried to solve this?
A- for example: I've stopped the avast program protection(web shield) and the applet start to give me the correct private ip.
B- In others machines I tried "point A" but It didn't work
C- I also edit host file but I didn't work as well
What I need from you is to help me to understand what is happening? where to look in order to resolve this...
Please don't answer saying "Why do you need the private ip? It could change..." ... I know all the machines that are going to connect to my web application so I can configure them.
Part of the source code that my applet use:
private String PrivateIP(boolean flag)
{
String s1 = "unknown";
String s2 = getDocumentBase().getHost();
int i = 80;
if(getDocumentBase().getPort() != -1)
i = getDocumentBase().getPort();
try
{
String s = (new Socket(s2, i)).getLocalAddress().getHostAddress();
if(!s.equals("255.255.255.255"))
s1 = s;
}
catch(SecurityException _ex)
{
s1 = "FORBIDDEN";
}
catch(Exception _ex)
{
s1 = "ERROR";
}
if(flag)
try
{
s1 = (new Socket(s2, i)).getLocalAddress().getHostName();
}
catch(Exception _ex)
{
Stat = "Cannot Lookup this IP";
}
return s1;
}
I'll let you more information:
I've traid this http://www.auditmypc.com/digital-footprint.asp in order to obtain the ip from probably other method but the same result, I've also run http://www.auditmypc.com/firewall-test.asp and obtained in the machines that I couldn't obtained the correct ip a message like "Congratulations you don't have any port to be open" xD...
Thanks in advance!
First of all, there can be more than one IP address available on the client, if there is more than one network interface. Which one is returned by your method depends on which is used for new Socket() to open.
Now, you do not have to open sockets to get the client's IP. What you can do instead is to enumerate them like this:
String host = InetAddress.getLocalHost().getHostName();
InetAddress[] addressArray = InetAddress.getAllByName(host);
String[] ipArray = new String[addressArray.length];
for (int i = 0; i < addressArray.length; i++) {
InetAddress addr = addressArray[i];
ipArray[i] = addr.getHostAddress();
}
return ipArray;
Now the ipArray will hold a list of available IP adresses on client's workstation.

jcifs.smb.SmbException: The network name cannot be found

The following is my piece of code
SmbFile catalExp = new SmbFile("smb://<Shared machine name>/Project share/Home/4. Folders/planning - Design & Exec/sample.txt",
new NtlmPasswordAuthentication(LoadProp.getShrdDomain(),"user","paswd"));
In this i am getting the error
jcifs.smb.SmbException: The network name cannot be found
at jcifs.smb.SmbTransport.send(SmbTransport.java:753)
at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:140)
at jcifs.smb.SmbSession.send(SmbSession.java:103)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:132)
at jcifs.smb.SmbFile.connect(SmbFile.java:674)
at jcifs.smb.SmbFile.connect0(SmbFile.java:644)
at jcifs.smb.SmbFile.open0(SmbFile.java:700)
at jcifs.smb.SmbFile.createNewFile(SmbFile.java:2027)
Is this anything to do with the user rights to that particular shared folder or am I doing anything wrong
Please advice
I ran into this error message, and it turned out the problem was that my network path was incorrect. You'll want to ensure that the NtlmPasswordAuthentication object is configured correctly, that your network path is correct, and that you've set the jcifs.netbios.wins property correctly, as indicated in the first example on this page.
For example, to load a remote properties file:
final NtlmPasswordAuthentication AUTH = new NtlmPasswordAuthentication("domainname", "username", "password");
Config.setProperty("jcifs.netbios.wins", "10.10.1.1");
Properties props = new Properties();
InputStream in = new SmbFileInputStream(new SmbFile("smb://10.10.1.1:445/rootfolder/path/filename.properties", AUTH));
props.load(in);
(You'll need to add try/catch and input stream closing)
A good way to ensure that all of your parameters are correct is to test logging into and locating the file using a smb/cifs client. For example smbclient on linux/unix:
smbclient -Uusername -p 139 //10.10.1.1/rootfolder
The domain is displayed at the top when you login with smbclient:
Domain=[DOMAINNAME]
..and you can navigate to your file to make sure you've got the path correct.
After running into this issue for almost 1 day i realize that these exception is meaningless
I was just giving wrong path of server side location
Below is the peace of groovy code worked for me
String domain = "domain"
String user = "username"
String pass = "password"
String IP = "xx.yy.zz.aa"
String sharedFolder="//my//path//to//server//";
String path="smb://$IP"+sharedFolder+"test.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, user, pass );
SmbFile smbFile = new SmbFile(path,auth);
SmbFileOutputStream smbfos = new SmbFileOutputStream(smbFile);
smbfos.write("testing....and writing to a file".getBytes());
System.out.println("completed ...nice !");
Well I'm getting this error also but only on one device, my code that works on Android 4.04 is
String strprog = "STRING CREATED| "; //debug log string
try {
strprog += "NTLM| ";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("username:password");
strprog += "SMB| ";
SmbFile file = new SmbFile("smb://<pcname>/foldername/filename.txt",auth);
strprog += "EXIST| ";
String there = String.valueOf(file.exists());
strprog += "View| ";
TextView pp;
pp = (TextView) findViewById(R.id.tv);
pp.setText(there);
} catch (Exception e) {
// TODO Auto-generated catch block
strprog += "ERROR! ";
TextView ll;
ll = (TextView) findViewById(R.id.tv);
ll.setText(strprog + e.getStackTrace().toString() + " " + e.getMessage() + " " + e.getLocalizedMessage() );
}
The only difference I see is where you have your NtlmPasswordAuth compared to mine.
But as I stated for some reason this throws null input param on Andriod 2.0 when I dive deeper then smb://host but I hope this helps you out.
I had this problem, and it turned out that I did not see what the share name was that was mapped to my Windows shared drive... So, using Mac OS, I ran:
smbutil view smb://MYUSERNAME#HOSTNAME
After I was prompted for my password, I then was displayed a list of share names (that weren't evident when I looked at this stuff using Windows). Once I found my share name, it was as simple as using that when connecting with JCIFS:
new SmbFile("smb://HOSTNAME/SHARENAME/path/I/was/trying/to/access", auth);

Categories

Resources