GetGravatarOperation.java
/*
* Copyright © 2011 Nokia Corporation. All rights reserved.
* Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation.
* Oracle and Java are trademarks or registered trademarks of Oracle and/or its
* affiliates. Other product and company names mentioned herein may be trademarks
* or trade names of their respective owners.
* See LICENSE.TXT for license information.
*/
package com.nokia.example.wordpress.networking;
import java.security.MessageDigest;
/**
* Operation for loading gravatar icons from www.gravatar.com.
*/
public class GetGravatarOperation extends NetworkOperation {
/**
* Listener interface
*/
public interface Listener {
/**
* Called when a gravatar has been loaded.
* @param email Email address identifying the gravatar
* @param data Image data
*/
public void gravatarReceived(String email, byte[] data);
}
String email;
Listener listener;
/**
* Constructor
* @param listener
* @param email Email identifying the gravatar to be loaded
*/
public GetGravatarOperation(Listener listener, String email) {
this.listener = listener;
this.email = email;
}
/**
* Starts the operation.
*/
public void start() {
StringBuffer hashcode = new StringBuffer();
try {
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
byte[] emailbytes = email.getBytes();
digest.update(emailbytes, 0, emailbytes.length);
byte[] output = new byte[128];
int out = digest.digest(output, 0, output.length);
for (int i = 0; i < out; i++) {
int num = output[i] & 0xff;
if (num < 0x10) {
hashcode.append("0");
}
hashcode.append(Integer.toHexString(num));
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
// Request a smaller image than default, which is 80x80
String url = "http://www.gravatar.com/avatar/" + hashcode + "?s=64.jpg";
System.out.println("Gravatar url for " + email + " is " + url);
Network nw = new Network(this);
nw.startHttpGet(url);
}
/**
* Calls the listener, no parsing needed here.
*/
public void networkHttpGetResponse(byte[] data) {
listener.gravatarReceived(email, data);
}
}