How can I download a file given the following URL with Java-SE-7:
imap://georg#imap.acme.com:143/fetch%3EUID%3E/INBOX%3E18678?fileName=testmail.eml
Any help highly appreciated - thank you in advance.
Here's my basic solution. The following code needs Apache Commons I/O 2.4 which can be downloaded here:
public class ImapMessage {
private String authority;
private String protocol;
private String host;
private int port;
private String username;
private String password;
private String foldername;
private long msgid;
private String filename;
private Message message;
public ImapMessage(String url) throws IOException, MessagingException {
parseURL(decodeURL(url));
}
#Override
public String toString() {
return "protocol: "+protocol+"\n"+
"host: "+host+"\n"+
"port: "+port+"\n"+
"username: "+username+"\n"+
"password: "+password+"\n"+
"folder: "+foldername+"\n"+
"msgid: "+msgid+"\n"+
"filename: "+filename;
}
private String decodeURL(String url) throws IOException {
if(url!=null && !url.isEmpty()) {
url = StringUtils.replace(url, "%3E", ">");
url = StringUtils.replace(url, "%20", " ");
return url;
} else {
throw new IOException("The given URL is empty or invalid.");
}
}
private void parseURL(String url) throws IOException, MalformedURLException {
if(url!=null && !url.isEmpty()) {
//<editor-fold defaultstate="collapsed" desc="Parse Protocol">
if(url.startsWith("imaps")) {
url = StringUtils.replace(url, "imaps", "http", 1);
protocol = "imaps";
} else if(url.startsWith("imap")) {
url = StringUtils.replace(url, "imap", "http", 1);
protocol = "imap";
} else {
throw new IOException("Unsupported protocol: "+url.substring(0, url.indexOf("://")));
}
try {
URL newurl = new URL(url);
String path = newurl.getPath();
String query = newurl.getQuery();
authority = newurl.getAuthority();
host = newurl.getHost();
port = newurl.getPort();
username = newurl.getUserInfo();
password = "provide your password here";
foldername = path.substring(path.indexOf(">/")+2, path.lastIndexOf(">"));
msgid = Long.parseLong(path.substring(path.lastIndexOf(">")+1, path.length()));
filename = query.substring(query.indexOf("=")+1, query.length());
} catch (MalformedURLException ex) {
throw ex;
}
} else {
throw new IOException("The given URL is empty or invalid.");
}
}
public File fetchMessage() throws IOException, FileNotFoundException, MessagingException {
Store store = null;
Folder folder = null;
File filepath = new File("/destination/directory");
try {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", protocol);
Session session = Session.getDefaultInstance(props, null);
// session.setDebug(true);
store = session.getStore(protocol);
store.connect(host, port, username, password);
folder = store.getFolder(foldername);
folder.open(Folder.READ_ONLY);
UIDFolder ufolder = (UIDFolder)folder;
message = ufolder.getMessageByUID(msgid);
if(message!=null) {
File file = null;
if(filename.equals("null")) {
file = new File(filepath.getAbsolutePath()+File.separator+Long.toString(System.nanoTime())+".eml");
} else {
file = new File(filepath.getAbsolutePath()+File.separator+filename);
}
message.writeTo(new FileOutputStream(file));
return file;
} else {
throw new MessagingException("The requested e-mail could not be found on the mail server.");
}
} catch(Exception ex) {
throw ex;
} finally {
if(folder!=null) {
folder.close(true);
}
if(store!=null) {
store.close();
}
}
}
}
Related
I'm working to make client rest service with jasperserver to generate reports. I'm using the following code to make that:
I have problem in setting server url and report path,
for server url I put http://localhost:8081/jasperserver/
and as shown in next image I put report path rest/report/mytest/my_report but I get 404 not found error in line
File remoteFile = resource.get(File.class);
So how can I get the proper report path from jasperserver?
public class App2 {
private final static String serverUrl = "http://localhost:8081
/jasperserver/";
private final static String serverUser = "jasperadmin";
private final static String serverPassword = "jasperadmin";
public static void main(String arg[]) throws Exception {
Report reporte = new Report();
reporte.setFormat("pdf");
reporte.setOutputFolder("/home/ali/images");
ClientConfig clientConfig;
Map<String, String> resourceCache=new HashMap<String, String>();
clientConfig = new DefaultApacheHttpClientConfig();
clientConfig.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
clientConfig.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true);
ApacheHttpClient client = ApacheHttpClient.create(clientConfig);
client.addFilter(new HTTPBasicAuthFilter(serverUser, serverPassword));
String describeResourcePath = "/rest/resource" + "/mytest/my_report/";
String generateReportPath = "/rest/report" + "/mytest/my_report/" + "?RUN_OUTPUT_FORMAT=" + reporte.getFormat();
WebResource resource = null;
String resourceResponse = null;
if (resourceCache.containsKey(describeResourcePath)) {
resourceResponse = resourceCache.get(describeResourcePath);
} else {
resource = client.resource(serverUrl);
resource.accept(MediaType.APPLICATION_XML);
resourceResponse = resource.path(describeResourcePath).get(String.class);
resourceCache.put(describeResourcePath, resourceResponse);
}
Document resourceXML = parseResource(resourceResponse);
resourceXML = addParametersToResource(resourceXML, reporte);
resource = client.resource(serverUrl + generateReportPath);
resource.accept(MediaType.TEXT_XML);
System.out.println(resource);
String reportResponse = resource.put(String.class, serializetoXML(resourceXML));
String urlReport = parseReport(reportResponse);
resource = client.resource(urlReport);
System.out.println(resource);
File destFile = null;
try {
File remoteFile = resource.get(File.class);
File parentDir = new File(reporte.getOutputFolder());
destFile = File.createTempFile("report_", "." + getExtension(reporte.getFormat()), parentDir);
FileUtils.copyFile(remoteFile, destFile);
} catch (IOException e) {
throw e;
}
}
/**
*
* #return
* #throws DocumentException
*/
private static Document parseResource(String resourceAsText) throws Exception {
// LOGGER.debug("parseResource:\n" + resourceAsText);
Document document;
try {
document = DocumentHelper.parseText(resourceAsText);
} catch (DocumentException e) {
throw e;
}
return document;
}
/**
*
*/
private static String parseReport(String reportResponse) throws Exception {
String urlReport = null;
try {
Document document = DocumentHelper.parseText(reportResponse);
Node node = document.selectSingleNode("/report/uuid");
String uuid = node.getText();
node = document.selectSingleNode("/report/totalPages");
Integer totalPages = Integer.parseInt(node.getText());
if (totalPages == 0) {
throw new Exception("Error generando reporte");
}
urlReport = serverUrl + "/report/" + uuid + "?file=report";
} catch (DocumentException e) {
throw e;
}
return urlReport;
}
/**
*
* #param resource
* #param reporte
* #return
*/
private static Document addParametersToResource(Document resource, Report reporte) {
// LOGGER.debug("addParametersToResource");
Element root = resource.getRootElement();
Map<String, String> params = reporte.getParams();
for (Map.Entry<String, String> entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key != null && value != null) {
root.addElement("parameter").addAttribute("name", key).addText(value);
}
}
// LOGGER.debug("resource:" + resource.asXML());
return resource;
}
/**
*
* #param aEncodingScheme
* #throws IOException
* #throws Exception
*/
private static String serializetoXML(Document resource) throws Exception {
OutputFormat outformat = OutputFormat.createCompactFormat();
ByteArrayOutputStream out = new ByteArrayOutputStream();
outformat.setEncoding("ISO-8859-1");
try {
XMLWriter writer = new XMLWriter(out, outformat);
writer.write(resource);
writer.flush();
} catch (IOException e) {
throw e;
}
return out.toString();
}
/**
*
* #param format
* #return
*/
private static String getExtension(String format) {
String ext = null;
if (format.equals(Report.FORMAT_PDF)) {
ext = "pdf";
} else if (format.equals(Report.FORMAT_EXCEL)) {
ext = "xls";
}
return ext;
}
}
I have fixed it,I need to change path
urlReport = serverUrl + "/report/" + uuid + "?file=report";
to
urlReport = serverUrl + "/rest/report/" + uuid + "?file=report";
in parseReport method
private static String parseReport(String reportResponse) throws Exception {
String urlReport = null;
try {
Document document = DocumentHelper.parseText(reportResponse);
Node node = document.selectSingleNode("/report/uuid");
String uuid = node.getText();
node = document.selectSingleNode("/report/totalPages");
Integer totalPages = Integer.parseInt(node.getText());
if (totalPages == 0) {
throw new Exception("Error generando reporte");
}
urlReport = serverUrl + "/report/" + uuid + "?file=report";
} catch (DocumentException e) {
throw e;
}
return urlReport;
}
I am trying to download multiple files from a remote server using multiple threads. However when I am using multiple threads I get
java.lang.IOException : Pipes closed.
The same code works fine when i am using exactly one thread.
Is it not possible to download multiple files simultaneously from the same remote server using JSch?
SftpTest.java
public class SftpTest {
private static List<SftpAccessor> accessorList = new ArrayList<SftpAccessor>();
private static List<Payload> files = new ArrayList<Payload>();
private static ExecutorService writerThreadPool = Executors.newFixedThreadPool(10);
public static void main(String args[]) throws JSchException, InterruptedException {
SSH srcServer = new SSH();
srcServer.setHostname("10.22.65.140");
srcServer.setKey("D:\\jars\\dmwvmcol01.ec2user.pem");
srcServer.setPort("22");
srcServer.setUsername("ec2-user");
SftpAccessor acc = new SftpAccessor(srcServer);
accessorList.add(acc);
files.addAll(acc.ls("/data/test/src", false, "*", 1));
for (Payload file : files) {
writerThreadPool.submit(new LocalWriterThread(file));
}
writerThreadPool.shutdown();
writerThreadPool.awaitTermination(20, TimeUnit.MINUTES);
}}
LocalWriterThread.java
public class LocalWriterThread implements Callable<String> {
private Payload payload;
public LocalWriterThread(Payload payload) {
this.payload = payload;
}
public String call() throws Exception {
String dest = "D:\\output\\jobsystemnew";
System.out.println(payload.getFilename());
File file = new File(dest + "/" + payload.getFilename());
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
copy(payload.getInputStream(), fos);
payload.setInputStream(null);
return "";
}
private void copy(InputStream is, OutputStream os) throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
System.out.println("Started Copying file : " + payload.getFilename());
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
while (bis.read(buffer) != -1) {
bos.write(buffer);
}
bos.flush();
System.out.println("Finished Copying file : " + payload.getFilename());
}
finally {
System.out.println("Closing input stream for " + payload.getFilename());
bis.close();
bos.close();
/*
* try { if (is != null) { is.close(); } } catch (Exception e) { System.out.println(" " + e + " : " + e.getMessage() + " unable to close input stream : " + payload.getFilename());
* e.printStackTrace(); }
*/
/*
* try { if (os != null) { os.close(); } } catch (Exception e) { System.out.println(" " + e + " : " + e.getMessage() + " unable to close output stream : " + payload.getFilename());
* e.printStackTrace(); }
*/
}
}}
SSH.java
public class SSH {
String hostname;
String port;
String username;
String key;
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
} }
SftpAccessor.java
public class SftpAccessor {
private JSch jsch = new JSch();
private ChannelSftp channelSftp = null;
private Session session = null;
String errorMsg = null;
public SftpAccessor(SSH ssh) throws JSchException {
jsch.addIdentity(ssh.getKey());
session = jsch.getSession(ssh.getUsername(), ssh.getHostname(), Integer.parseInt(ssh.getPort()));
session.setHostKeyAlias(ssh.getKey());
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
}
public List<Payload> ls(String directory, boolean recursive, String filemask, int delayMinutes) {
List<Payload> files = new ArrayList<Payload>();
try {
channelSftp.cd(directory);
#SuppressWarnings("unchecked")
Vector<ChannelSftp.LsEntry> entries = channelSftp.ls(filemask);
for (ChannelSftp.LsEntry entry : entries) {
try {
if (entry.getAttrs().isDir()) {
if (recursive) {
List<Payload> filesToAdd = ls(directory + "/" + entry.getFilename(), recursive, filemask, delayMinutes);
files.addAll(filesToAdd);
}
}
else {
Date lastmodified = new Date(entry.getAttrs().getMTime() * 1000L);
Date currdate = new Date(new Date().getTime() - (delayMinutes * 60 * 1000L));
if (lastmodified.before(currdate)) {
String filename = entry.getFilename();
entry.getAttrs().getMTime();
Payload file = new Payload();
System.out.println("Getting input Stream for " + directory + "/" + filename);
file.setInputStream(channelSftp.get(directory + "/" + filename));
file.setFilename(filename);
file.setLastModified(lastmodified);
files.add(file);
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
catch (SftpException e) {
}
return files;
}}
Payload.java
public class Payload {
private String filename;
private InputStream inputStream;
private Date lastModified;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(Date lastModified) {
this.lastModified = lastModified;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}}
JSch is not thread-safe. Even if it were, there's hardly any performance advantage in using parallel downloads over a single SSH session. It would be as slow as serial downloads. Moreover, you may hit server-side limit of concurrent file handles.
You should open a separate session for each thread/download.
I need to export/download all files of the other domain users. I used the client login with administer account to see the all files of domain users. however,only document can be export/download,others are fail.
so what is the download url format of the others(For File,pdf,presentation and spreadsheet)??
my document download url is
https://docs.google.com/feeds/download/documents/Export?xoauth_requestor=admin#domain.com&docId=<id>&exportFormat=doc
my program is as following:
public class AuthExample {
private static DocsService docService = new DocsService("Auth Example");
public static void main(String[] args)
throws Exception
{
String adminUser = admin;
String adminPassword = adminpasswd;
String impersonatedUser = "user#domain.com";
docService.setUserCredentials(adminUser, adminPassword);
URL url = new URL( "https://docs.google.com/feeds/" + impersonatedUser + "/private/full");
DocumentListFeed feed = docService.getFeed(url, DocumentListFeed.class);
for (DocumentListEntry entry : feed.getEntries()) {
String title = entry.getTitle().getPlainText();
System.out.println( title );
String type = entry.getType();
if ( type.equals("document") )
{
String encodedAdminUser = URLEncoder.encode(adminUser);
String resourceId = entry.getResourceId();
String resourceIdNoPrefix = resourceId.substring( resourceId.indexOf(':')+1 );
String downloadUrl =
"https://docs.google.com/feeds/download/documents/Export" +
"?xoauth_requestor=" + encodedAdminUser +
"&docId=" + resourceIdNoPrefix +
"&exportFormat=doc";
downloadFile( downloadUrl, title + ".doc" );
}
}
}
// Method pasted directly from Google documentation
public static void downloadFile(String exportUrl, String filepath)
throws IOException, MalformedURLException, ServiceException
{
System.out.println("Exporting document from: " + exportUrl);
MediaContent mc = new MediaContent();
mc.setUri(exportUrl);
MediaSource ms = docService.getMedia(mc);
InputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = ms.getInputStream();
outStream = new FileOutputStream(filepath);
int c;
while ((c = inStream.read()) != -1) {
outStream.write(c);
}
} finally {
if (inStream != null) {
inStream.close();
}
if (outStream != null) {
outStream.flush();
outStream.close();
}
}
}
}
Don't build the download link manually, instead use the entry's content link as explained in the docs:
https://developers.google.com/google-apps/documents-list/#downloading_documents_and_files
I have tried all the things to connect Facebook with XMPP but i have faced only
one error all the time which is :
SASL authentication failed using mechanism DIGEST-MD5 I am implementing following method to perform this task :
public class MySASLDigestMD5Mechanism extends SASLMechanism {
public MySASLDigestMD5Mechanism(SASLAuthentication saslAuthentication) {
super(saslAuthentication);
}
protected void authenticate() throws IOException, XMPPException {
String[] mechanisms = { getName() };
Map<String, String> props = new HashMap<String, String>();
sc = Sasl.createSaslClient(mechanisms, null, "xmpp", hostname, props, this);
super.authenticate();
}
public void authenticate(String username, String host, String password) throws IOException, XMPPException {
this.authenticationId = username;
this.password = password;
this.hostname = host;
String[] mechanisms = { getName() };
Map<String,String> props = new HashMap<String,String>();
sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this);
super.authenticate();
}
public void authenticate(String username, String host, CallbackHandler cbh) throws IOException, XMPPException {
String[] mechanisms = { getName() };
Map<String,String> props = new HashMap<String,String>();
sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, (org.apache.harmony.javax.security.auth.callback.CallbackHandler) cbh);
super.authenticate();
}
protected String getName() {
return "DIGEST-MD5";
}
/*public void challengeReceived1(String challenge) throws IOException {
// Build the challenge response stanza encoding the response text
StringBuilder stanza = new StringBuilder();
byte response[];
if (challenge != null) {
response = sc.evaluateChallenge(Base64.decode(challenge));
} else {
response = sc.evaluateChallenge(null);
}
String authenticationText="";
if (response != null) { // fix from 3.1.1
authenticationText = Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
if (authenticationText.equals("")) {
authenticationText = "=";
}
}
stanza.append("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">");
stanza.append(authenticationText);
stanza.append("</response>");
// Send the authentication to the server
getSASLAuthentication().send(stanza.toString());
}*/
public void challengeReceived(String challenge)
throws IOException {
byte response[];
if (challenge != null) {
response = sc.evaluateChallenge(Base64.decode(challenge));
} else {
response = sc.evaluateChallenge(new byte[0]);
}
Packet responseStanza;
if (response == null) {
responseStanza = new Response();
} else {
responseStanza = new Response(Base64.encodeBytes(response, Base64.DONT_BREAK_LINES));
}
getSASLAuthentication().send(responseStanza);
}
}
And Connection Function is :
try{
SASLAuthentication.registerSASLMechanism("DIGEST-MD5",MySASLDigestMD5Mechanism. class);
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com",5222);
config.setSASLAuthenticationEnabled(true);
config.setRosterLoadedAtLogin (true);
connection = new XMPPConnection(config);
connection.connect();
Log.d("Connect...", "Afetr Connect");
connection.login("username#chat.facebook.com", "password");
Log.d("done","XMPP client logged in");
}
catch(XMPPException ex)
{
Log.d("not done","in catchhhhhhhhh");
System.out.println(ex.getMessage ());
connection.disconnect();
}
}
but "After connect" it gone to the ctach and give me error like :
SASL authentication failed using mechanism DIGEST-MD5
I searched all blog and find same thing but i dont know what am i doing wrong here..
If is there any other way or solution to connect Facebook XMPP then please Help me
ASAP
Finally, thanks to the no.good.at.coding code and the suggestion of harism, I've been able to connect to the Facebook chat. This code is the Mechanism for the Asmack library (the Smack port for Android). For the Smack library is necessary to use the no.good.at.coding mechanism.
SASLXFacebookPlatformMechanism.java:
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import org.apache.harmony.javax.security.auth.callback.CallbackHandler;
import org.apache.harmony.javax.security.sasl.Sasl;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.sasl.SASLMechanism;
import org.jivesoftware.smack.util.Base64;
public class SASLXFacebookPlatformMechanism extends SASLMechanism
{
private static final String NAME = "X-FACEBOOK-PLATFORM";
private String apiKey = "";
private String applicationSecret = "";
private String sessionKey = "";
/** * Constructor. */
public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication)
{
super(saslAuthentication);
}
#Override
protected void authenticate() throws IOException, XMPPException
{
getSASLAuthentication().send(new AuthMechanism(NAME, ""));
}
#Override
public void authenticate(String apiKeyAndSessionKey, String host, String applicationSecret) throws IOException, XMPPException
{
if (apiKeyAndSessionKey == null || applicationSecret == null)
{
throw new IllegalArgumentException("Invalid parameters");
}
String[] keyArray = apiKeyAndSessionKey.split("\\|", 2);
if (keyArray.length < 2)
{
throw new IllegalArgumentException( "API key or session key is not present"); }
this.apiKey = keyArray[0];
this.applicationSecret = applicationSecret;
this.sessionKey = keyArray[1];
this.authenticationId = sessionKey;
this.password = applicationSecret;
this.hostname = host;
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,this);
authenticate();
}
#Override
public void authenticate(String username, String host, CallbackHandler cbh)throws IOException, XMPPException
{
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props,cbh);
authenticate();
} #Override protected String getName()
{
return NAME;
}
#Override
public void challengeReceived(String challenge) throws IOException
{
byte[] response = null;
if (challenge != null)
{
String decodedChallenge = new String(Base64.decode(challenge));
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
long callId = new GregorianCalendar().getTimeInMillis();
String sig = "api_key=" + apiKey + "call_id=" + callId + "method=" + method + "nonce=" + nonce + "session_key=" + sessionKey + "v=" + version + applicationSecret;
try
{
sig = md5(sig);
}
catch (NoSuchAlgorithmException e)
{
throw new IllegalStateException(e);
}
String composedResponse = "api_key=" + URLEncoder.encode(apiKey, "utf-8") + "&call_id=" + callId + "&method="+ URLEncoder.encode(method, "utf-8") + "&nonce="+ URLEncoder.encode(nonce, "utf-8")+ "&session_key="+ URLEncoder.encode(sessionKey, "utf-8") + "&v="+ URLEncoder.encode(version, "utf-8") + "&sig="+ URLEncoder.encode(sig, "utf-8");response = composedResponse.getBytes("utf-8");
}
String authenticationText = "";
if (response != null)
{
authenticationText = Base64.encodeBytes(response, Base64.DONT_BREAK_LINES);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
private Map<String, String> getQueryMap(String query)
{
Map<String, String> map = new HashMap<String, String>();
String[] params = query.split("\\&");
for (String param : params)
{
String[] fields = param.split("=", 2);
map.put(fields[0], (fields.length > 1 ? fields[1] : null));
}
return map;
}
private String md5(String text) throws NoSuchAlgorithmException,UnsupportedEncodingException
{
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text.getBytes("utf-8"), 0, text.length());
return convertToHex(md.digest());
}
private String convertToHex(byte[] data)
{
StringBuilder buf = new StringBuilder();
int len = data.length;
for (int i = 0; i < len; i++)
{
int halfByte = (data[i] >>> 4) & 0xF;
int twoHalfs = 0;
do
{
if (0 <= halfByte && halfByte <= 9)
{
buf.append((char) ('0' + halfByte));
}
else
{
buf.append((char) ('a' + halfByte - 10));
}
halfByte = data[i] & 0xF;
}
while (twoHalfs++ < 1);
}
return buf.toString();
}
}
To use it:
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222);
config.setSASLAuthenticationEnabled(true);
XMPPConnection xmpp = new XMPPConnection(config);
try
{
SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM", SASLXFacebookPlatformMechanism.class);
SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
xmpp.connect();
xmpp.login(apiKey + "|" + sessionKey, sessionSecret, "Application");
}
catch (XMPPException e)
{
xmpp.disconnect();
e.printStackTrace();
}
apiKey is the API key given in the application settings page in Facebook. sessionKey is the second part of the access token. If the token is in this form, AAA|BBB|CCC, the BBB is the session key. sessionSecret is obtained using the old REST API with the method auth.promoteSession. To use it, it's needed to make a Http get to this url:
https://api.facebook.com/method/auth.promoteSession?access_token=yourAccessToken
Despite of the Facebook Chat documentation says that it's needed to use your application secret key, only when I used the key that returned that REST method I was able to make it works. To make that method works, you have to disable the Disable Deprecated Auth Methods option in the Advance tab in your application settings.
I solved this problem. I find solution that http://community.igniterealtime.org/thread/41080
Jerry Magill wrote this...
import java.io.IOException;
import java.util.HashMap;
import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.Sasl;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.sasl.SASLMechanism;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.Base64;
public class MySASLDigestMD5Mechanism extends SASLMechanism
{
public MySASLDigestMD5Mechanism(SASLAuthentication saslAuthentication)
{
super(saslAuthentication);
}
protected void authenticate()
throws IOException, XMPPException
{
String mechanisms[] = {
getName()
};
java.util.Map props = new HashMap();
sc = Sasl.createSaslClient(mechanisms, null, "xmpp", hostname, props, this);
super.authenticate();
}
public void authenticate(String username, String host, String password)
throws IOException, XMPPException
{
authenticationId = username;
this.password = password;
hostname = host;
String mechanisms[] = {
getName()
};
java.util.Map props = new HashMap();
sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this);
super.authenticate();
}
public void authenticate(String username, String host, CallbackHandler cbh)
throws IOException, XMPPException
{
String mechanisms[] = {
getName()
};
java.util.Map props = new HashMap();
sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, cbh);
super.authenticate();
}
protected String getName()
{
return "DIGEST-MD5";
}
public void challengeReceived(String challenge)
throws IOException
{
//StringBuilder stanza = new StringBuilder();
byte response[];
if(challenge != null)
response = sc.evaluateChallenge(Base64.decode(challenge));
else
//response = sc.evaluateChallenge(null);
response = sc.evaluateChallenge(new byte[0]);
//String authenticationText = "";
Packet responseStanza;
//if(response != null)
//{
//authenticationText = Base64.encodeBytes(response, 8);
//if(authenticationText.equals(""))
//authenticationText = "=";
if (response == null){
responseStanza = new Response();
} else {
responseStanza = new Response(Base64.encodeBytes(response,Base64.DONT_BREAK_LINES));
}
//}
//stanza.append("<response xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\">");
//stanza.append(authenticationText);
//stanza.append("</response>");
//getSASLAuthentication().send(stanza.toString());
getSASLAuthentication().send(responseStanza);
}
}
It is then called thus from the JabberSmackAPI:
public void login(String userName, String password) throws XMPPException
{
SASLAuthentication.registerSASLMechanism("DIGEST-MD5",MySASLDigestMD5Mechanism. class);
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com",5222);
config.setSASLAuthenticationEnabled(true);
config.setRosterLoadedAtLogin (true);
connection = new XMPPConnection(config);
connection.connect();
connection.login(userName, password);
}
I want to fetch the emails of my gmail account from Java code. How can I go about doing this?
Here is the Refresh Working Code, that Displays the Email msgs in the console in a proper format along with the Attachments also being Downloaded....
import com.sun.mail.pop3.POP3Folder;
import com.sun.mail.pop3.POP3SSLStore;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.MimeBodyPart;
public class MailfetchingPop3
{
private Session session;
private POP3SSLStore store;
private String username;
private String password;
private POP3Folder folder;
public static String numberOfFiles = null;
public static int toCheck = 0;
public static Writer output = null;
URLName url;
public static String receiving_attachments="C:\\download";
public MailfetchingPop3()
{
session = null;
store = null;
}
public void setUserPass(String username, String password)
{
this.username = username;
this.password = password;
}
public void connect()
throws Exception
{
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
url = new URLName("pop3", "pop.gmail.com", 995, "", username, password);
session = Session.getInstance(pop3Props, null);
store = new POP3SSLStore(session, url);
store.connect();
}
public void openFolder(String folderName)
throws Exception
{
folder = (POP3Folder)store.getFolder(folderName);
System.out.println((new StringBuilder("For test----")).append
(folder.getParent().getFullName()).toString());
if(folder == null)
throw new Exception("Invalid folder");
try
{
folder.open(2);
System.out.println((new StringBuilder("Folder name----")).append
(folder.getFullName()).toString());
}
catch(Exception ex)
{
System.out.println((new StringBuilder("Folder Opening Exception..")).append(ex).toString());
}
}
public void closeFolder()
throws Exception
{
folder.close(false);
}
public int getMessageCount()
throws Exception
{
return folder.getMessageCount();
}
public int getNewMessageCount()
throws Exception
{
return folder.getNewMessageCount();
}
public void disconnect()
throws Exception
{
store.close();
}
public void printAllMessages()
throws Exception
{
Message msgs[] = folder.getMessages();
FetchProfile fp = new FetchProfile();
folder.fetch(msgs, fp);
for(int i = 0; i < msgs.length; i++){
Message message = msgs[i];
dumpEnvelope(msgs[i]);
System.out.println("==============================");
System.out.println("Email #" + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
}
public static int saveFile(File saveFile, Part part) throws Exception {
BufferedOutputStream bos = new BufferedOutputStream( new
FileOutputStream(saveFile) );
byte[] buff = new byte[2048];
InputStream is = part.getInputStream();
int ret = 0, count = 0;
while( (ret = is.read(buff)) > 0 ){
bos.write(buff, 0, ret);
count += ret;
}
bos.close();
is.close();
return count;
}
private static void dumpEnvelope(Message m) throws Exception
{
String body="";
String path="";
int size=0;
Object content = m.getContent();
if(content instanceof String){
body = (String)content;
}
else if(content instanceof Multipart)
{
Multipart mp = (Multipart)content;
for (int j=0; j < mp.getCount(); j++)
{
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
//System.out.println("test disposition---->>"+disposition);
if (disposition == null) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart)part;
if (mbp.isMimeType("text/plain")) {
body += mbp.getContent().toString();
}
else if (mbp.isMimeType("TEXT/HTML")) {
body += mbp.getContent().toString();
}
else {
//unknown
}
} else if ((disposition != null) &&
(disposition.equals(Part.ATTACHMENT) || disposition.equals
(Part.INLINE) || disposition.equals("ATTACHMENT") || disposition.equals
("INLINE")) )
{
// Check if plain
MimeBodyPart mbp = (MimeBodyPart)part;
if (mbp.isMimeType("text/plain")) {
body += (String)mbp.getContent();
}
else if (mbp.isMimeType("TEXT/HTML")) {
body += mbp.getContent().toString();
}
else {
File savedir = new File(receiving_attachments);
savedir.mkdirs();
File savefile = new File(savedir+"\\"+part.getFileName());
path = savefile.getAbsolutePath();
size = saveFile( savefile, part);
}
}
}
}
}
public static void main(String args[])
{
try
{
MailfetchingPop3 gmail = new MailfetchingPop3();
gmail.setUserPass("your-gmail-username", "your-gmail-password");
gmail.connect();
gmail.openFolder("INBOX");
gmail.printAllMessages();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(-1);
}
}
}
Another option: if you don't mind it being a Gmail-specific solution, note that Gmail also provides an RSS feed to your mailbox, which you can then access with normal XML processing APIs.
Gmail uses IMAP, which Javamail can use. Try to use that in an implementation, and if you get stuck, post some more specific questions here.
Here is the code which fetch mail along with it's attachments (if any) from a gmail account using POST OFFICE PROTOCOL (pop3) .
import com.sun.mail.pop3.POP3Folder;
import com.sun.mail.pop3.POP3SSLStore;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.MimeBodyPart;
public class MailfetchingPop3
{
private Session session;
private POP3SSLStore store;
private String username;
private String password;
private POP3Folder folder;
public static String numberOfFiles = null;
public static int toCheck = 0;
public static Writer output = null;
URLName url;
public static String receiving_attachments="C:\\download";
public MailfetchingPop3()
{
session = null;
store = null;
}
public void setUserPass(String username, String password)
{
this.username = username;
this.password = password;
}
public void connect()
throws Exception
{
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties pop3Props = new Properties();
pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
pop3Props.setProperty("mail.pop3.port", "995");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
url = new URLName("pop3", "pop.gmail.com", 995, "", username, password);
session = Session.getInstance(pop3Props, null);
store = new POP3SSLStore(session, url);
store.connect();
}
public void openFolder(String folderName)
throws Exception
{
folder = (POP3Folder)store.getFolder(folderName);
System.out.println((new StringBuilder("For test----")).append(folder.getParent().getFullName()).toString());
if(folder == null)
throw new Exception("Invalid folder");
try
{
folder.open(2);
System.out.println((new StringBuilder("Folder name----")).append(folder.getFullName()).toString());
}
catch(Exception ex)
{
System.out.println((new StringBuilder("Folder Opening Exception..")).append(ex).toString());
}
}
public void closeFolder()
throws Exception
{
folder.close(false);
}
public int getMessageCount()
throws Exception
{
return folder.getMessageCount();
}
public int getNewMessageCount()
throws Exception
{
return folder.getNewMessageCount();
}
public void disconnect()
throws Exception
{
store.close();
}
public void printAllMessages()
throws Exception
{
Message msgs[] = folder.getMessages();
FetchProfile fp = new FetchProfile();
folder.fetch(msgs, fp);
for(int i = 0; i < msgs.length; i++)
dumpEnvelope(msgs[i]);
}
public static int saveFile(File saveFile, Part part) throws Exception {
BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(saveFile) );
byte[] buff = new byte[2048];
InputStream is = part.getInputStream();
int ret = 0, count = 0;
while( (ret = is.read(buff)) > 0 ){
bos.write(buff, 0, ret);
count += ret;
}
bos.close();
is.close();
return count;
}
private static void dumpEnvelope(Message m) throws Exception
{
String body="";
String path="";
int size=0;
Object content = m.getContent();
if(content instanceof String){
body = (String)content;
}
else if(content instanceof Multipart)
{
Multipart mp = (Multipart)content;
for (int j=0; j < mp.getCount(); j++)
{
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
//System.out.println("test disposition---->>"+disposition);
if (disposition == null) {
// Check if plain
MimeBodyPart mbp = (MimeBodyPart)part;
if (mbp.isMimeType("text/plain")) {
body += mbp.getContent().toString();
}
else if (mbp.isMimeType("TEXT/HTML")) {
body += mbp.getContent().toString();
}
else {
//unknown
}
} else if ((disposition != null) &&
(disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE) || disposition.equals("ATTACHMENT") || disposition.equals("INLINE")) )
{
// Check if plain
MimeBodyPart mbp = (MimeBodyPart)part;
if (mbp.isMimeType("text/plain")) {
body += (String)mbp.getContent();
}
else if (mbp.isMimeType("TEXT/HTML")) {
body += mbp.getContent().toString();
}
else {
File savedir = new File(receiving_attachments);
savedir.mkdirs();
File savefile = new File(savedir+"\\"+part.getFileName());
path = savefile.getAbsolutePath();
size = saveFile( savefile, part);
}
}
}
}
}
public static void main(String args[])
{
try
{
MailfetchingPop3 gmail = new MailfetchingPop3();
gmail.setUserPass("your_gmail_Id", "your_gmail_mail_id_password");
gmail.connect();
gmail.openFolder("INBOX");
gmail.printAllMessages();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(-1);
}
}
}
To run this java class you need to download javamail.jar and activation.jar