Java源码示例:com.codename1.io.NetworkManager
示例1
private void showFacebookUser(String token){
ConnectionRequest req = new ConnectionRequest();
req.setPost(false);
req.setUrl("https://graph.facebook.com/v2.3/me");
req.addArgumentNoEncoding("access_token", token);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req);
byte[] data = req.getResponseData();
JSONParser parser = new JSONParser();
Map map = null;
try {
map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
String name = (String) map.get("name");
d.dispose();
Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), "https://graph.facebook.com/v2.3/me/picture?access_token=" + token);
userForm.show();
}
示例2
private void showGoogleUser(String token){
ConnectionRequest req = new ConnectionRequest();
req.addRequestHeader("Authorization", "Bearer " + token);
req.setUrl("https://www.googleapis.com/plus/v1/people/me");
req.setPost(false);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req);
d.dispose();
byte[] data = req.getResponseData();
JSONParser parser = new JSONParser();
Map map = null;
try {
map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
String name = (String) map.get("displayName");
Map im = (Map) map.get("image");
String url = (String) im.get("url");
Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), url);
userForm.show();
}
示例3
/**
* @inheritDoc
*/
public int getAPType(String id) {
Vector v = getValidSBEntries();
for (int iter = 0; iter < v.size(); iter++) {
ServiceRecord r = (ServiceRecord) v.elementAt(iter);
if (("" + r.getUid()).equals(id)) {
if (r.getUid().toLowerCase().indexOf("wifi") > -1) {
return NetworkManager.ACCESS_POINT_TYPE_WLAN;
}
// wap2
if (r.getCid().toLowerCase().indexOf("wptcp") > -1) {
return NetworkManager.ACCESS_POINT_TYPE_NETWORK3G;
}
return NetworkManager.ACCESS_POINT_TYPE_UNKNOWN;
}
}
return NetworkManager.ACCESS_POINT_TYPE_UNKNOWN;
}
示例4
@Override
protected boolean validateToken(String token) {
//make a call to the API if the return value is 40X the token is not
//valid anymore
final boolean[] retval = new boolean[1];
retval[0] = true;
ConnectionRequest req = new ConnectionRequest() {
@Override
protected void handleErrorResponseCode(int code, String message) {
//access token not valid anymore
if (code >= 400 && code <= 410) {
retval[0] = false;
return;
}
super.handleErrorResponseCode(code, message);
}
};
req.setPost(false);
req.setUrl("https://www.googleapis.com/plus/v1/people/me");
req.addRequestHeader("Authorization", "Bearer " + token);
NetworkManager.getInstance().addToQueueAndWait(req);
return retval[0];
}
示例5
@Override
protected boolean validateToken(String token) {
//make a call to the API if the return value is 40X the token is not
//valid anymore
final boolean[] retval = new boolean[1];
retval[0] = true;
ConnectionRequest req = new ConnectionRequest() {
@Override
protected void handleErrorResponseCode(int code, String message) {
//access token not valid anymore
if (code >= 400 && code <= 410) {
retval[0] = false;
return;
}
super.handleErrorResponseCode(code, message);
}
};
req.setPost(false);
req.setUrl("https://graph.facebook.com/v2.4/me");
req.addArgumentNoEncoding("access_token", token);
NetworkManager.getInstance().addToQueueAndWait(req);
return retval[0];
}
示例6
/**
* This method returns immediately and will call the callback when it returns with
* the FaceBook Object data.
*
* @param faceBookId the object id that we would like to query
* @param callback the callback that should be updated when the data arrives
*/
public void getFaceBookObject(String faceBookId, final ActionListener callback) throws IOException {
checkAuthentication();
final FacebookRESTService con = new FacebookRESTService(token, faceBookId, "", false);
con.addResponseListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (!con.isAlive()) {
return;
}
if (callback != null) {
callback.actionPerformed(evt);
}
}
});
if (slider != null) {
SliderBridge.bindProgress(con, slider);
}
for (int i = 0; i < responseCodeListeners.size(); i++) {
con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
}
current = con;
NetworkManager.getInstance().addToQueue(con);
}
示例7
/**
* Get a list of FaceBook objects for a given id
*
* @param faceBookId the id to preform the query upon
* @param itemsConnection the type of the query
* @param feed
* @param params
* @param callback the callback that should be updated when the data arrives
*/
public void getFaceBookObjectItems(String faceBookId, String itemsConnection,
final DefaultListModel feed, Hashtable params, final ActionListener callback) throws IOException {
checkAuthentication();
final FacebookRESTService con = new FacebookRESTService(token, faceBookId, itemsConnection, false);
con.setResponseDestination(feed);
con.addResponseListener(new Listener(con, callback));
if (params != null) {
Enumeration keys = params.keys();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
con.addArgument(key, (String) params.get(key));
}
}
if (slider != null) {
SliderBridge.bindProgress(con, slider);
}
for (int i = 0; i < responseCodeListeners.size(); i++) {
con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
}
current = con;
NetworkManager.getInstance().addToQueue(con);
}
示例8
/**
* Post a message on the users wall
*
* @param userId the userId
* @param message the message to post
*/
public void postOnWall(String userId, String message, ActionListener callback) throws IOException {
checkAuthentication();
FacebookRESTService con = new FacebookRESTService(token, userId, FacebookRESTService.FEED, true);
con.addArgument("message", "" + message);
con.addResponseListener(new Listener(con, callback));
if (slider != null) {
SliderBridge.bindProgress(con, slider);
}
for (int i = 0; i < responseCodeListeners.size(); i++) {
con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
}
current = con;
NetworkManager.getInstance().addToQueueAndWait(con);
}
示例9
/**
* Post a comment on a given post
*
* @param postId the post id
* @param message the message to post
*/
public void postComment(String postId, String message, ActionListener callback) throws IOException {
checkAuthentication();
FacebookRESTService con = new FacebookRESTService(token, postId, FacebookRESTService.COMMENTS, true);
con.addResponseListener(new Listener(con, callback));
con.addArgument("message", "" + message);
if (slider != null) {
SliderBridge.bindProgress(con, slider);
}
for (int i = 0; i < responseCodeListeners.size(); i++) {
con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
}
current = con;
NetworkManager.getInstance().addToQueueAndWait(con);
}
示例10
/**
* Post a note onto the users wall
*
* @param userId the userId
* @param message the message to post
*/
public void createNote(String userId, String subject, String message, ActionListener callback) throws IOException {
checkAuthentication();
FacebookRESTService con = new FacebookRESTService(token, userId, FacebookRESTService.NOTES, true);
con.addResponseListener(new Listener(con, callback));
con.addArgument("subject","" + subject);
con.addArgument("message", "" + message);
if (slider != null) {
SliderBridge.bindProgress(con, slider);
}
for (int i = 0; i < responseCodeListeners.size(); i++) {
con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
}
current = con;
System.out.println(con.getUrl());
NetworkManager.getInstance().addToQueueAndWait(con);
}
示例11
private int refreshImpl(CloudObject[] objects, CloudResponse<Integer> response) {
RefreshConnection refreshRequest = new RefreshConnection();
refreshRequest.objects = objects;
refreshRequest.response = response;
refreshRequest.setPost(true);
refreshRequest.setUrl(SERVER_URL + "/objStoreRefresh");
for(int iter = 0 ; iter < objects.length ; iter++) {
objects[iter].setStatus(CloudObject.STATUS_REFRESH_IN_PROGRESS);
refreshRequest.addArgument("i" + iter, objects[iter].getCloudId());
refreshRequest.addArgument("m" + iter, "" + objects[iter].getLastModified());
}
refreshRequest.addArgument("t", CloudPersona.getCurrentPersona().getToken());
refreshRequest.addArgument("pk", Display.getInstance().getProperty("package_name", null));
refreshRequest.addArgument("bb", Display.getInstance().getProperty("built_by_user", null));
// async code
if(response != null) {
NetworkManager.getInstance().addToQueue(refreshRequest);
return -1;
}
NetworkManager.getInstance().addToQueueAndWait(refreshRequest);
return refreshRequest.returnValue;
}
示例12
/**
* Deletes a file from the cloud storage
*
* @param fileId the file id to delete
* @return true if the operation was successful
* @deprecated this API is currently deprecated due to Googles cloud storage deprection
*/
public boolean deleteCloudFile(String fileId) {
if(CloudPersona.getCurrentPersona().getToken() == null) {
CloudPersona.createAnonymous();
}
ConnectionRequest req = new ConnectionRequest();
req.setPost(false);
req.setFailSilently(true);
req.setUrl(SERVER_URL + "/fileStoreDelete");
req.addArgument("i", fileId);
req.addArgument("t", CloudPersona.getCurrentPersona().getToken());
NetworkManager.getInstance().addToQueueAndWait(req);
if(req.getResponseCode() == 200) {
return new String(req.getResponseData()).equals("OK");
}
return false;
}
示例13
/**
* Commit works synchronously and returns one of the return codes above to indicate
* the status.
* @return status code from the constants in this class
*/
public synchronized int commit() {
if(storageQueue.size() > 0) {
if(CloudPersona.getCurrentPersona().getToken() == null) {
CloudPersona.createAnonymous();
}
StorageRequest req = new StorageRequest();
req.setContentType("multipart/form-data");
req.setUrl(SERVER_URL + "/objStoreCommit");
req.setPost(true);
NetworkManager.getInstance().addToQueueAndWait(req);
int i = req.getReturnCode();
if(i == RETURN_CODE_SUCCESS) {
storageQueue.clear();
Storage.getInstance().deleteStorageFile("CN1StorageQueue");
}
return i;
}
return RETURN_CODE_EMPTY_QUEUE;
}
示例14
/**
* Logs in to twitter as an application
*
* @param consumerKey the key to login with
* @param consumerSecret the secret to to login with
* @return the authorization token
*/
public static String initToken(String consumerKey, String consumerSecret) {
ConnectionRequest auth = new ConnectionRequest() {
protected void readResponse(InputStream input) throws IOException {
JSONParser p = new JSONParser();
Hashtable h = p.parse(new InputStreamReader(input));
authToken = (String)h.get("access_token");
if(authToken == null) {
return;
}
}
};
auth.setPost(true);
auth.setUrl("https://api.twitter.com/oauth2/token");
// YOU MUST CHANGE THIS IF YOU BUILD YOUR OWN APP
String encoded = Base64.encodeNoNewline((consumerKey + ":" + consumerSecret).getBytes());
auth.addRequestHeader("Authorization", "Basic " + encoded);
auth.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
auth.addArgument("grant_type", "client_credentials");
NetworkManager.getInstance().addToQueueAndWait(auth);
return authToken;
}
示例15
/**
* Checks that the cached data is up to date and if a newer version exits it updates the data in place
*
* @param d the data to check
* @param callback optional callback to be invoked on request completion
*/
public static void updateData(CachedData d, ActionListener callback) {
if(d.isFetching()) {
return;
}
d.setFetching(true);
CachedDataService c = new CachedDataService();
c.setUrl(d.getUrl());
c.setPost(false);
if(callback != null) {
c.addResponseListener(callback);
}
if(d.getModified() != null && d.getModified().length() > 0) {
c.addRequestHeader("If-Modified-Since", d.getModified());
if(d.getEtag() != null) {
c.addRequestHeader("If-None-Match", d.getEtag());
}
}
NetworkManager.getInstance().addToQueue(c);
}
示例16
/**
* Binds the progress UI to the completion of this request
*
* @param title the title of the progress dialog
* @param request the network request pending
* @param showPercentage shows percentage on the progress bar
*/
public Progress(String title, ConnectionRequest request, boolean showPercentage) {
super(title);
this.request = request;
SliderBridge b = new SliderBridge(request);
b.setRenderPercentageOnTop(showPercentage);
b.setRenderValueOnTop(true);
setLayout(new BoxLayout(BoxLayout.Y_AXIS));
addComponent(b);
Command cancel = new Command(UIManager.getInstance().localize("cancel", "Cancel"));
if(Display.getInstance().isTouchScreenDevice() || getSoftButtonCount() < 2) {
// if this is a touch screen device or a blackberry use a centered button
Button btn = new Button(cancel);
Container cnt = new Container(new FlowLayout(CENTER));
cnt.addComponent(btn);
addComponent(cnt);
} else {
// otherwise use a command
addCommand(cancel);
}
setDisposeWhenPointerOutOfBounds(false);
setAutoDispose(false);
NetworkManager.getInstance().addProgressListener(this);
}
示例17
/**
* Send the request to the server, will only work once. This is called implicitly
* when the list is initialized
*/
public void sendRequest() {
if(service == null) {
service = new RSSService(url, limit);
if(iconPlaceholder != null) {
service.setIconPlaceholder(iconPlaceholder);
}
service.addResponseListener(new EventHandler());
if(blockList) {
Progress p = new Progress(progressTitle, service, displayProgressPercentage);
p.setAutoShow(true);
p.setDisposeOnCompletion(true);
}
setHint(progressTitle);
NetworkManager.getInstance().addToQueue(service);
}
}
示例18
private void showFacebookUser(String token){
ConnectionRequest req = new ConnectionRequest();
req.setPost(false);
req.setUrl("https://graph.facebook.com/v2.3/me");
req.addArgumentNoEncoding("access_token", token);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req);
byte[] data = req.getResponseData();
JSONParser parser = new JSONParser();
Map map = null;
try {
map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
String name = (String) map.get("name");
d.dispose();
Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), "https://graph.facebook.com/v2.3/me/picture?access_token=" + token);
userForm.show();
}
示例19
private void showGoogleUser(String token){
ConnectionRequest req = new ConnectionRequest();
req.addRequestHeader("Authorization", "Bearer " + token);
req.setUrl("https://www.googleapis.com/plus/v1/people/me");
req.setPost(false);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req);
d.dispose();
byte[] data = req.getResponseData();
JSONParser parser = new JSONParser();
Map map = null;
try {
map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
String name = (String) map.get("displayName");
Map im = (Map) map.get("image");
String url = (String) im.get("url");
Form userForm = new UserForm(name, (EncodedImage) theme.getImage("user.png"), url);
userForm.show();
}
示例20
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
if (currRequest != null) {
//currRequest.kill();
}
ConnectionRequest r = new ConnectionRequest();
currRequest = r;
r.setPost(false);
r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
r.addArgument("key", apiKey.getText());
r.addArgument("input", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
String[] res = Result.fromContent(result).getAsStringArray("//description");
return res;
}
} catch(Exception err) {
Log.e(err);
}
return null;
}
示例21
@Override
public void fetchData(String token, Runnable callback) {
this.token = token;
ConnectionRequest req = new ConnectionRequest() {
@Override
protected void readResponse(InputStream input) throws IOException {
JSONParser parser = new JSONParser();
Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
name = (String) parsed.get("name");
id = (String) parsed.get("id");
}
@Override
protected void postResponse() {
callback.run();
}
@Override
protected void handleErrorResponseCode(int code, String message) {
//access token not valid anymore
if(code >= 400 && code <= 410){
doLogin(FacebookConnect.getInstance(), FacebookData.this, true);
return;
}
super.handleErrorResponseCode(code, message);
}
};
req.setPost(false);
req.setUrl("https://graph.facebook.com/v2.4/me");
req.addArgumentNoEncoding("access_token", token);
NetworkManager.getInstance().addToQueue(req);
}
示例22
@Override
public void fetchData(String token, Runnable callback) {
this.callback = callback;
addRequestHeader("Authorization", "Bearer " + token);
setUrl("https://www.googleapis.com/plus/v1/people/me");
setPost(false);
NetworkManager.getInstance().addToQueue(this);
}
示例23
@Override
public void fetchData(String token, Runnable callback) {
this.callback = callback;
addRequestHeader("Authorization", "Bearer " + token);
setUrl("https://www.googleapis.com/plus/v1/people/me");
setPost(false);
NetworkManager.getInstance().addToQueue(this);
}
示例24
private Command createPictureCommand(final Container grid) {
return new Command("Take Picture") {
public void actionPerformed(ActionEvent ev) {
String picture = Capture.capturePhoto(1024, -1);
if(picture == null) {
return;
}
MultipartRequest mp = new MultipartRequest() {
private long key;
@Override
protected void readResponse(InputStream input) throws IOException {
DataInputStream di = new DataInputStream(input);
key = di.readLong();
}
@Override
protected void postResponse() {
final Button btn = createImageButton(key, grid, imageList.getSize());
imageList.addImageId(key);
grid.addComponent(0, btn);
if(!animating) {
animating = true;
grid.animateLayoutAndWait(400);
animating = false;
}
}
};
mp.setUrl(UPLOAD_URL);
try {
mp.addData("i", picture, "image/jpeg");
mp.addArgument("p", "Data;More data");
NetworkManager.getInstance().addToQueue(mp);
} catch(IOException err) {
err.printStackTrace();
}
}
};
}
示例25
private String getDirections(Coord origin, Coord destination) throws IOException {
ConnectionRequest req = new ConnectionRequest();
req.setUrl("http://maps.googleapis.com/maps/api/directions/json");
req.setUserAgent("Opera/8.0 (Windows NT 5.1; U; en)");
req.setPost(false);
req.addArgument("origin", "" + origin.getLatitude() + " " + origin.getLongitude());
req.addArgument("destination", "" + destination.getLatitude() + " " + destination.getLongitude());
req.addArgument("mode", "walking");
req.addArgument("sensor", "false");
NetworkManager.getInstance().addToQueueAndWait(req);
JSONParser p = new JSONParser();
Hashtable h = p.parse(new InputStreamReader(new ByteArrayInputStream(req.getResponseData())));
System.out.println(h.toString());
return ((Hashtable) ((Hashtable) ((Vector) h.get("routes")).firstElement()).get("overview_polyline")).get("points").toString();
}
示例26
@Override
protected void onMain_ImportJSONAction(final Component c, ActionEvent event) {
ConnectionRequest cr = new ConnectionRequest() {
protected void readResponse(InputStream is) throws IOException {
JSONParser p = new JSONParser();
Hashtable h = p.parse(new InputStreamReader(is));
Hashtable<Object, Hashtable<String, String>> todoHash = (Hashtable<Object, Hashtable<String, String>>)h.get("todo");
Container tasksContainer = findTasksContainer(c.getParent());
for(Hashtable<String, String> values : todoHash.values()) {
String photoURL = values.get("photoURL");
String title = values.get("title");
MultiButton mb = createEntry(values);
todos.add(values);
tasksContainer.addComponent(mb);
if(photoURL != null) {
ImageDownloadService.createImageToStorage(photoURL, mb.getIconComponent(),
title, new Dimension(imageWidth, imageHeight));
}
}
Storage.getInstance().writeObject("todos", todos);
findTabs1(c.getParent()).setSelectedIndex(0);
tasksContainer.animateLayout(500);
}
};
InfiniteProgress i = new InfiniteProgress();
Dialog blocking = i.showInifiniteBlocking();
cr.setDisposeOnCompletion(blocking);
cr.setPost(false);
cr.setUrl("https://dl.dropbox.com/u/57067724/cn1/Course%20Material/webservice/NetworkingChapter.json");
NetworkManager.getInstance().addToQueue(cr);
}
示例27
private void killNetworkAccess() {
Enumeration e = NetworkManager.getInstance().enumurateQueue();
while (e.hasMoreElements()) {
ConnectionRequest r = (ConnectionRequest) e.nextElement();
r.kill();
}
}
示例28
/**
* @inheritDoc
*/
public void setCurrentAccessPoint(String id) {
currentAccessPoint = id;
int t = getAPType(id);
deviceSide = t == NetworkManager.ACCESS_POINT_TYPE_NETWORK3G ||
t == NetworkManager.ACCESS_POINT_TYPE_NETWORK2G ||
t == NetworkManager.ACCESS_POINT_TYPE_WLAN;
}
示例29
/**
* This method returns immediately and will call the callback when it returns with
* the FaceBook Object data.
*
* @param faceBookId the object id that we would like to query
* @param callback the callback that should be updated when the data arrives
* @param needToken if true authentication is being checked
*/
public void getFaceBookObject(String faceBookId, final ActionListener callback, boolean needToken, boolean async) throws IOException {
if(needToken){
checkAuthentication();
}
final FacebookRESTService con = new FacebookRESTService(token, faceBookId, "", false);
con.addResponseListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (!con.isAlive()) {
return;
}
if (callback != null) {
callback.actionPerformed(evt);
}
}
});
if (slider != null) {
SliderBridge.bindProgress(con, slider);
}
for (int i = 0; i < responseCodeListeners.size(); i++) {
con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
}
current = con;
if(async){
NetworkManager.getInstance().addToQueue(con);
}else{
NetworkManager.getInstance().addToQueueAndWait(con);
}
}
示例30
/**
* Post a message on the users wall
*
* @param userId the userId
* @param message the message to post
* @param name
* @param link
* @param description
* @param picture
* @param caption
*/
public void postOnWall(String userId, String message, String name, String link,
String description, String picture, String caption, ActionListener callback) throws IOException {
checkAuthentication();
FacebookRESTService con = new FacebookRESTService(token, userId, FacebookRESTService.FEED, true);
if (message != null) {
con.addArgument("message", message);
}
if (name != null) {
con.addArgument("name", name);
}
if (link != null) {
con.addArgument("link", link);
}
if (description != null) {
con.addArgument("description", description);
}
if (picture != null) {
con.addArgument("picture", picture);
}
if (caption != null) {
con.addArgument("caption", caption);
}
con.addResponseListener(new Listener(con, callback));
if (slider != null) {
SliderBridge.bindProgress(con, slider);
}
for (int i = 0; i < responseCodeListeners.size(); i++) {
con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
}
current = con;
NetworkManager.getInstance().addToQueueAndWait(con);
}