Java tutorial
/* * Author: cooperok * cooperok.so@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cooperok.socialuser.vk; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Scanner; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreProtocolPNames; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.preference.PreferenceManager; import com.cooperok.socialuser.SocialDataLoadListener; import com.cooperok.socialuser.SocialUserInfo; import com.cooperok.socialuser.SocialUserInterface; import com.cooperok.socialuser.User; import com.cooperok.socialuser.callbacks.LikeCallback; import com.cooperok.socialuser.callbacks.LikeGroupCallback; import com.cooperok.socialuser.callbacks.PostImageCallback; import com.perm.kate.api.Api; import com.perm.kate.api.KException; import com.perm.kate.api.Photo; public class VkAccount implements SocialUserInterface { private String mAccessToken; private int mSocialType; private VkUserInfo mUserInfo; private SocialDataLoadListener mListener; private Api mApi; public VkAccount() { mSocialType = User.SocialUserType.VKONTAKTE; mUserInfo = new VkUserInfo(); } public void setAccessToken(String token) { mAccessToken = token; mApi = new Api(token, "NEED_APP_ID"); } public void setUserId(String userId) { mUserInfo.setUserId(userId); } public void save(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Editor editor = prefs.edit(); editor.putString("access_token", mAccessToken); editor.putString("user_id", mUserInfo.getUserId()); editor.commit(); } public void restore(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String accessToken = prefs.getString("access_token", null); if (accessToken != null) { setAccessToken(accessToken); mUserInfo.setUserId(prefs.getString("user_id", null)); User.getInstance().onUserAuthorized(this, context); } } @Override public String getAccessToken() { return mAccessToken; } @Override public String getSocialId() { return mUserInfo.getUserId(); } @Override public boolean isAuthorized() { return getSocialId() != null && mAccessToken != null; } @Override public void postImage(Bitmap image, PostImageCallback callback) { new PostImageLoader().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new ShareImageObject(image, callback)); } @Override public int getSocialType() { return mSocialType; } @Override public SocialUserInfo getUserInfo() { return mUserInfo; } @Override public void loadUserData(Context context, SocialDataLoadListener listener) { mListener = listener; if (mApi != null) { loadUserInfo(); } } private void loadUserInfo() { new InfoLoader().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null); } public void logout() { mAccessToken = null; mUserInfo = new VkUserInfo(); } private class InfoLoader extends AsyncTask<Void, Void, Void> { @Override protected void onPostExecute(Void result) { mListener.onDataLoad(VkAccount.this); } @Override protected Void doInBackground(Void... params) { Collection<Long> id = new ArrayList<Long>(1); id.add(Long.valueOf(mUserInfo.getUserId())); try { ArrayList<com.perm.kate.api.User> users = mApi.getProfiles(id, null, "photo_200,photo_200_orig,photo_50,photo_400_orig", null, null, null); if (users.size() > 0) { com.perm.kate.api.User user = users.get(0); String photo = ""; if (user.photo_200 != null && !user.photo_200.isEmpty()) { photo = user.photo_200; } else if (user.photo_big != null && !user.photo_big.isEmpty()) { photo = user.photo_big; } else if (user.photo_400_orig != null && !user.photo_400_orig.isEmpty()) { photo = user.photo_400_orig; } else { photo = user.photo; } mUserInfo.setUser(user); if (photo != null && !photo.isEmpty()) { mUserInfo.setUserAvatar(photo); HttpGet request = new HttpGet(photo); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == 200) { mUserInfo.setUserPicture(BitmapFactory.decodeStream(response.getEntity().getContent())); } } } } catch (IOException e) { } catch (JSONException e) { } catch (KException e) { } return null; } } private class PostImageLoader extends AsyncTask<ShareImageObject, Void, Boolean> { private PostImageCallback mCallback; private String mPostId; @Override protected void onPostExecute(Boolean result) { if (result) { mCallback.onImagePosted(VkAccount.this, mPostId); } else { mCallback.onImagePostedError(VkAccount.this); } } @Override protected Boolean doInBackground(ShareImageObject... params) { boolean result = false; try { ShareImageObject o = params[0]; mCallback = o.getCallback(); String url = mApi.photosGetWallUploadServer(Long.valueOf(getSocialId()), null); HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(url); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); o.getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, byteStream); byte[] imageInByte = byteStream.toByteArray(); HttpEntity e = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE) .addBinaryBody("photo", imageInByte, ContentType.DEFAULT_BINARY, "" + System.currentTimeMillis() + ".jpg") .build(); httppost.setEntity(e); byteStream.close(); HttpResponse response = httpclient.execute(httppost); BufferedInputStream stream = new BufferedInputStream(response.getEntity().getContent()); Scanner s = new Scanner(stream, "UTF-8").useDelimiter("\\A"); String photoResp = s.hasNext() ? s.next() : ""; JSONObject json = new JSONObject(photoResp); s.close(); ArrayList<Photo> photos = mApi.saveWallPhoto(json.getString("server"), json.getString("photo"), json.getString("hash"), Long.valueOf(getSocialId()), null); Photo p = photos.get(0); List<String> attachments = new ArrayList<String>(); attachments.add("photo" + p.owner_id + "_" + p.pid); long postID = mApi.createWallPost(Long.valueOf(getSocialId()), "", attachments, null, false, false, false, null, null, null, 0L, null, null); mPostId = String.valueOf(postID); result = true; } catch (NumberFormatException e) { } catch (IOException e) { } catch (JSONException e) { } catch (KException e) { } return result; } } private class ShareImageObject { private Bitmap mBitmap; private PostImageCallback mCallback; public ShareImageObject(Bitmap bitmap, PostImageCallback callback) { mBitmap = bitmap; mCallback = callback; } public Bitmap getBitmap() { return mBitmap; } public PostImageCallback getCallback() { return mCallback; } } @Override public void likeGroup(Context context, LikeGroupCallback callback) { // TODO fb group id new LikeGroupLoader(callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "NEED_GROUP_ID"); } private class LikeGroupLoader extends AsyncTask<String, Void, Boolean> { private LikeGroupCallback mCallback; public LikeGroupLoader(LikeGroupCallback callback) { mCallback = callback; } @Override protected void onPostExecute(Boolean result) { if (result) { mCallback.onLikeGroup(VkAccount.this); } else { mCallback.onLikeGroupError(VkAccount.this); } } @Override protected Boolean doInBackground(String... id) { boolean result = false; try { // need to treat error code 17, when we should validate user String likeGroupCode = mApi.joinGroup(Long.valueOf(id[0]), null, null); result = true; } catch (NumberFormatException e) { } catch (IOException e) { } catch (JSONException e) { } catch (KException e) { } return result; } } @Override public void checkLikePage(String pageId, LikeCallback callback) { new LikeGroupCheckLoader(callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, pageId); } private class LikeGroupCheckLoader extends AsyncTask<String, Void, Boolean> { private LikeCallback mCallback; public LikeGroupCheckLoader(LikeCallback callback) { mCallback = callback; } @Override protected void onPostExecute(Boolean result) { mCallback.onLikeChecked(result); } @Override protected Boolean doInBackground(String... id) { boolean result = false; try { // 17, String likeGroupCode = mApi.isMemberGroup(Long.valueOf(id[0]), null, null); result = likeGroupCode.equals("1"); } catch (NumberFormatException e) { } catch (IOException e) { } catch (JSONException e) { } catch (KException e) { } catch (Exception e) { } return result; } } }