FTP file upload failure Java - java

I use Apache's FTPClient and FTPServer libraries in my Java project. Server and client are on the same machine.
My FTPServer is supposed to be a local server,nothing related to the Internet. I can connect to the FTPServer from the client(I get 230 as reply code) but i cant seem to do anything. I cant store or retrieve any files.
I read almost every question related to this matter but people who asked other questions were be able to send simple files and had trouble with sending files like pdf etc. I just need to send or retrieve text files.
Any suggestions?
FTPClient client = new FTPClient();
String host = "mypc";
String Name = "user";
String Pass = "12345";
client.connect(host);
client.login(Name,Pass);
System.out.println("Reply Code: " +client.getReplyCode());
File file = new File("C:\\.....myfile..txt");
FileInputStream in = new FileInputStream("C:\\.....myfile..txt");
boolean isStored = client.storeFile("uploadedfile.txt", in);
in.close();
client.logout();
System.out.println("isStored: " +isStored);
I didnt put the real path names. It returns false,no exceptions etc. This might be because of they're on the same machine?
Edit: Turned out i needed write permission to send a file to ftpserver. By default, it doesnt give users write permission. How can i give users write permission using Apache's ftpserver library?

Problem Solved:
This is how to give a user write permission. I added this snippet to server side and it worked.
List<Authority> auths = new ArrayList<Authority>();
Authority auth = new WritePermission();
auths.add(auth);
user.setAuthorities(auths);
There's term Authority written in this symbol -> < > after List and ArrayList in the first line. Site doesn't see words in <> symbol.

Related

How to use Facebook Messenger API?

I am writing a java application in which I need to access my chat history (chat messages between me and another Facebook friend). I have looked at
this link, but it seems outdated since I have noticed that Facebook changed his messenger API significantly. I was wondering if it is still possible to access my message history via java.
p.s. I found a good Facebook Graph API called restfb. But I was not able to find such an API for chat messages.
You can use the inbox resource of the Graph API: https://developers.facebook.com/docs/graph-api/reference/v2.3/user/inbox
Edit:
In order to use this from Java, you'll need to first follow the login instructions at https://developers.facebook.com/docs/facebook-login/v2.3 . That's a large enough operation that I'm going to assume that you've already done it -- it's well outside the scope of this answer (but I'm sure there are other questions that handle it sufficiently on StackOverflow if you look).
Once you have an access token for a particular session (you can get one to test with by going to https://developers.facebook.com/docs/graph-api/reference/v2.3/user/inbox, clicking the Graph Explorer button, clicking "Get Token" -> "Get Access Token", and ensuring that "read_mailbox" is selected under "Extended Permissions), it's pretty straightforward to read the API. You can do it using only standard JDK classes in just a few lines:
String accessToken = "replaceThisWithAccessToken";
String urlString = MessageFormat.format("https://graph.facebook.com/v2.3/me/inbox?access_token={0}&&format=json&method=get",
accessToken);
URL url = new URL(urlString);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
This glosses over a lot of things -- doesn't help with authentication, assumes your active trust store contains a certification path for the Facebook SSL cert (it should), and ignore proper error handling. And in practice you'll want to use RestClient or something similar instead of using URL directly -- but the above should be indicative of basically what you need to do.

How to stream url from .pls file with java?

I want to stream a radio with Java, my approach is to download the playlist file (.pls), then extract one of the urls given in that same file and finally, stream it with java. However, it seems I cannot find a way to do it.. I tried with JMF, but I get java.io.IOException: Invalid Http response everytime I run the code.
Here is what I tried:
Player player = Manager.createPlayer(new URL("http://50.7.98.106:8398"));
player.start();
The .pls file:
[playlist]
NumberOfEntries=1
File1=http://50.7.98.106:8398/
In the piece of code above I'm setting the URL by hand, just for testing, but I've sucessfuly done the .pls downloading code and it's working, and from this I make another question, is it a better approach to just simply play the .pls file locally? Can it be done?
You are connecting to an Icecast server, not a web server. That address/port is not sending back HTTP responses, it's sending back Icecast responses.
The HTTP specification states that the response line must start with the HTTP version of the response. Icecast responses don't do that, so they are not valid HTTP responses.
I don't know anything about implementing an Icecast client, but I suspect such clients interpret an http: URL in a .pls file as being just a host and port specification, rather than a true HTTP URL.
You can't use the URL class to download your stream, because it (rightly) rejects invalid HTTP responses, so you'll need to read the data yourself. Fortunately, that part is fairly easy:
Socket connection = new Socket("50.7.98.106", 8398);
String request = "GET / HTTP/1.1\n\n";
OutputStream out = connection.getOutputStream();
out.write(request.getBytes(StandardCharsets.US_ASCII));
out.flush();
InputStream response = connection.getInputStream();
// Skip headers until we read a blank line.
int lineLength;
do {
lineLength = 0;
for (int b = response.read();
b >= 0 && b != '\n';
b = response.read()) {
lineLength++;
}
} while (lineLength > 0);
// rest of stream is audio data.
// ...
You still will need to find something to play the audio. Java Sound can't play MP3s (without a plugin). JMF and JavaFX require a URL, not just an InputStream.
I see a lot of recommendations on Stack Overflow for JLayer, whose Player class accepts an InputStream. Using that, the rest of the code is:
Player player = new Player(response);
player.play();

Apache Camel reading unread mail from gmail account

Just tried learning Apache Camel.
I am trying to read gmail inbox unread mail.
I got the code snippet while searching but not able to get success from it.
if someone point out the mistake,
PollingConsumer pollingConsumer = null;
CamelContext context = new DefaultCamelContext();
Endpoint endpoint = context.getEndpoint("imaps://imap.gmail.com?username=" + mailId + "&password=" + password + "&delete=false&peek=false&unseen=true&consumer.delay=6000&closeFolder=false&disconnect=false");
System.out.println("end point:"+endpoint);
pollingConsumer = endpoint.createPollingConsumer();
System.out.println("polling consumer:"+pollingConsumer);
pollingConsumer.start();
pollingConsumer.getEndpoint().createExchange();
System.out.println("Exchange is created:");
Exchange exchange = pollingConsumer.receive();
System.out.println("pollingConsumer.receive()");
pollingConsumer.receive(); is getting blocked, I have unread mail in my mailbox.
Also I tried pollingConsumer.receive(6000); but it returns null.
I enable IMAP access in Gmail settings. is there any thing I am missing?
Let me write the solution, It will help someone facing similar issue .
Actually I have added java mail jar, but imap jar was missing and it was not displaying any error for this.
That is why I was not able to figure out the actual cause.
After browsing the parameters of "imaps://imap.gmail.com", I came across "debugMode" parameter which by default is false. when I added that parameter with value true, then it complained of missing jar on my console. After adding that jar thinks work perfectly.
Thanks for help.

Adding to, cc,subject in Desktop.mail(uri)

I am a beginner of using Desktop.mail(URI) class, so I am looking for a way to add to, cc and subject to the mail when triggered from the program.
String mailTo = "test#domain.com";
String cc = "test2#domain.com";
String subject = "firstEmail";
String body = "the java message";
URI uriMailTo = new URI(mailTo,cc,subject,body);
Desktop desktop;
desktop = Desktop.getDesktop();
desktop.mail(uriMailTo);
can any one suggest any tutorials to learn this process, because I am looking for even more functions like receiving the data back from the outlook to the Java program.
Thanks in advance for help!
The Desktop.mail() function is a utility method for launching whatever mail program may exist in the users system (if any). You have (very) limited capability of controlling the actual mail message to be (eventually) sent, and once the mail client is displayed you're pretty much done - aka you wont be getting any feedback on what message was actually sent or wether it succeeded.
If you need this level of control then you should be using the JavaMail API, which does a lot of what you seem to need.
If you are stuck with using the Desktop mail client, then you might want to read up on RFC 2368. It describes all the fields that can be included in a mailto URI. So, you will be able to populate the message, but you won't get feedback on wether it was successfully sent or not:
mailto:joe#example.com?cc=bob#example.com&body=hello+world
A code example of constructing your URI (which is incorrect btw):
final String mailURIStr = String.format("mailto:%s?subject=%s&cc=%s&body=%s",
mailTo, subject, cc, body);
final URI mailURI = new URI(mailURIStr);
Where the substituted should be URL encoded if necessary.

Where does Java store remembered HTTP basic auth passwords and how do you delete them?

I have a Java Swing app that launches by web start and accesses data files on a server through a URL. The files are served by Apache2, with HTTP basic Auth. Java pops up a dialog box prompting for a login, and that works fine.
The trouble comes when a user has checked "save this password in your password list". Then the password changes or was incorrect in the first place and you're stuck. It's apparently not smart enough to give you another chance. If your saved login fails you get a 401 error and that's it.
So, where is it storing saved passwords and how do you delete them?
The code involved looks like this:
// uri is a String
URL url = new URL(uri);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
// check HTTP response code
int responseCode = urlConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK)
throw new IOException("\nHTTP response code: " + responseCode);
// read the file
BufferedReader reader = new BufferedReader
(new InputStreamReader (urlConnection.getInputStream ()));
... etc ...
That code works fine, except in this situation where the user has saved a bad password, in which case you get a 401.
My understanding is that Java WebStart puts its hooks into the java.net classes, so that you get things like the password prompt, which you wouldn't get by running the same code from the command line or from your IDE. So, this question is really about that behavior.
Thanks!
No Code? Now you get a vague answer. Depending on your HttpClient, it's probably stored in the cookies or something. Re-initializing your HttpClient would be a great first debugging step. If that doesn't work, posting a little code here would be very helpful.
In windows the passwords are saved in below file.
{user_name}\AppData\LocalLow\Sun\Java\Deployment\security\auth.dat
You can delete this file to clear the saved passwords.

Categories

Resources