code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
package com.ch_linghu.fanfoudroid.data2;
import java.util.Date;
public class Status {
private Date created_at;
private String id;
private String text;
private String source;
private boolean truncated;
private String in_reply_to_status_id;
private String in_reply_to_user_id;
private boolean favorited;
private String in_reply_to_screen_name;
private Photo photo_url;
private User user;
private boolean isUnRead = false;
private int type = -1;
private String owner_id;
public Status() {}
public Date getCreatedAt() {
return created_at;
}
public void setCreatedAt(Date created_at) {
this.created_at = created_at;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public boolean isTruncated() {
return truncated;
}
public void setTruncated(boolean truncated) {
this.truncated = truncated;
}
public String getInReplyToStatusId() {
return in_reply_to_status_id;
}
public void setInReplyToStatusId(String in_reply_to_status_id) {
this.in_reply_to_status_id = in_reply_to_status_id;
}
public String getInReplyToUserId() {
return in_reply_to_user_id;
}
public void setInReplyToUserId(String in_reply_to_user_id) {
this.in_reply_to_user_id = in_reply_to_user_id;
}
public boolean isFavorited() {
return favorited;
}
public void setFavorited(boolean favorited) {
this.favorited = favorited;
}
public String getInReplyToScreenName() {
return in_reply_to_screen_name;
}
public void setInReplyToScreenName(String in_reply_to_screen_name) {
this.in_reply_to_screen_name = in_reply_to_screen_name;
}
public Photo getPhotoUrl() {
return photo_url;
}
public void setPhotoUrl(Photo photo_url) {
this.photo_url = photo_url;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public boolean isUnRead() {
return isUnRead;
}
public void setUnRead(boolean isUnRead) {
this.isUnRead = isUnRead;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getOwnerId() {
return owner_id;
}
public void setOwnerId(String owner_id) {
this.owner_id = owner_id;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Status other = (Status) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (owner_id == null) {
if (other.owner_id != null)
return false;
} else if (!owner_id.equals(other.owner_id))
return false;
if (type != other.type)
return false;
if (user == null) {
if (other.user != null)
return false;
} else if (!user.equals(other.user))
return false;
return true;
}
@Override
public String toString() {
return "Status [created_at=" + created_at + ", id=" + id + ", text="
+ text + ", source=" + source + ", truncated=" + truncated
+ ", in_reply_to_status_id=" + in_reply_to_status_id
+ ", in_reply_to_user_id=" + in_reply_to_user_id
+ ", favorited=" + favorited + ", in_reply_to_screen_name="
+ in_reply_to_screen_name + ", photo_url=" + photo_url
+ ", user=" + user + "]";
}
}
| Java |
package com.ch_linghu.fanfoudroid.data2;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class DataUtils {
static SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
public static Date parseDate(String str, String format) throws ParseException {
if (str == null || "".equals(str)) {
return null;
}
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.parse(str);
}
}
| Java |
package com.ch_linghu.fanfoudroid.data2;
import java.util.Date;
public class User {
private String id;
private String name;
private String screen_name;
private String location;
private String desription;
private String profile_image_url;
private String url;
private boolean isProtected;
private int friends_count;
private int followers_count;
private int favourites_count;
private Date created_at;
private boolean following;
private boolean notifications;
private int utc_offset;
private Status status; // null
public User() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScreenName() {
return screen_name;
}
public void setScreenName(String screen_name) {
this.screen_name = screen_name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getDesription() {
return desription;
}
public void setDesription(String desription) {
this.desription = desription;
}
public String getProfileImageUrl() {
return profile_image_url;
}
public void setProfileImageUrl(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public boolean isProtected() {
return isProtected;
}
public void setProtected(boolean isProtected) {
this.isProtected = isProtected;
}
public int getFriendsCount() {
return friends_count;
}
public void setFriendsCount(int friends_count) {
this.friends_count = friends_count;
}
public int getFollowersCount() {
return followers_count;
}
public void setFollowersCount(int followers_count) {
this.followers_count = followers_count;
}
public int getFavouritesCount() {
return favourites_count;
}
public void setFavouritesCount(int favourites_count) {
this.favourites_count = favourites_count;
}
public Date getCreatedAt() {
return created_at;
}
public void setCreatedAt(Date created_at) {
this.created_at = created_at;
}
public boolean isFollowing() {
return following;
}
public void setFollowing(boolean following) {
this.following = following;
}
public boolean isNotifications() {
return notifications;
}
public void setNotifications(boolean notifications) {
this.notifications = notifications;
}
public int getUtcOffset() {
return utc_offset;
}
public void setUtcOffset(int utc_offset) {
this.utc_offset = utc_offset;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", screen_name="
+ screen_name + ", location=" + location + ", desription="
+ desription + ", profile_image_url=" + profile_image_url
+ ", url=" + url + ", isProtected=" + isProtected
+ ", friends_count=" + friends_count + ", followers_count="
+ followers_count + ", favourites_count=" + favourites_count
+ ", created_at=" + created_at + ", following=" + following
+ ", notifications=" + notifications + ", utc_offset="
+ utc_offset + ", status=" + status + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
| Java |
package com.ch_linghu.fanfoudroid.data2;
public class Photo {
private String thumburl;
private String imageurl;
private String largeurl;
public Photo() {}
public String getThumburl() {
return thumburl;
}
public void setThumburl(String thumburl) {
this.thumburl = thumburl;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public String getLargeurl() {
return largeurl;
}
public void setLargeurl(String largeurl) {
this.largeurl = largeurl;
}
@Override
public String toString() {
return "Photo [thumburl=" + thumburl + ", imageurl=" + imageurl
+ ", largeurl=" + largeurl + "]";
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.HttpRefusedException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.MyListView;
import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter;
public class UserTimelineActivity extends TwitterListBaseActivity implements
MyListView.OnNeedMoreListener, Refreshable {
private static final String TAG = UserTimelineActivity.class
.getSimpleName();
private Feedback mFeedback;
private static final String EXTRA_USERID = "userID";
private static final String EXTRA_NAME_SHOW = "showName";
private static final String SIS_RUNNING_KEY = "running";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.USERTIMELINE";
public static Intent createIntent(String userID, String showName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(EXTRA_USERID, userID);
intent.putExtra(EXTRA_NAME_SHOW, showName);
return intent;
}
// State.
private User mUser;
private String mUserID;
private String mShowName;
private ArrayList<Tweet> mTweets;
private int mNextPage = 1;
// Views.
private TextView headerView;
private TextView footerView;
private MyListView mTweetList;
// 记录服务器拒绝访问的信息
private String msg;
private static final int LOADINGFLAG = 1;
private static final int SUCCESSFLAG = 2;
private static final int NETWORKERRORFLAG = 3;
private static final int AUTHERRORFLAG = 4;
private TweetArrayAdapter mAdapter;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mLoadMoreTask;
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
mFeedback.failed("登录失败, 请重新登录.");
updateHeader(AUTHERRORFLAG);
return;
} else if (result == TaskResult.OK) {
updateHeader(SUCCESSFLAG);
updateFooter(SUCCESSFLAG);
draw();
goTop();
} else if (result == TaskResult.IO_ERROR) {
mFeedback.failed("更新失败.");
updateHeader(NETWORKERRORFLAG);
}
mFeedback.success("");
}
@Override
public String getName() {
return "UserTimelineRetrieve";
}
};
private TaskListener mLoadMoreTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onLoadMoreBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mFeedback.success("");
updateFooter(SUCCESSFLAG);
draw();
}
}
@Override
public String getName() {
return "UserTimelineLoadMoreTask";
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "_onCreate()...");
if (super._onCreate(savedInstanceState)) {
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
Intent intent = getIntent();
// get user id
mUserID = intent.getStringExtra(EXTRA_USERID);
// show username in title
mShowName = intent.getStringExtra(EXTRA_NAME_SHOW);
// Set header title
mNavbar.setHeaderTitle("@" + mShowName);
boolean wasRunning = isTrue(savedInstanceState, SIS_RUNNING_KEY);
// 此处要求mTweets不为空,最好确保profile页面消息为0时不能进入这个页面
if (!mTweets.isEmpty() && !wasRunning) {
updateHeader(SUCCESSFLAG);
draw();
} else {
doRetrieve();
}
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mLoadMoreTask != null
&& mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) {
mLoadMoreTask.cancel(true);
}
super.onDestroy();
}
@Override
protected void draw() {
mAdapter.refresh(mTweets);
}
public void goTop() {
Log.d(TAG, "goTop.");
mTweetList.setSelection(1);
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new UserTimelineRetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
private void doLoadMore() {
Log.d(TAG, "Attempting load more.");
if (mLoadMoreTask != null
&& mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mLoadMoreTask = new UserTimelineLoadMoreTask();
mLoadMoreTask.setListener(mLoadMoreTaskListener);
mLoadMoreTask.execute();
}
}
private void onRetrieveBegin() {
mFeedback.start("");
// 更新查询状态显示
updateHeader(LOADINGFLAG);
updateFooter(LOADINGFLAG);
}
private void onLoadMoreBegin() {
mFeedback.start("");
}
private class UserTimelineRetrieveTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
statusList = getApi().getUserTimeline(mUserID,
new Paging(mNextPage));
mUser = getApi().showUser(mUserID);
mFeedback.update(60);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
Throwable cause = e.getCause();
if (cause instanceof HttpRefusedException) {
// AUTH ERROR
msg = ((HttpRefusedException) cause).getError()
.getMessage();
return TaskResult.AUTH_ERROR;
} else {
return TaskResult.IO_ERROR;
}
}
mFeedback.update(100 - (int)Math.floor(statusList.size()*2)); // 60~100
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mTweets.add(tweet);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addTweets(mTweets);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
private class UserTimelineLoadMoreTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
statusList = getApi().getUserTimeline(mUserID,
new Paging(mNextPage));
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
Throwable cause = e.getCause();
if (cause instanceof HttpRefusedException) {
// AUTH ERROR
msg = ((HttpRefusedException) cause).getError()
.getMessage();
return TaskResult.AUTH_ERROR;
} else {
return TaskResult.IO_ERROR;
}
}
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mTweets.add(tweet);
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
addTweets(mTweets);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
@Override
public void needMore() {
if (!isLastPage()) {
doLoadMore();
}
}
public boolean isLastPage() {
return mNextPage == -1;
}
private synchronized void addTweets(ArrayList<Tweet> tweets) {
// do more时没有更多时
if (tweets.size() == 0) {
mNextPage = -1;
return;
}
mTweets.addAll(tweets);
++mNextPage;
}
@Override
protected String getActivityTitle() {
return "@" + mShowName;
}
@Override
protected Tweet getContextItemTweet(int position) {
if (position >= 1 && position <= mAdapter.getCount()) {
return (Tweet) mAdapter.getItem(position - 1);
} else {
return null;
}
}
@Override
protected int getLayoutId() {
return R.layout.user_timeline;
}
@Override
protected com.ch_linghu.fanfoudroid.ui.module.TweetAdapter getTweetAdapter() {
return mAdapter;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected void setupState() {
mTweets = new ArrayList<Tweet>();
mAdapter = new TweetArrayAdapter(this);
mTweetList = (MyListView) findViewById(R.id.tweet_list);
// Add Header to ListView
headerView = (TextView) TextView.inflate(this,
R.layout.user_timeline_header, null);
mTweetList.addHeaderView(headerView);
// Add Footer to ListView
footerView = (TextView) TextView.inflate(this,
R.layout.user_timeline_footer, null);
mTweetList.addFooterView(footerView);
mTweetList.setAdapter(mAdapter);
mTweetList.setOnNeedMoreListener(this);
}
@Override
protected void updateTweet(Tweet tweet) {
// 该方法作用?
}
@Override
protected boolean useBasicMenu() {
return true;
}
private void updateHeader(int flag) {
if (flag == LOADINGFLAG) {
// 重新刷新页面时从第一页开始获取数据 --- phoenix
mNextPage = 1;
mTweets.clear();
mAdapter.refresh(mTweets);
headerView.setText(getResources()
.getString(R.string.search_loading));
}
if (flag == SUCCESSFLAG) {
headerView.setText(getResources().getString(
R.string.user_query_status_success));
}
if (flag == NETWORKERRORFLAG) {
headerView.setText(getResources().getString(
R.string.login_status_network_or_connection_error));
}
if (flag == AUTHERRORFLAG) {
headerView.setText(msg);
}
}
private void updateFooter(int flag) {
if (flag == LOADINGFLAG) {
footerView.setText("该用户总共?条消息");
}
if (flag == SUCCESSFLAG) {
footerView.setText("该用户总共" + mUser.getStatusesCount() + "条消息,当前显示"
+ mTweets.size() + "条。");
}
}
} | Java |
/*
* Copyright (C) 2009 Google Inc.
*
* 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.ch_linghu.fanfoudroid;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetEdit;
//FIXME: 将WriteDmActivity和WriteActivity进行整合。
/**
* 撰写私信界面
* @author lds
*
*/
public class WriteDmActivity extends BaseActivity {
public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW";
public static final String EXTRA_TEXT = "text";
public static final String REPLY_ID = "reply_id";
private static final String TAG = "WriteActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
// View
private TweetEdit mTweetEdit;
private EditText mTweetEditText;
private TextView mProgressText;
private Button mSendButton;
//private AutoCompleteTextView mToEdit;
private TextView mToEdit;
private NavBar mNavbar;
// Task
private GenericTask mSendTask;
private TaskListener mSendTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
disableEntry();
updateProgress(getString(R.string.page_status_updating));
}
@Override
public void onPostExecute(GenericTask task,
TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mToEdit.setText("");
mTweetEdit.setText("");
updateProgress("");
enableEntry();
// 发送成功就直接关闭界面
finish();
// 关闭软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(), 0);
} else if (result == TaskResult.NOT_FOLLOWED_ERROR) {
updateProgress(getString(R.string.direct_meesage_status_the_person_not_following_you));
enableEntry();
} else if (result == TaskResult.IO_ERROR) {
// TODO: 什么情况下会抛出IO_ERROR?需要给用户更为具体的失败原因
updateProgress(getString(R.string.page_status_unable_to_update));
enableEntry();
}
}
@Override
public String getName() {
return "DMSend";
}
};
private FriendsAdapter mFriendsAdapter; // Adapter for To: recipient
// autocomplete.
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMSW";
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
// sub menu
// protected void createInsertPhotoDialog() {
//
// final CharSequence[] items = {
// getString(R.string.write_label_take_a_picture),
// getString(R.string.write_label_choose_a_picture) };
//
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle(getString(R.string.write_label_insert_picture));
// builder.setItems(items, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int item) {
// // Toast.makeText(getApplicationContext(), items[item],
// // Toast.LENGTH_SHORT).show();
// switch (item) {
// case 0:
// openImageCaptureMenu();
// break;
// case 1:
// openPhotoLibraryMenu();
// }
// }
// });
// AlertDialog alert = builder.create();
// alert.show();
// }
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)){
// init View
setContentView(R.layout.write_dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this);
// Intent & Action & Extras
Intent intent = getIntent();
Bundle extras = intent.getExtras();
// View
mProgressText = (TextView) findViewById(R.id.progress_text);
mTweetEditText = (EditText) findViewById(R.id.tweet_edit);
TwitterDatabase db = getDb();
//FIXME: 暂时取消收件人自动完成功能
//FIXME: 可根据目前以后内容重新完成自动完成功能
//mToEdit = (AutoCompleteTextView) findViewById(R.id.to_edit);
//Cursor cursor = db.getFollowerUsernames("");
//// startManagingCursor(cursor);
//mFriendsAdapter = new FriendsAdapter(this, cursor);
//mToEdit.setAdapter(mFriendsAdapter);
mToEdit = (TextView) findViewById(R.id.to_edit);
// Update status
mTweetEdit = new TweetEdit(mTweetEditText,
(TextView) findViewById(R.id.chars_text));
mTweetEdit.setOnKeyListener(editEnterHandler);
mTweetEdit
.addTextChangedListener(new MyTextWatcher(WriteDmActivity.this));
// With extras
if (extras != null) {
String to = extras.getString(EXTRA_USER);
if (!TextUtils.isEmpty(to)) {
mToEdit.setText(to);
mTweetEdit.requestFocus();
}
}
View.OnClickListener sendListenner = new View.OnClickListener() {
public void onClick(View v) {
doSend();
}
};
mSendButton = (Button) findViewById(R.id.send_button);
mSendButton.setOnClickListener(sendListenner);
Button mTopSendButton = (Button) findViewById(R.id.top_send_btn);
mTopSendButton.setOnClickListener(sendListenner);
return true;
}else{
return false;
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
mTweetEdit.updateCharsRemain();
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
// Doesn't really cancel execution (we let it continue running).
// See the SendTask code for more details.
mSendTask.cancel(true);
}
// Don't need to cancel FollowersTask (assuming it ends properly).
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
public static Intent createNewTweetIntent(String text) {
Intent intent = new Intent(NEW_TWEET_ACTION);
intent.putExtra(EXTRA_TEXT, text);
return intent;
}
private class MyTextWatcher implements TextWatcher {
private WriteDmActivity _activity;
public MyTextWatcher(WriteDmActivity activity) {
_activity = activity;
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (s.length() == 0) {
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
private void doSend() {
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
String to = mToEdit.getText().toString();
String status = mTweetEdit.getText().toString();
if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(to)) {
mSendTask = new DmSendTask();
mSendTask.setListener(mSendTaskListener);
mSendTask.execute();
} else if (TextUtils.isEmpty(status)) {
updateProgress(getString(R.string.direct_meesage_status_texting_is_null));
} else if (TextUtils.isEmpty(to)) {
updateProgress(getString(R.string.direct_meesage_status_user_is_null));
}
}
}
private class DmSendTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String user = mToEdit.getText().toString();
String text = mTweetEdit.getText().toString();
DirectMessage directMessage = getApi().sendDirectMessage(user,
text);
Dm dm = Dm.create(directMessage, true);
// if (!Utils.isEmpty(dm.profileImageUrl)) {
// // Fetch image to cache.
// try {
// getImageManager().put(dm.profileImageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
getDb().createDm(dm, false);
} catch (HttpException e) {
Log.d(TAG, e.getMessage());
// TODO: check is this is actually the case.
return TaskResult.NOT_FOLLOWED_ERROR;
}
return TaskResult.OK;
}
}
private static class FriendsAdapter extends CursorAdapter {
public FriendsAdapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
mUserTextColumn = cursor
.getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater
.inflate(R.layout.dropdown_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view.findViewById(android.R.id.text1);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.userText.setText(cursor.getString(mUserTextColumn));
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String filter = constraint == null ? "" : constraint.toString();
return TwitterApplication.mDb.getFollowerUsernames(filter);
}
@Override
public String convertToString(Cursor cursor) {
return cursor.getString(mUserTextColumn);
}
}
private void enableEntry() {
mTweetEdit.setEnabled(true);
mSendButton.setEnabled(true);
}
private void disableEntry() {
mTweetEdit.setEnabled(false);
mSendButton.setEnabled(false);
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
private View.OnKeyListener editEnterHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
doSend();
}
return true;
}
return false;
}
};
} | Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing search API response
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class QueryResult extends WeiboResponse {
private long sinceId;
private long maxId;
private String refreshUrl;
private int resultsPerPage;
private int total = -1;
private String warning;
private double completedIn;
private int page;
private String query;
private List<Status> tweets;
private static final long serialVersionUID = -9059136565234613286L;
/*package*/ QueryResult(Response res, WeiboSupport weiboSupport) throws HttpException {
super(res);
// 饭否search API直接返回 "[{JSONObejet},{JSONObejet},{JSONObejet}]"的JSONArray
//System.out.println("TAG " + res.asString());
JSONArray array = res.asJSONArray();
try {
tweets = new ArrayList<Status>(array.length());
for (int i = 0; i < array.length(); i++) {
JSONObject tweet = array.getJSONObject(i);
tweets.add(new Status(tweet));
}
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + array.toString(), jsone);
}
}
/*package*/ QueryResult(Query query) throws HttpException {
super();
sinceId = query.getSinceId();
resultsPerPage = query.getRpp();
page = query.getPage();
tweets = new ArrayList<Status>(0);
}
public long getSinceId() {
return sinceId;
}
public long getMaxId() {
return maxId;
}
public String getRefreshUrl() {
return refreshUrl;
}
public int getResultsPerPage() {
return resultsPerPage;
}
/**
* returns the number of hits
* @return number of hits
* @deprecated The Weibo API doesn't return total anymore
* @see <a href="http://yusuke.homeip.net/jira/browse/TFJ-108">TRJ-108 deprecate QueryResult#getTotal()</a>
*/
@Deprecated
public int getTotal() {
return total;
}
public String getWarning() {
return warning;
}
public double getCompletedIn() {
return completedIn;
}
public int getPage() {
return page;
}
public String getQuery() {
return query;
}
public List<Status> getStatus() {
return tweets;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
QueryResult that = (QueryResult) o;
if (Double.compare(that.completedIn, completedIn) != 0) return false;
if (maxId != that.maxId) return false;
if (page != that.page) return false;
if (resultsPerPage != that.resultsPerPage) return false;
if (sinceId != that.sinceId) return false;
if (total != that.total) return false;
if (!query.equals(that.query)) return false;
if (refreshUrl != null ? !refreshUrl.equals(that.refreshUrl) : that.refreshUrl != null)
return false;
if (tweets != null ? !tweets.equals(that.tweets) : that.tweets != null)
return false;
if (warning != null ? !warning.equals(that.warning) : that.warning != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = (int) (sinceId ^ (sinceId >>> 32));
result = 31 * result + (int) (maxId ^ (maxId >>> 32));
result = 31 * result + (refreshUrl != null ? refreshUrl.hashCode() : 0);
result = 31 * result + resultsPerPage;
result = 31 * result + total;
result = 31 * result + (warning != null ? warning.hashCode() : 0);
temp = completedIn != +0.0d ? Double.doubleToLongBits(completedIn) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
result = 31 * result + page;
result = 31 * result + query.hashCode();
result = 31 * result + (tweets != null ? tweets.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "QueryResult{" +
"sinceId=" + sinceId +
", maxId=" + maxId +
", refreshUrl='" + refreshUrl + '\'' +
", resultsPerPage=" + resultsPerPage +
", total=" + total +
", warning='" + warning + '\'' +
", completedIn=" + completedIn +
", page=" + page +
", query='" + query + '\'' +
", tweets=" + tweets +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.AccessControlException;
import java.util.Properties;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Configuration {
private static Properties defaultProperty;
static {
init();
}
/*package*/ static void init() {
defaultProperty = new Properties();
//defaultProperty.setProperty("fanfoudroid.debug", "false");
defaultProperty.setProperty("fanfoudroid.debug", "true");
defaultProperty.setProperty("fanfoudroid.source", "fanfoudroid");
//defaultProperty.setProperty("fanfoudroid.clientVersion","");
defaultProperty.setProperty("fanfoudroid.clientURL", "http://sandin.tk/fanfoudroid.xml");
defaultProperty.setProperty("fanfoudroid.http.userAgent", "fanfoudroid 1.0");
//defaultProperty.setProperty("fanfoudroid.user","");
//defaultProperty.setProperty("fanfoudroid.password","");
defaultProperty.setProperty("fanfoudroid.http.useSSL", "false");
//defaultProperty.setProperty("fanfoudroid.http.proxyHost","");
defaultProperty.setProperty("fanfoudroid.http.proxyHost.fallback", "http.proxyHost");
//defaultProperty.setProperty("fanfoudroid.http.proxyUser","");
//defaultProperty.setProperty("fanfoudroid.http.proxyPassword","");
//defaultProperty.setProperty("fanfoudroid.http.proxyPort","");
defaultProperty.setProperty("fanfoudroid.http.proxyPort.fallback", "http.proxyPort");
defaultProperty.setProperty("fanfoudroid.http.connectionTimeout", "20000");
defaultProperty.setProperty("fanfoudroid.http.readTimeout", "120000");
defaultProperty.setProperty("fanfoudroid.http.retryCount", "3");
defaultProperty.setProperty("fanfoudroid.http.retryIntervalSecs", "10");
//defaultProperty.setProperty("fanfoudroid.oauth.consumerKey","");
//defaultProperty.setProperty("fanfoudroid.oauth.consumerSecret","");
defaultProperty.setProperty("fanfoudroid.async.numThreads", "1");
defaultProperty.setProperty("fanfoudroid.clientVersion", "1.0");
try {
// Android platform should have dalvik.system.VMRuntime in the classpath.
// @see http://developer.android.com/reference/dalvik/system/VMRuntime.html
Class.forName("dalvik.system.VMRuntime");
defaultProperty.setProperty("fanfoudroid.dalvik", "true");
} catch (ClassNotFoundException cnfe) {
defaultProperty.setProperty("fanfoudroid.dalvik", "false");
}
DALVIK = getBoolean("fanfoudroid.dalvik");
String t4jProps = "fanfoudroid.properties";
boolean loaded = loadProperties(defaultProperty, "." + File.separatorChar + t4jProps) ||
loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/WEB-INF/" + t4jProps)) ||
loadProperties(defaultProperty, Configuration.class.getResourceAsStream("/" + t4jProps));
}
private static boolean loadProperties(Properties props, String path) {
try {
File file = new File(path);
if(file.exists() && file.isFile()){
props.load(new FileInputStream(file));
return true;
}
} catch (Exception ignore) {
}
return false;
}
private static boolean loadProperties(Properties props, InputStream is) {
try {
props.load(is);
return true;
} catch (Exception ignore) {
}
return false;
}
private static boolean DALVIK;
public static boolean isDalvik() {
return DALVIK;
}
public static boolean useSSL() {
return getBoolean("fanfoudroid.http.useSSL");
}
public static String getScheme(){
return useSSL() ? "https://" : "http://";
}
public static String getCilentVersion() {
return getProperty("fanfoudroid.clientVersion");
}
public static String getCilentVersion(String clientVersion) {
return getProperty("fanfoudroid.clientVersion", clientVersion);
}
public static String getSource() {
return getProperty("fanfoudroid.source");
}
public static String getSource(String source) {
return getProperty("fanfoudroid.source", source);
}
public static String getProxyHost() {
return getProperty("fanfoudroid.http.proxyHost");
}
public static String getProxyHost(String proxyHost) {
return getProperty("fanfoudroid.http.proxyHost", proxyHost);
}
public static String getProxyUser() {
return getProperty("fanfoudroid.http.proxyUser");
}
public static String getProxyUser(String user) {
return getProperty("fanfoudroid.http.proxyUser", user);
}
public static String getClientURL() {
return getProperty("fanfoudroid.clientURL");
}
public static String getClientURL(String clientURL) {
return getProperty("fanfoudroid.clientURL", clientURL);
}
public static String getProxyPassword() {
return getProperty("fanfoudroid.http.proxyPassword");
}
public static String getProxyPassword(String password) {
return getProperty("fanfoudroid.http.proxyPassword", password);
}
public static int getProxyPort() {
return getIntProperty("fanfoudroid.http.proxyPort");
}
public static int getProxyPort(int port) {
return getIntProperty("fanfoudroid.http.proxyPort", port);
}
public static int getConnectionTimeout() {
return getIntProperty("fanfoudroid.http.connectionTimeout");
}
public static int getConnectionTimeout(int connectionTimeout) {
return getIntProperty("fanfoudroid.http.connectionTimeout", connectionTimeout);
}
public static int getReadTimeout() {
return getIntProperty("fanfoudroid.http.readTimeout");
}
public static int getReadTimeout(int readTimeout) {
return getIntProperty("fanfoudroid.http.readTimeout", readTimeout);
}
public static int getRetryCount() {
return getIntProperty("fanfoudroid.http.retryCount");
}
public static int getRetryCount(int retryCount) {
return getIntProperty("fanfoudroid.http.retryCount", retryCount);
}
public static int getRetryIntervalSecs() {
return getIntProperty("fanfoudroid.http.retryIntervalSecs");
}
public static int getRetryIntervalSecs(int retryIntervalSecs) {
return getIntProperty("fanfoudroid.http.retryIntervalSecs", retryIntervalSecs);
}
public static String getUser() {
return getProperty("fanfoudroid.user");
}
public static String getUser(String userId) {
return getProperty("fanfoudroid.user", userId);
}
public static String getPassword() {
return getProperty("fanfoudroid.password");
}
public static String getPassword(String password) {
return getProperty("fanfoudroid.password", password);
}
public static String getUserAgent() {
return getProperty("fanfoudroid.http.userAgent");
}
public static String getUserAgent(String userAgent) {
return getProperty("fanfoudroid.http.userAgent", userAgent);
}
public static String getOAuthConsumerKey() {
return getProperty("fanfoudroid.oauth.consumerKey");
}
public static String getOAuthConsumerKey(String consumerKey) {
return getProperty("fanfoudroid.oauth.consumerKey", consumerKey);
}
public static String getOAuthConsumerSecret() {
return getProperty("fanfoudroid.oauth.consumerSecret");
}
public static String getOAuthConsumerSecret(String consumerSecret) {
return getProperty("fanfoudroid.oauth.consumerSecret", consumerSecret);
}
public static boolean getBoolean(String name) {
String value = getProperty(name);
return Boolean.valueOf(value);
}
public static int getIntProperty(String name) {
String value = getProperty(name);
try {
return Integer.parseInt(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static int getIntProperty(String name, int fallbackValue) {
String value = getProperty(name, String.valueOf(fallbackValue));
try {
return Integer.parseInt(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static long getLongProperty(String name) {
String value = getProperty(name);
try {
return Long.parseLong(value);
} catch (NumberFormatException nfe) {
return -1;
}
}
public static String getProperty(String name) {
return getProperty(name, null);
}
public static String getProperty(String name, String fallbackValue) {
String value;
try {
value = System.getProperty(name, fallbackValue);
if (null == value) {
value = defaultProperty.getProperty(name);
}
if (null == value) {
String fallback = defaultProperty.getProperty(name + ".fallback");
if (null != fallback) {
value = System.getProperty(fallback);
}
}
} catch (AccessControlException ace) {
// Unsigned applet cannot access System properties
value = fallbackValue;
}
return replace(value);
}
private static String replace(String value) {
if (null == value) {
return value;
}
String newValue = value;
int openBrace = 0;
if (-1 != (openBrace = value.indexOf("{", openBrace))) {
int closeBrace = value.indexOf("}", openBrace);
if (closeBrace > (openBrace + 1)) {
String name = value.substring(openBrace + 1, closeBrace);
if (name.length() > 0) {
newValue = value.substring(0, openBrace) + getProperty(name)
+ value.substring(closeBrace + 1);
}
}
}
if (newValue.equals(value)) {
return value;
} else {
return replace(newValue);
}
}
public static int getNumberOfAsyncThreads() {
return getIntProperty("fanfoudroid.async.numThreads");
}
public static boolean getDebug() {
return getBoolean("fanfoudroid.debug");
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Treands.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.2
*/
public class Trends extends WeiboResponse implements Comparable<Trends> {
private Date asOf;
private Date trendAt;
private Trend[] trends;
private static final long serialVersionUID = -7151479143843312309L;
public int compareTo(Trends that) {
return this.trendAt.compareTo(that.trendAt);
}
/*package*/ Trends(Response res, Date asOf, Date trendAt, Trend[] trends)
throws HttpException {
super(res);
this.asOf = asOf;
this.trendAt = trendAt;
this.trends = trends;
}
/*package*/
static List<Trends> constructTrendsList(Response res) throws
HttpException {
JSONObject json = res.asJSONObject();
List<Trends> trends;
try {
Date asOf = parseDate(json.getString("as_of"));
JSONObject trendsJson = json.getJSONObject("trends");
trends = new ArrayList<Trends>(trendsJson.length());
Iterator ite = trendsJson.keys();
while (ite.hasNext()) {
String key = (String) ite.next();
JSONArray array = trendsJson.getJSONArray(key);
Trend[] trendsArray = jsonArrayToTrendArray(array);
if (key.length() == 19) {
// current trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd HH:mm:ss"), trendsArray));
} else if (key.length() == 16) {
// daily trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd HH:mm"), trendsArray));
} else if (key.length() == 10) {
// weekly trends
trends.add(new Trends(res, asOf, parseDate(key
, "yyyy-MM-dd"), trendsArray));
}
}
Collections.sort(trends);
return trends;
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
/*package*/
static Trends constructTrends(Response res) throws HttpException {
JSONObject json = res.asJSONObject();
try {
Date asOf = parseDate(json.getString("as_of"));
JSONArray array = json.getJSONArray("trends");
Trend[] trendsArray = jsonArrayToTrendArray(array);
return new Trends(res, asOf, asOf, trendsArray);
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
private static Date parseDate(String asOfStr) throws HttpException {
Date parsed;
if (asOfStr.length() == 10) {
parsed = new Date(Long.parseLong(asOfStr) * 1000);
} else {
// parsed = WeiboResponse.parseDate(asOfStr, "EEE, d MMM yyyy HH:mm:ss z");
parsed = WeiboResponse.parseDate(asOfStr, "EEE MMM WW HH:mm:ss z yyyy");
}
return parsed;
}
private static Trend[] jsonArrayToTrendArray(JSONArray array) throws JSONException {
Trend[] trends = new Trend[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject trend = array.getJSONObject(i);
trends[i] = new Trend(trend);
}
return trends;
}
public Trend[] getTrends() {
return this.trends;
}
public Date getAsOf() {
return asOf;
}
public Date getTrendAt() {
return trendAt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Trends)) return false;
Trends trends1 = (Trends) o;
if (asOf != null ? !asOf.equals(trends1.asOf) : trends1.asOf != null)
return false;
if (trendAt != null ? !trendAt.equals(trends1.trendAt) : trends1.trendAt != null)
return false;
if (!Arrays.equals(trends, trends1.trends)) return false;
return true;
}
@Override
public int hashCode() {
int result = asOf != null ? asOf.hashCode() : 0;
result = 31 * result + (trendAt != null ? trendAt.hashCode() : 0);
result = 31 * result + (trends != null ? Arrays.hashCode(trends) : 0);
return result;
}
@Override
public String toString() {
return "Trends{" +
"asOf=" + asOf +
", trendAt=" + trendAt +
", trends=" + (trends == null ? null : Arrays.asList(trends)) +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* 模仿JSONObject的XML实现
* @author jmx
*
*/
class XmlObject{
private String str;
public XmlObject(String s){
this.str = s;
}
//FIXME: 这里用的是一个专有的ugly实现
public String getString(String name) throws Exception {
Pattern p = Pattern.compile(String.format("<%s>(.*?)</%s>", name, name));
Matcher m = p.matcher(this.str);
if (m.find()){
return m.group(1);
}else{
throw new Exception(String.format("<%s> value not found", name));
}
}
@Override
public String toString(){
return this.str;
}
}
/**
* 服务器响应的错误信息
*/
public class RefuseError extends WeiboResponse implements java.io.Serializable {
// TODO: get error type
public static final int ERROR_A = 1;
public static final int ERROR_B = 1;
public static final int ERROR_C = 1;
private int mErrorCode = -1;
private String mRequestUrl = "";
private String mResponseError = "";
private static final long serialVersionUID = -2105422180879273058L;
public RefuseError(Response res) throws HttpException {
String error = res.asString();
try{
//先尝试作为json object进行处理
JSONObject json = new JSONObject(error);
init(json);
}catch(Exception e1){
//如果失败,则作为XML再进行处理
try{
XmlObject xml = new XmlObject(error);
init(xml);
}catch(Exception e2){
//再失败就作为普通字符串进行处理,这个处理保证不会出错
init(error);
}
}
}
public void init(JSONObject json) throws HttpException {
try {
mRequestUrl = json.getString("request");
mResponseError = json.getString("error");
parseError(mResponseError);
} catch (JSONException je) {
throw new HttpException(je.getMessage() + ":" + json.toString(), je);
}
}
public void init(XmlObject xml) throws HttpException {
try {
mRequestUrl = xml.getString("request");
mResponseError = xml.getString("error");
parseError(mResponseError);
} catch (Exception e) {
throw new HttpException(e.getMessage() + ":" + xml.toString(), e);
}
}
public void init(String error){
mRequestUrl = "";
mResponseError = error;
parseError(mResponseError);
}
private void parseError(String error) {
if (error.equals("")) {
mErrorCode = ERROR_A;
}
}
public int getErrorCode() {
return mErrorCode;
}
public String getRequestUrl() {
return mRequestUrl;
}
public String getMessage() {
return mResponseError;
}
} | Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import com.ch_linghu.fanfoudroid.http.HttpClient;
/**
* @author Yusuke Yamamoto - yusuke at mac.com
*/
/*protected*/ class WeiboSupport {
protected HttpClient http = null;
protected String source = Configuration.getSource();
protected final boolean USE_SSL;
/*package*/ WeiboSupport(){
USE_SSL = Configuration.useSSL();
http = new HttpClient(); // In case that the user is not logged in
}
/*package*/ WeiboSupport(String userId, String password){
USE_SSL = Configuration.useSSL();
http = new HttpClient(userId, password);
}
/**
* Returns authenticating userid
*
* @return userid
*/
public String getUserId() {
return http.getUserId();
}
/**
* Returns authenticating password
*
* @return password
*/
public String getPassword() {
return http.getPassword();
}
//Low-level interface
public HttpClient getHttpClient(){
return http;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONException;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing array of numeric IDs.
*
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class IDs extends WeiboResponse {
private String[] ids;
private long previousCursor;
private long nextCursor;
private static final long serialVersionUID = -6585026560164704953L;
private static String[] ROOT_NODE_NAMES = {"id_list", "ids"};
/*package*/ IDs(Response res) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
ensureRootNodeNameIs(ROOT_NODE_NAMES, elem);
NodeList idlist = elem.getElementsByTagName("id");
ids = new String[idlist.getLength()];
for (int i = 0; i < idlist.getLength(); i++) {
try {
ids[i] = idlist.item(i).getFirstChild().getNodeValue();
} catch (NumberFormatException nfe) {
throw new HttpException("Weibo API returned malformed response(Invalid Number): " + elem, nfe);
} catch (NullPointerException npe) {
throw new HttpException("Weibo API returned malformed response(NULL): " + elem, npe);
}
}
previousCursor = getChildLong("previous_cursor", elem);
nextCursor = getChildLong("next_cursor", elem);
}
/* package */IDs(Response res, Weibo w) throws HttpException {
super(res);
// TODO: 饭否返回的为 JSONArray 类型,
// 例如["ifan","fanfouapi","\u62cd\u62cd","daoru"]
// JSONObject json= res.asJSONObject();
JSONArray jsona = res.asJSONArray();
try {
int size = jsona.length();
ids = new String[size];
for (int i = 0; i < size; i++) {
ids[i] = jsona.getString(i);
}
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
public String[] getIDs() {
return ids;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean hasPrevious(){
return 0 != previousCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public long getPreviousCursor() {
return previousCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean hasNext(){
return 0 != nextCursor;
}
/**
*
* @since Weibo4J 2.0.10
*/
public long getNextCursor() {
return nextCursor;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof IDs)) return false;
IDs iDs = (IDs) o;
if (!Arrays.equals(ids, iDs.ids)) return false;
return true;
}
@Override
public int hashCode() {
return ids != null ? Arrays.hashCode(ids) : 0;
}
public int getCount(){
return ids.length;
}
@Override
public String toString() {
return "IDs{" +
"ids=" + ids +
", previousCursor=" + previousCursor +
", nextCursor=" + nextCursor +
'}';
}
} | Java |
/*
* UserObjectWapper.java created on 2010-7-28 上午08:48:35 by bwl (Liu Daoru)
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.Serializable;
import java.util.List;
/**
* 对User对象列表进行的包装,以支持cursor相关信息传递
* @author liudaoru - daoru at sina.com.cn
*/
public class UserWapper implements Serializable {
private static final long serialVersionUID = -3119107701303920284L;
/**
* 用户对象列表
*/
private List<User> users;
/**
* 向前翻页的cursor
*/
private long previousCursor;
/**
* 向后翻页的cursor
*/
private long nextCursor;
public UserWapper(List<User> users, long previousCursor, long nextCursor) {
this.users = users;
this.previousCursor = previousCursor;
this.nextCursor = nextCursor;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public long getPreviousCursor() {
return previousCursor;
}
public void setPreviousCursor(long previousCursor) {
this.previousCursor = previousCursor;
}
public long getNextCursor() {
return nextCursor;
}
public void setNextCursor(long nextCursor) {
this.nextCursor = nextCursor;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
/**
* Controlls pagination
*
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Paging implements java.io.Serializable {
private int page = -1;
private int count = -1;
private String sinceId = "";
private String maxId = "";
private static final long serialVersionUID = -3285857427993796670L;
public Paging() {
}
public Paging(int page) {
setPage(page);
}
public Paging(String sinceId) {
setSinceId(sinceId);
}
public Paging(int page, int count) {
this(page);
setCount(count);
}
public Paging(int page, String sinceId) {
this(page);
setSinceId(sinceId);
}
public Paging(int page, int count, String sinceId) {
this(page, count);
setSinceId(sinceId);
}
public Paging(int page, int count, String sinceId, String maxId) {
this(page, count, sinceId);
setMaxId(maxId);
}
public int getPage() {
return page;
}
public void setPage(int page) {
if (page < 1) {
throw new IllegalArgumentException("page should be positive integer. passed:" + page);
}
this.page = page;
}
public int getCount() {
return count;
}
public void setCount(int count) {
if (count < 1) {
throw new IllegalArgumentException("count should be positive integer. passed:" + count);
}
this.count = count;
}
public Paging count(int count) {
setCount(count);
return this;
}
public String getSinceId() {
return sinceId;
}
public void setSinceId(String sinceId) {
if (sinceId.length() > 0) {
this.sinceId = sinceId;
} else {
throw new IllegalArgumentException("since_id is null. passed:" + sinceId);
}
}
public Paging sinceId(String sinceId) {
setSinceId(sinceId);
return this;
}
public String getMaxId() {
return maxId;
}
public void setMaxId(String maxId) {
if (maxId.length() == 0) {
throw new IllegalArgumentException("max_id is null. passed:" + maxId);
}
this.maxId = maxId;
}
public Paging maxId(String maxId) {
setMaxId(maxId);
return this;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
public class Weibo extends WeiboSupport implements java.io.Serializable {
public static final String TAG = "Weibo_API";
public static final String CONSUMER_KEY = Configuration.getSource();
public static final String CONSUMER_SECRET = "";
private String baseURL = Configuration.getScheme() + "api.fanfou.com/";
private String searchBaseURL = Configuration.getScheme() + "api.fanfou.com/";
private static final long serialVersionUID = -1486360080128882436L;
public Weibo() {
super(); // In case that the user is not logged in
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public Weibo(String userId, String password) {
super(userId, password);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public Weibo(String userId, String password, String baseURL) {
this(userId, password);
this.baseURL = baseURL;
}
/**
* 设置HttpClient的Auth,为请求做准备
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
http.setCredentials(username, password);
}
/**
* 仅判断是否为空
* @param username
* @param password
* @return
*/
public static boolean isValidCredentials(String username, String password) {
return !TextUtils.isEmpty(username) && !TextUtils.isEmpty(password);
}
/**
* 在服务器上验证用户名/密码是否正确,成功则返回该用户信息,失败则抛出异常。
* @param username
* @param password
* @return Verified User
* @throws HttpException 验证失败及其他非200响应均抛出异常
*/
public User login(String username, String password) throws HttpException {
Log.d(TAG, "Login attempt for " + username);
http.setCredentials(username, password);
// Verify userName and password on the server.
User user = verifyCredentials();
if (null != user && user.getId().length() > 0) {
}
return user;
}
/**
* Reset HttpClient's Credentials
*/
public void reset() {
http.reset();
}
/**
* Whether Logged-in
* @return
*/
public boolean isLoggedIn() {
// HttpClient的userName&password是由TwitterApplication#onCreate
// 从SharedPreferences中取出的,他们为空则表示尚未登录,因为他们只在验证
// 账户成功后才会被储存,且注销时被清空。
return isValidCredentials(http.getUserId(), http.getPassword());
}
/**
* Sets the base URL
*
* @param baseURL String the base URL
*/
public void setBaseURL(String baseURL) {
this.baseURL = baseURL;
}
/**
* Returns the base URL
*
* @return the base URL
*/
public String getBaseURL() {
return this.baseURL;
}
/**
* Sets the search base URL
*
* @param searchBaseURL the search base URL
* @since fanfoudroid 0.5.0
*/
public void setSearchBaseURL(String searchBaseURL) {
this.searchBaseURL = searchBaseURL;
}
/**
* Returns the search base url
* @return search base url
* @since fanfoudroid 0.5.0
*/
public String getSearchBaseURL(){
return this.searchBaseURL;
}
/**
* Returns authenticating userid
* 注意:此userId不一定等同与饭否用户的user_id参数
* 它可能是任意一种当前用户所使用的ID类型(如邮箱,用户名等),
*
* @return userid
*/
public String getUserId() {
return http.getUserId();
}
/**
* Returns authenticating password
*
* @return password
*/
public String getPassword() {
return http.getPassword();
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, boolean authenticate) throws HttpException {
return get(url, null, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param authenticate if true, the request will be sent with BASIC authentication header
* @param name1 the name of the first parameter
* @param value1 the value of the first parameter
* @return the response
* @throws HttpException
*/
protected Response get(String url, String name1, String value1, boolean authenticate) throws HttpException {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add( new BasicNameValuePair(name1, HttpClient.encode(value1) ) );
return get(url, params, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param name1 the name of the first parameter
* @param value1 the value of the first parameter
* @param name2 the name of the second parameter
* @param value2 the value of the second parameter
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, String name1, String value1, String name2, String value2, boolean authenticate) throws HttpException {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair(name1, HttpClient.encode(value1)));
params.add(new BasicNameValuePair(name2, HttpClient.encode(value2)));
return get(url, params, authenticate);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param params the request parameters
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, ArrayList<BasicNameValuePair> params, boolean authenticated) throws HttpException {
if (url.indexOf("?") == -1) {
url += "?source=" + CONSUMER_KEY;
} else if (url.indexOf("source") == -1) {
url += "&source=" + CONSUMER_KEY;
}
//以HTML格式获得数据,以便进一步处理
url += "&format=html";
if (null != params && params.size() > 0) {
url += "&" + HttpClient.encodeParameters(params);
}
return http.get(url, authenticated);
}
/**
* Issues an HTTP GET request.
*
* @param url the request url
* @param params the request parameters
* @param paging controls pagination
* @param authenticate if true, the request will be sent with BASIC authentication header
* @return the response
* @throws HttpException
*/
protected Response get(String url, ArrayList<BasicNameValuePair> params, Paging paging, boolean authenticate) throws HttpException {
if (null == params) {
params = new ArrayList<BasicNameValuePair>();
}
if (null != paging) {
if ("" != paging.getMaxId()) {
params.add(new BasicNameValuePair("max_id", String.valueOf(paging.getMaxId())));
}
if ("" != paging.getSinceId()) {
params.add(new BasicNameValuePair("since_id", String.valueOf(paging.getSinceId())));
}
if (-1 != paging.getPage()) {
params.add(new BasicNameValuePair("page", String.valueOf(paging.getPage())));
}
if (-1 != paging.getCount()) {
params.add(new BasicNameValuePair("count", String.valueOf(paging.getCount())));
}
return get(url, params, authenticate);
} else {
return get(url, params, authenticate);
}
}
/**
* 生成POST Parameters助手
* @param nameValuePair 参数(一个或多个)
* @return post parameters
*/
public ArrayList<BasicNameValuePair> createParams(BasicNameValuePair... nameValuePair ) {
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
for (BasicNameValuePair param : nameValuePair) {
params.add(param);
}
return params;
}
/***************** API METHOD START *********************/
/* 搜索相关的方法 */
/**
* Returns tweets that match a specified query.
* <br>This method calls http://api.fanfou.com/users/search.format
* @param query - the search condition
* @return the result
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public QueryResult search(Query query) throws HttpException {
try{
return new QueryResult(get(searchBaseURL + "search/public_timeline.json", query.asPostParameters(), false), this);
}catch(HttpException te){
if(404 == te.getStatusCode()){
return new QueryResult(query);
}else{
throw te;
}
}
}
/**
* Returns the top ten topics that are currently trending on Weibo. The response includes the time of the request, the name of each trend.
* @return the result
* @throws HttpException
* @since fanfoudroid 0.5.0
*/
public Trends getTrends() throws HttpException {
return Trends.constructTrends(get(searchBaseURL + "trends.json", false));
}
private String toDateStr(Date date){
if(null == date){
date = new Date();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/* 消息相关的方法 */
/**
* Returns the 20 most recent statuses from non-protected users who have set a custom user icon.
* <br>This method calls http://api.fanfou.com/statuses/public_timeline.format
*
* @return list of statuses of the Public Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getPublicTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() +
"statuses/public_timeline.json", true));
}
public RateLimitStatus getRateLimitStatus()throws
HttpException {
return new RateLimitStatus(get(getBaseURL() +
"account/rate_limit_status.json", true),this);
}
/**
* Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.
* <br>This method calls http://api.fanfou.com/statuses/home_timeline.format
*
* @return list of the home Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getHomeTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/home_timeline.json", true));
}
/**
* Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.
* <br>This method calls http://api.fanfou.com/statuses/home_timeline.format
*
* @param paging controls pagination
* @return list of the home Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getHomeTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/home_timeline.json", null, paging, true));
}
/**
* Returns the 20 most recent statuses posted in the last 24 hours from the authenticating1 user and that user's friends.
* It's also possible to request another user's friends_timeline via the id parameter below.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
*
* @return list of the Friends Timeline
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFriendsTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json", true));
}
/**
* Returns the 20 most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
*
* @param paging controls pagination
* @return list of the Friends Timeline
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFriendsTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json",null, paging, true));
}
/**
* Returns friend time line by page and count.
* <br>This method calls http://api.fanfou.com/statuses/friends_timeline.format
* @param page
* @param count
* @return
* @throws HttpException
*/
public List<Status> getFriendsTimeline(int page, int count) throws
HttpException {
Paging paging = new Paging(page, count);
return Status.constructStatuses(get(getBaseURL() + "statuses/friends_timeline.json",null, paging, true));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param id specifies the ID or screen name of the user for whom to return the user_timeline
* @param paging controls pagenation
* @return list of the user Timeline
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline(String id, Paging paging)
throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline/" + id + ".json",
null, paging, http.isAuthenticationEnabled()));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the specified userid.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param id specifies the ID or screen name of the user for whom to return the user_timeline
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline(String id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline/" + id + ".json", http.isAuthenticationEnabled()));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getUserTimeline() throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, true));
}
/**
* Returns the most recent statuses posted in the last 24 hours from the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/user_timeline.format
*
* @param paging controls pagination
* @return the 20 most recent statuses posted in the last 24 hours from the user
* @throws HttpException
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getUserTimeline(Paging paging) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, null, paging, true));
}
public List<Status> getUserTimeline(int page, int count) throws
HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/user_timeline.json"
, null, new Paging(page, count), true));
}
/**
* Returns the 20 most recent mentions (status containing @username) for the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/mentions.format
*
* @return the 20 most recent replies
* @throws HttpException
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getMentions() throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
null, true));
}
// by since_id
public List<Status> getMentions(String since_id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
"since_id", String.valueOf(since_id), true));
}
/**
* Returns the 20 most recent mentions (status containing @username) for the authenticating user.
* <br>This method calls http://api.fanfou.com/statuses/mentions.format
*
* @param paging controls pagination
* @return the 20 most recent replies
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getMentions(Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "statuses/mentions.json",
null, paging, true));
}
/**
* Returns a single status, specified by the id parameter. The status's author will be returned inline.
* <br>This method calls http://api.fanfou.com/statuses/show/id.format
*
* @param id the numerical ID of the status you're trying to retrieve
* @return a single status
* @throws HttpException when Weibo service or network is unavailable. 可能因为“你没有通过这个用户的验证“,返回403
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status showStatus(String id) throws HttpException {
return new Status(get(getBaseURL() + "statuses/show/" + id + ".json", true));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>This method calls http://api.fanfou.com/statuses/update.format
*
* @param status the text of your status update
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status updateStatus(String status) throws HttpException{
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source))));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param latitude The location's latitude that this tweet refers to.
* @param longitude The location's longitude that this tweet refers to.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, double latitude, double longitude) throws HttpException, JSONException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("location", latitude + "," + longitude))));
}
/**
* Updates the user's status.
* 如果要使用inreplyToStatusId参数, 那么该status就必须得是@别人的.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param inReplyToStatusId The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, String inReplyToStatusId) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("in_reply_to_status_id", inReplyToStatusId))));
}
/**
* Updates the user's status.
* The text will be trimed if the length of the text is exceeding 160 characters.
* <br>发布消息 http://api.fanfou.com/statuses/update.[json|xml]
*
* @param status the text of your status update
* @param inReplyToStatusId The ID of an existing status that the status to be posted is in reply to. This implicitly sets the in_reply_to_user_id attribute of the resulting status to the user ID of the message being replied to. Invalid/missing status IDs will be ignored.
* @param latitude The location's latitude that this tweet refers to.
* @param longitude The location's longitude that this tweet refers to.
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status updateStatus(String status, String inReplyToStatusId
, double latitude, double longitude) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source),
new BasicNameValuePair("location", latitude + "," + longitude),
new BasicNameValuePair("in_reply_to_status_id", inReplyToStatusId))));
}
/**
* upload the photo.
* The text will be trimed if the length of the text is exceeding 160 characters.
* The image suport.
* <br>上传照片 http://api.fanfou.com/photos/upload.[json|xml]
*
* @param status the text of your status update
* @return the latest status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status uploadPhoto(String status, File file) throws HttpException {
return new Status(http.httpRequest(getBaseURL() + "photos/upload.json",
createParams(new BasicNameValuePair("status", status),
new BasicNameValuePair("source", source)),
file, true, HttpPost.METHOD_NAME));
}
public Status updateStatus(String status, File file) throws HttpException {
return uploadPhoto(status, file);
}
/**
* Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status.
* <br>删除消息 http://api.fanfou.com/statuses/destroy.[json|xml]
*
* @param statusId The ID of the status to destroy.
* @return the deleted status
* @throws HttpException when Weibo service or network is unavailable
* @since 1.0.5
*/
public Status destroyStatus(String statusId) throws HttpException {
return new Status(http.post(getBaseURL() + "statuses/destroy/" + statusId + ".json",
createParams(), true));
}
/**
* Returns extended information of a given user, specified by ID or screen name as per the required id parameter below. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences.
* <br>This method calls http://api.fanfou.com/users/show.format
*
* @param id (cann't be screenName the ID of the user for whom to request the detail
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public User showUser(String id) throws HttpException {
return new User(get(getBaseURL() + "users/show.json",
createParams(new BasicNameValuePair("id", id)), true));
}
/**
* Return a status of repost
* @param to_user_name repost status's user name
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @param new_status the new status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String to_user_name, String repost_status_id,
String repost_status_text, String new_status) throws HttpException {
StringBuilder sb = new StringBuilder();
sb.append(new_status);
sb.append(" ");
sb.append(R.string.pref_rt_prefix_default + ":@");
sb.append(to_user_name);
sb.append(" ");
sb.append(repost_status_text);
sb.append(" ");
String message = sb.toString();
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", message),
new BasicNameValuePair("repost_status_id", repost_status_id)), true));
}
/**
* Return a status of repost
* @param to_user_name repost status's user name
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @param new_status the new status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String new_status, String repost_status_id) throws HttpException
{
return new Status(http.post(getBaseURL() + "statuses/update.json",
createParams(new BasicNameValuePair("status", new_status),
new BasicNameValuePair("source", CONSUMER_KEY),
new BasicNameValuePair("repost_status_id", repost_status_id)), true));
}
/**
* Return a status of repost
* @param repost_status_id repost status id
* @param repost_status_text repost status text
* @return a single status
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public Status repost(String repost_status_id, String new_status, boolean tmp) throws HttpException {
Status repost_to = showStatus(repost_status_id);
String to_user_name = repost_to.getUser().getName();
String repost_status_text = repost_to.getText();
return repost(to_user_name, repost_status_id, repost_status_text, new_status);
}
/* User Methods */
/**
* Returns the specified user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFriendsStatuses() throws HttpException {
return User.constructResult(get(getBaseURL() + "users/friends.json", true));
}
/**
* Returns the specified user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
* <br>分页每页显示100条
*
* @param paging controls pagination
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*
*/
public List<User> getFriendsStatuses(Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json", null,
paging, true));
}
/**
* Returns the user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFriendsStatuses(String id) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json",
createParams(new BasicNameValuePair("id", id)), false));
}
/**
* Returns the user's friends, each with current status inline.
* <br>This method calls http://api.fanfou.com/statuses/friends.format
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @param paging controls pagination (饭否API 默认返回 100 条/页)
* @return the list of friends
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFriendsStatuses(String id, Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "users/friends.json",
createParams(new BasicNameValuePair("id", id)), paging, false));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<User> getFollowersStatuses() throws HttpException {
return User.constructResult(get(getBaseURL() + "statuses/followers.json", true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers.json", null
, paging, true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param id The ID (not screen name) of the user for whom to request a list of followers.
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(String id) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers/" + id + ".json", true));
}
/**
* Returns the authenticating user's followers, each with current status inline. They are ordered by the order in which they joined Weibo (this is going to be changed).
* <br>This method calls http://api.fanfou.com/statuses/followers.format
*
* @param id The ID or screen name of the user for whom to request a list of followers.
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<User> getFollowersStatuses(String id, Paging paging) throws HttpException {
return User.constructUsers(get(getBaseURL() + "statuses/followers/" + id +
".json", null, paging, true));
}
/* 私信功能 */
/**
* Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.
* The text will be trimed if the length of the text is exceeding 140 characters.
* <br>This method calls http://api.fanfou.com/direct_messages/new.format
* <br>通过客户端只能给互相关注的人发私信
*
* @param id the ID of the user to whom send the direct message
* @param text String
* @return DirectMessage
* @throws HttpException when Weibo service or network is unavailable
@see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public DirectMessage sendDirectMessage(String id, String text) throws HttpException {
return new DirectMessage(http.post(getBaseURL() + "direct_messages/new.json",
createParams(new BasicNameValuePair("user", id),
new BasicNameValuePair("text", text))).asJSONObject());
}
//TODO: need be unit tested by in_reply_to_id.
/**
* Sends a new direct message to the specified user from the authenticating user. Requires both the user and text parameters below.
* The text will be trimed if the length of the text is exceeding 140 characters.
* <br>通过客户端只能给互相关注的人发私信
*
* @param id
* @param text
* @param in_reply_to_id
* @return
* @throws HttpException
*/
public DirectMessage sendDirectMessage(String id, String text, String in_reply_to_id)
throws HttpException {
return new DirectMessage(http.post(getBaseURL() + "direct_messages/new.json",
createParams(new BasicNameValuePair("user", id),
new BasicNameValuePair("text", text),
new BasicNameValuePair("is_reply_to_id", in_reply_to_id))).asJSONObject());
}
/**
* Destroys the direct message specified in the required ID parameter. The authenticating user must be the recipient of the specified direct message.
* <br>This method calls http://api.fanfou.com/direct_messages/destroy/id.format
*
* @param id the ID of the direct message to destroy
* @return the deleted direct message
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public DirectMessage destroyDirectMessage(String id) throws
HttpException {
return new DirectMessage(http.post(getBaseURL() +
"direct_messages/destroy/" + id + ".json", true).asJSONObject());
}
/**
* Returns a list of the direct messages sent to the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getDirectMessages() throws HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() + "direct_messages.json", true));
}
/**
* Returns a list of the direct messages sent to the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages.format
*
* @param paging controls pagination
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getDirectMessages(Paging paging) throws HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL()
+ "direct_messages.json", null, paging, true));
}
/**
* Returns a list of the direct messages sent by the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages/sent.format
*
* @return List
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getSentDirectMessages() throws
HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() +
"direct_messages/sent.json", null, true));
}
/**
* Returns a list of the direct messages sent by the authenticating user.
* <br>This method calls http://api.fanfou.com/direct_messages/sent.format
*
* @param paging controls pagination
* @return List 默认返回20条, 一次最多返回60条
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<DirectMessage> getSentDirectMessages(Paging paging) throws
HttpException {
return DirectMessage.constructDirectMessages(get(getBaseURL() +
"direct_messages/sent.json", null, paging, true));
}
/* 收藏功能 */
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites() throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", createParams(), true));
}
public List<Status> getFavorites(Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", createParams(), paging, true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param page the number of page
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites(int page) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites.json", "page", String.valueOf(page), true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param id the ID or screen name of the user for whom to request a list of favorite statuses
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
* @since fanfoudroid 0.5.0
*/
public List<Status> getFavorites(String id) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", createParams(), true));
}
/**
* Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter in the requested format.
*
* @param id the ID or screen name of the user for whom to request a list of favorite statuses
* @param page the number of page
* @return List<Status>
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public List<Status> getFavorites(String id, int page) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", "page", String.valueOf(page), true));
}
public List<Status> getFavorites(String id, Paging paging) throws HttpException {
return Status.constructStatuses(get(getBaseURL() + "favorites/" + id + ".json", null, paging, true));
}
/**
* Favorites the status specified in the ID parameter as the authenticating user. Returns the favorite status when successful.
*
* @param id the ID of the status to favorite
* @return Status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status createFavorite(String id) throws HttpException {
return new Status(http.post(getBaseURL() + "favorites/create/" + id + ".json", true));
}
/**
* Un-favorites the status specified in the ID parameter as the authenticating user. Returns the un-favorited status in the requested format when successful.
*
* @param id the ID of the status to un-favorite
* @return Status
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public Status destroyFavorite(String id) throws HttpException {
return new Status(http.post(getBaseURL() + "favorites/destroy/" + id + ".json", true));
}
/**
* Enables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
* @param id String
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @deprecated 饭否该功能暂时关闭, 等待该功能开放.
*/
public User enableNotification(String id) throws HttpException {
return new User(http.post(getBaseURL() + "notifications/follow/" + id + ".json", true).asJSONObject());
}
/**
* Disables notifications for updates from the specified user to the authenticating user. Returns the specified user when successful.
* @param id String
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否该功能暂时关闭, 等待该功能开放.
* @since fanfoudroid 0.5.0
*/
public User disableNotification(String id) throws HttpException {
return new User(http.post(getBaseURL() + "notifications/leave/" + id + ".json", true).asJSONObject());
}
/* 黑名单 */
/**
* Blocks the user specified in the ID parameter as the authenticating user. Returns the blocked user in the requested format when successful.
* @param id the ID or screen_name of the user to block
* @return the blocked user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public User createBlock(String id) throws HttpException {
return new User(http.post(getBaseURL() + "blocks/create/" + id + ".json", true).asJSONObject());
}
/**
* Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful.
* @param id the ID or screen_name of the user to block
* @return the unblocked user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public User destroyBlock(String id) throws HttpException {
return new User(http.post(getBaseURL() + "blocks/destroy/" + id + ".json", true).asJSONObject());
}
/**
* Tests if a friendship exists between two users.
* @param id The ID or screen_name of the potentially blocked user.
* @return if the authenticating user is blocking a target user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public boolean existsBlock(String id) throws HttpException {
try{
return -1 == get(getBaseURL() + "blocks/exists/" + id + ".json", true).
asString().indexOf("<error>You are not blocking this user.</error>");
}catch(HttpException te){
if(te.getStatusCode() == 404){
return false;
}
throw te;
}
}
/**
* Returns a list of user objects that the authenticating user is blocking.
* @return a list of user objects that the authenticating user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public List<User> getBlockingUsers() throws
HttpException {
return User.constructUsers(get(getBaseURL() +
"blocks/blocking.json", true));
}
/**
* Returns a list of user objects that the authenticating user is blocking.
* @param page the number of page
* @return a list of user objects that the authenticating user
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public List<User> getBlockingUsers(int page) throws
HttpException {
return User.constructUsers(get(getBaseURL() +
"blocks/blocking.json?page=" + page, true));
}
/**
* Returns an array of numeric user ids the authenticating user is blocking.
* @return Returns an array of numeric user ids the authenticating user is blocking.
* @throws HttpException when Weibo service or network is unavailable
* @deprecated 饭否暂无此功能, 期待此功能
* @since fanfoudroid 0.5.0
*/
public IDs getBlockingUsersIDs() throws HttpException {
return new IDs(get(getBaseURL() + "blocks/blocking/ids.json", true),this);
}
/* 好友关系方法 */
/**
* Tests if a friendship exists between two users.
*
* @param userA The ID or screen_name of the first user to test friendship for.
* @param userB The ID or screen_name of the second user to test friendship for.
* @return if a friendship exists between two users.
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public boolean existsFriendship(String userA, String userB) throws HttpException {
return -1 != get(getBaseURL() + "friendships/exists.json", "user_a", userA, "user_b", userB, true).
asString().indexOf("true");
}
/**
* Discontinues friendship with the user specified in the ID parameter as the authenticating user. Returns the un-friended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
*
* @param id the ID or screen name of the user for whom to request a list of friends
* @return User
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User destroyFriendship(String id) throws HttpException {
return new User(http.post(getBaseURL() + "friendships/destroy/" + id + ".json", createParams(), true).asJSONObject());
}
/**
* Befriends the user specified in the ID parameter as the authenticating user. Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
*
* @param id the ID or screen name of the user to be befriended
* @return the befriended user
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User createFriendship(String id) throws HttpException {
return new User(http.post(getBaseURL() + "friendships/create/" + id + ".json", createParams(), true).asJSONObject());
}
/**
* Returns an array of numeric IDs for every user the specified user is followed by.
* @param userId Specifies the ID of the user for whom to return the followers list.
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return The ID or screen_name of the user to retrieve the friends ID list for.
* @throws HttpException when Weibo service or network is unavailable
* @since Weibo4J 2.0.10
* @see <a href="http://open.t.sina.com.cn/wiki/index.php/Followers/ids">followers/ids </a>
*/
public IDs getFollowersIDs(String userId) throws HttpException {
return new IDs(get(getBaseURL() + "followers/ids.json?user_id=" + userId, true), this);
}
/**
* Returns an array of numeric IDs for every user the specified user is followed by.
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return The ID or screen_name of the user to retrieve the friends ID list for.
* @throws HttpException when Weibo service or network is unavailable
* @since Weibo4J 2.0.10
* @see <a href="http://open.t.sina.com.cn/wiki/index.php/Followers/ids">followers/ids </a>
*/
public IDs getFollowersIDs() throws HttpException {
return new IDs(get(getBaseURL() + "followers/ids.json", true), this);
}
public List<com.ch_linghu.fanfoudroid.fanfou.User> getFollowersList(String userId,Paging paging) throws HttpException{
return User.constructUsers(get(getBaseURL() + "users/followers.json",
createParams(new BasicNameValuePair("id", userId)),paging, false));
}
public List<com.ch_linghu.fanfoudroid.fanfou.User> getFollowersList(String userId) throws HttpException{
return User.constructUsers(get(getBaseURL() + "users/followers.json",
createParams(new BasicNameValuePair("id", userId)), false));
}
/**
* Returns an array of numeric IDs for every user the authenticating user is following.
* @return an array of numeric IDs for every user the authenticating user is following
* @throws HttpException when Weibo service or network is unavailable
* @since androidroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public IDs getFriendsIDs() throws HttpException {
return getFriendsIDs(-1l);
}
/**
* Returns an array of numeric IDs for every user the authenticating user is following.
* <br/>饭否无cursor参数
*
* @param cursor Specifies the page number of the results beginning at 1. A single page contains 5000 ids. This is recommended for users with large ID lists. If not provided all ids are returned.
* @return an array of numeric IDs for every user the authenticating user is following
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public IDs getFriendsIDs(long cursor) throws HttpException {
return new IDs(get(getBaseURL() + "friends/ids.json?cursor=" + cursor, true), this);
}
/**
* 获取关注者id列表
* @param userId
* @return
* @throws HttpException
*/
public IDs getFriendsIDs(String userId) throws HttpException{
return new IDs(get(getBaseURL() + "friends/ids.json?id=" +userId , true), this);
}
/* 账户方法 */
/**
* Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; returns a 401 status code and an error message if not. Use this method to test if supplied user credentials are valid.
* 注意: 如果使用 错误的用户名/密码 多次登录后,饭否会锁IP
* 返回提示为“尝试次数过多,请去 http://fandou.com 登录“,且需输入验证码
*
* 登录成功返回 200 code
* 登录失败返回 401 code
* 使用HttpException的getStatusCode取得code
*
* @return user
* @since androidroid 0.5.0
* @throws HttpException when Weibo service or network is unavailable
* @see <a href="http://code.google.com/p/fanfou-api/wiki/ApiDocumentation"</a>
*/
public User verifyCredentials() throws HttpException {
return new User(get(getBaseURL() + "account/verify_credentials.json"
, true).asJSONObject());
}
/* Saved Searches Methods */
/**
* Returns the authenticated user's saved search queries.
* @return Returns an array of numeric user ids the authenticating user is blocking.
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public List<SavedSearch> getSavedSearches() throws HttpException {
return SavedSearch.constructSavedSearches(get(getBaseURL() + "saved_searches.json", true));
}
/**
* Retrieve the data for a saved search owned by the authenticating user specified by the given id.
* @param id The id of the saved search to be retrieved.
* @return the data for a saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch showSavedSearch(int id) throws HttpException {
return new SavedSearch(get(getBaseURL() + "saved_searches/show/" + id
+ ".json", true));
}
/**
* Retrieve the data for a saved search owned by the authenticating user specified by the given id.
* @return the data for a created saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch createSavedSearch(String query) throws HttpException {
return new SavedSearch(http.post(getBaseURL() + "saved_searches/create.json",
createParams(new BasicNameValuePair("query", query)), true));
}
/**
* Destroys a saved search for the authenticated user. The search specified by id must be owned by the authenticating user.
* @param id The id of the saved search to be deleted.
* @return the data for a destroyed saved search
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public SavedSearch destroySavedSearch(int id) throws HttpException {
return new SavedSearch(http.post(getBaseURL() + "saved_searches/destroy/" + id
+ ".json", true));
}
/* Help Methods */
/**
* Returns the string "ok" in the requested format with a 200 OK HTTP status code.
* @return true if the API is working
* @throws HttpException when Weibo service or network is unavailable
* @since fanfoudroid 0.5.0
*/
public boolean test() throws HttpException {
return -1 != get(getBaseURL() + "help/test.json", false).
asString().indexOf("ok");
}
/***************** API METHOD END *********************/
private SimpleDateFormat format = new SimpleDateFormat(
"EEE, d MMM yyyy HH:mm:ss z", Locale.US);
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Weibo weibo = (Weibo) o;
if (!baseURL.equals(weibo.baseURL)) return false;
if (!format.equals(weibo.format)) return false;
if (!http.equals(weibo.http)) return false;
if (!searchBaseURL.equals(weibo.searchBaseURL)) return false;
if (!source.equals(weibo.source)) return false;
return true;
}
@Override
public int hashCode() {
int result = http.hashCode();
result = 31 * result + baseURL.hashCode();
result = 31 * result + searchBaseURL.hashCode();
result = 31 * result + source.hashCode();
result = 31 * result + format.hashCode();
return result;
}
@Override
public String toString() {
return "Weibo{" +
"http=" + http +
", baseURL='" + baseURL + '\'' +
", searchBaseURL='" + searchBaseURL + '\'' +
", source='" + source + '\'' +
", format=" + format +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing one single status of a user.
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class Status extends WeiboResponse implements java.io.Serializable {
private static final long serialVersionUID = 1608000492860584608L;
private Date createdAt;
private String id;
private String text;
private String source;
private boolean isTruncated;
private String inReplyToStatusId;
private String inReplyToUserId;
private boolean isFavorited;
private String inReplyToScreenName;
private double latitude = -1;
private double longitude = -1;
private String thumbnail_pic;
private String bmiddle_pic;
private String original_pic;
private String photo_url;
private RetweetDetails retweetDetails;
private User user = null;
/*package*/Status(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(res, elem, weibo);
}
/*package*/Status(Response res, Element elem, Weibo weibo) throws
HttpException {
super(res);
init(res, elem, weibo);
}
Status(Response res)throws HttpException{
super(res);
JSONObject json=res.asJSONObject();
try {
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
isFavorited = getBoolean("favorited", json);
// System.out.println("json photo" + json.getJSONObject("photo"));
if(!json.isNull("photo")) {
// System.out.println("not null" + json.getJSONObject("photo"));
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
// System.out.println("Null");
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
if(!json.isNull("user"))
user = new User(json.getJSONObject("user"));
inReplyToScreenName=json.getString("in_reply_to_screen_name");
if(!json.isNull("retweetDetails")){
retweetDetails = new RetweetDetails(json.getJSONObject("retweetDetails"));
}
} catch (JSONException je) {
throw new HttpException(je.getMessage() + ":" + json.toString(), je);
}
}
/* modify by sycheng add some field*/
public Status(JSONObject json)throws HttpException, JSONException{
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
isFavorited = getBoolean("favorited", json);
isTruncated=getBoolean("truncated", json);
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
inReplyToScreenName=json.getString("in_reply_to_screen_name");
if(!json.isNull("photo")) {
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
user = new User(json.getJSONObject("user"));
}
public Status(String str) throws HttpException, JSONException {
// StatusStream uses this constructor
super();
JSONObject json = new JSONObject(str);
id = json.getString("id");
text = json.getString("text");
source = json.getString("source");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
inReplyToStatusId = getString("in_reply_to_status_id", json);
inReplyToUserId = getString("in_reply_to_user_id", json);
isFavorited = getBoolean("favorited", json);
if(!json.isNull("photo")) {
Photo photo = new Photo(json.getJSONObject("photo"));
thumbnail_pic = photo.getThumbnail_pic();
bmiddle_pic = photo.getBmiddle_pic();
original_pic = photo.getOriginal_pic();
} else {
thumbnail_pic = "";
bmiddle_pic = "";
original_pic = "";
}
user = new User(json.getJSONObject("user"));
}
private void init(Response res, Element elem, Weibo weibo) throws
HttpException {
ensureRootNodeNameIs("status", elem);
user = new User(res, (Element) elem.getElementsByTagName("user").item(0)
, weibo);
id = getChildString("id", elem);
text = getChildText("text", elem);
source = getChildText("source", elem);
createdAt = getChildDate("created_at", elem);
isTruncated = getChildBoolean("truncated", elem);
inReplyToStatusId = getChildString("in_reply_to_status_id", elem);
inReplyToUserId = getChildString("in_reply_to_user_id", elem);
isFavorited = getChildBoolean("favorited", elem);
inReplyToScreenName = getChildText("in_reply_to_screen_name", elem);
NodeList georssPoint = elem.getElementsByTagName("georss:point");
if(1 == georssPoint.getLength()){
String[] point = georssPoint.item(0).getFirstChild().getNodeValue().split(" ");
if(!"null".equals(point[0]))
latitude = Double.parseDouble(point[0]);
if(!"null".equals(point[1]))
longitude = Double.parseDouble(point[1]);
}
NodeList retweetDetailsNode = elem.getElementsByTagName("retweet_details");
if(1 == retweetDetailsNode.getLength()){
retweetDetails = new RetweetDetails(res,(Element)retweetDetailsNode.item(0),weibo);
}
}
/**
* Return the created_at
*
* @return created_at
* @since Weibo4J 1.1.0
*/
public Date getCreatedAt() {
return this.createdAt;
}
/**
* Returns the id of the status
*
* @return the id
*/
public String getId() {
return this.id;
}
/**
* Returns the text of the status
*
* @return the text
*/
public String getText() {
return this.text;
}
/**
* Returns the source
*
* @return the source
* @since Weibo4J 1.0.4
*/
public String getSource() {
return this.source;
}
/**
* Test if the status is truncated
*
* @return true if truncated
* @since Weibo4J 1.0.4
*/
public boolean isTruncated() {
return isTruncated;
}
/**
* Returns the in_reply_tostatus_id
*
* @return the in_reply_tostatus_id
* @since Weibo4J 1.0.4
*/
public String getInReplyToStatusId() {
return inReplyToStatusId;
}
/**
* Returns the in_reply_user_id
*
* @return the in_reply_tostatus_id
* @since Weibo4J 1.0.4
*/
public String getInReplyToUserId() {
return inReplyToUserId;
}
/**
* Returns the in_reply_to_screen_name
*
* @return the in_in_reply_to_screen_name
* @since Weibo4J 2.0.4
*/
public String getInReplyToScreenName() {
return inReplyToScreenName;
}
/**
* returns The location's latitude that this tweet refers to.
*
* @since Weibo4J 2.0.10
*/
public double getLatitude() {
return latitude;
}
/**
* returns The location's longitude that this tweet refers to.
*
* @since Weibo4J 2.0.10
*/
public double getLongitude() {
return longitude;
}
/**
* Test if the status is favorited
*
* @return true if favorited
* @since Weibo4J 1.0.4
*/
public boolean isFavorited() {
return isFavorited;
}
public String getThumbnail_pic() {
return thumbnail_pic;
}
public String getBmiddle_pic() {
return bmiddle_pic;
}
public String getOriginal_pic() {
return original_pic;
}
/**
* Return the user
*
* @return the user
*/
public User getUser() {
return user;
}
// TODO: 等合并Tweet, Status
public int getType() {
return -1111111;
}
/**
*
* @since Weibo4J 2.0.10
*/
public boolean isRetweet(){
return null != retweetDetails;
}
/**
*
* @since Weibo4J 2.0.10
*/
public RetweetDetails getRetweetDetails() {
return retweetDetails;
}
/*package*/
static List<Status> constructStatuses(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<Status>(0);
} else {
try {
ensureRootNodeNameIs("statuses", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"status");
int size = list.getLength();
List<Status> statuses = new ArrayList<Status>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
statuses.add(new Status(res, status, weibo));
}
return statuses;
} catch (HttpException te) {
ensureRootNodeNameIs("nil-classes", doc);
return new ArrayList<Status>(0);
}
}
}
/* modify by sycheng add json call method */
/* package */
static List<Status> constructStatuses(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<Status> statuses = new ArrayList<Status>(size);
for (int i = 0; i < size; i++) {
statuses.add(new Status(list.getJSONObject(i)));
}
return statuses;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
// return obj instanceof Status && ((Status) obj).id == this.id;
return obj instanceof Status && this.id.equals(((Status) obj).id);
}
@Override
public String toString() {
return "Status{" +
"createdAt=" + createdAt +
", id=" + id +
", text='" + text + '\'' +
", source='" + source + '\'' +
", isTruncated=" + isTruncated +
", inReplyToStatusId=" + inReplyToStatusId +
", inReplyToUserId=" + inReplyToUserId +
", isFavorited=" + isFavorited +
", thumbnail_pic=" + thumbnail_pic +
", bmiddle_pic=" + bmiddle_pic +
", original_pic=" + original_pic +
", inReplyToScreenName='" + inReplyToScreenName + '\'' +
", latitude=" + latitude +
", longitude=" + longitude +
", retweetDetails=" + retweetDetails +
", user=" + user +
'}';
}
public boolean isEmpty() {
return (null == id);
}
}
| Java |
package com.ch_linghu.fanfoudroid.fanfou;
/**
* An exception class that will be thrown when WeiboAPI calls are failed.<br>
* In case the Fanfou server returned HTTP error code, you can get the HTTP status code using getStatusCode() method.
*/
public class WeiboException extends Exception {
private int statusCode = -1;
private static final long serialVersionUID = -2623309261327598087L;
public WeiboException(String msg) {
super(msg);
}
public WeiboException(Exception cause) {
super(cause);
}
public WeiboException(String msg, int statusCode) {
super(msg);
this.statusCode = statusCode;
}
public WeiboException(String msg, Exception cause) {
super(msg, cause);
}
public WeiboException(String msg, Exception cause, int statusCode) {
super(msg, cause);
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing a Saved Search
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.8
*/
public class SavedSearch extends WeiboResponse {
private Date createdAt;
private String query;
private int position;
private String name;
private int id;
private static final long serialVersionUID = 3083819860391598212L;
/*package*/ SavedSearch(Response res) throws HttpException {
super(res);
init(res.asJSONObject());
}
/*package*/ SavedSearch(Response res, JSONObject json) throws HttpException {
super(res);
init(json);
}
/*package*/ SavedSearch(JSONObject savedSearch) throws HttpException {
init(savedSearch);
}
/*package*/ static List<SavedSearch> constructSavedSearches(Response res) throws HttpException {
JSONArray json = res.asJSONArray();
List<SavedSearch> savedSearches;
try {
savedSearches = new ArrayList<SavedSearch>(json.length());
for(int i=0;i<json.length();i++){
savedSearches.add(new SavedSearch(res,json.getJSONObject(i)));
}
return savedSearches;
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + res.asString(), jsone);
}
}
private void init(JSONObject savedSearch) throws HttpException {
try {
createdAt = parseDate(savedSearch.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
query = getString("query", savedSearch, true);
name = getString("name", savedSearch, true);
id = getInt("id", savedSearch);
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + savedSearch.toString(), jsone);
}
}
public Date getCreatedAt() {
return createdAt;
}
public String getQuery() {
return query;
}
public int getPosition() {
return position;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof SavedSearch)) return false;
SavedSearch that = (SavedSearch) o;
if (id != that.id) return false;
if (position != that.position) return false;
if (!createdAt.equals(that.createdAt)) return false;
if (!name.equals(that.name)) return false;
if (!query.equals(that.query)) return false;
return true;
}
@Override
public int hashCode() {
int result = createdAt.hashCode();
result = 31 * result + query.hashCode();
result = 31 * result + position;
result = 31 * result + name.hashCode();
result = 31 * result + id;
return result;
}
@Override
public String toString() {
return "SavedSearch{" +
"createdAt=" + createdAt +
", query='" + query + '\'' +
", position=" + position +
", name='" + name + '\'' +
", id=" + id +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import org.apache.http.message.BasicNameValuePair;
/**
* A data class represents search query.
*/
public class Query {
private String query = null;
private String lang = null;
private int rpp = -1;
private int page = -1;
private long sinceId = -1;
private String maxId = null;
private String geocode = null;
public Query(){
}
public Query(String query){
this.query = query;
}
public String getQuery() {
return query;
}
/**
* Sets the query string
* @param query - the query string
*/
public void setQuery(String query) {
this.query = query;
}
public String getLang() {
return lang;
}
/**
* restricts tweets to the given language, given by an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
* @param lang an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
*/
public void setLang(String lang) {
this.lang = lang;
}
public int getRpp() {
return rpp;
}
/**
* sets the number of tweets to return per page, up to a max of 100
* @param rpp the number of tweets to return per page
*/
public void setRpp(int rpp) {
this.rpp = rpp;
}
public int getPage() {
return page;
}
/**
* sets the page number (starting at 1) to return, up to a max of roughly 1500 results
* @param page - the page number (starting at 1) to return
*/
public void setPage(int page) {
this.page = page;
}
public long getSinceId() {
return sinceId;
}
/**
* returns tweets with status ids greater than the given id.
* @param sinceId - returns tweets with status ids greater than the given id
*/
public void setSinceId(long sinceId) {
this.sinceId = sinceId;
}
public String getMaxId() {
return maxId;
}
/**
* returns tweets with status ids less than the given id.
* @param maxId - returns tweets with status ids less than the given id
*/
public void setMaxId(String maxId) {
this.maxId = maxId;
}
public String getGeocode() {
return geocode;
}
public static final String MILES = "mi";
public static final String KILOMETERS = "km";
/**
* returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Weibo profile
* @param latitude latitude
* @param longtitude longtitude
* @param radius radius
* @param unit Query.MILES or Query.KILOMETERS
*/
public void setGeoCode(double latitude, double longtitude, double radius
, String unit) {
this.geocode = latitude + "," + longtitude + "," + radius + unit;
}
public ArrayList<BasicNameValuePair> asPostParameters(){
ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
appendParameter("q", query, params);
appendParameter("lang", lang, params);
appendParameter("page", page, params);
appendParameter("since_id",sinceId , params);
appendParameter("max_id", maxId, params);
appendParameter("geocode", geocode, params);
return params;
}
private void appendParameter(String name, String value, ArrayList<BasicNameValuePair> params) {
if (null != value) {
params.add(new BasicNameValuePair(name, value));
}
}
private void appendParameter(String name, long value, ArrayList<BasicNameValuePair> params) {
if (0 <= value) {
params.add(new BasicNameValuePair(name, value + ""));
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Query query1 = (Query) o;
if (page != query1.page) return false;
if (rpp != query1.rpp) return false;
if (sinceId != query1.sinceId) return false;
if (geocode != null ? !geocode.equals(query1.geocode) : query1.geocode != null)
return false;
if (lang != null ? !lang.equals(query1.lang) : query1.lang != null)
return false;
if (query != null ? !query.equals(query1.query) : query1.query != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = query != null ? query.hashCode() : 0;
result = 31 * result + (lang != null ? lang.hashCode() : 0);
result = 31 * result + rpp;
result = 31 * result + page;
result = 31 * result + (int) (sinceId ^ (sinceId >>> 32));
result = 31 * result + (geocode != null ? geocode.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Query{" +
"query='" + query + '\'' +
", lang='" + lang + '\'' +
", rpp=" + rpp +
", page=" + page +
", sinceId=" + sinceId +
", geocode='" + geocode + '\'' +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HTMLEntity;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* Super class of Weibo Response objects.
*
* @see weibo4j.DirectMessage
* @see weibo4j.Status
* @see weibo4j.User
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class WeiboResponse implements java.io.Serializable {
private static Map<String,SimpleDateFormat> formatMap = new HashMap<String,SimpleDateFormat>();
private static final long serialVersionUID = 3519962197957449562L;
private transient int rateLimitLimit = -1;
private transient int rateLimitRemaining = -1;
private transient long rateLimitReset = -1;
public WeiboResponse() {
}
public WeiboResponse(Response res) {
}
protected static void ensureRootNodeNameIs(String rootName, Element elem) throws HttpException {
if (!rootName.equals(elem.getNodeName())) {
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/.");
}
}
protected static void ensureRootNodeNameIs(String[] rootNames, Element elem) throws HttpException {
String actualRootName = elem.getNodeName();
for (String rootName : rootNames) {
if (rootName.equals(actualRootName)) {
return;
}
}
String expected = "";
for (int i = 0; i < rootNames.length; i++) {
if (i != 0) {
expected += " or ";
}
expected += rootNames[i];
}
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + expected + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/.");
}
protected static void ensureRootNodeNameIs(String rootName, Document doc) throws HttpException {
Element elem = doc.getDocumentElement();
if (!rootName.equals(elem.getNodeName())) {
throw new HttpException("Unexpected root node name:" + elem.getNodeName() + ". Expected:" + rootName + ". Check the availability of the Weibo API at http://open.t.sina.com.cn/");
}
}
protected static boolean isRootNodeNilClasses(Document doc) {
String root = doc.getDocumentElement().getNodeName();
return "nil-classes".equals(root) || "nilclasses".equals(root);
}
protected static String getChildText( String str, Element elem ) {
return HTMLEntity.unescape(getTextContent(str,elem));
}
protected static String getTextContent(String str, Element elem){
NodeList nodelist = elem.getElementsByTagName(str);
if (nodelist.getLength() > 0) {
Node node = nodelist.item(0).getFirstChild();
if (null != node) {
String nodeValue = node.getNodeValue();
return null != nodeValue ? nodeValue : "";
}
}
return "";
}
/*modify by sycheng add "".equals(str) */
protected static int getChildInt(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return -1;
} else {
return Integer.valueOf(str2);
}
}
/*modify by sycheng add "".equals(str) */
protected static String getChildString(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return "";
} else {
return String.valueOf(str2);
}
}
protected static long getChildLong(String str, Element elem) {
String str2 = getTextContent(str, elem);
if (null == str2 || "".equals(str2)||"null".equals(str)) {
return -1;
} else {
return Long.valueOf(str2);
}
}
protected static String getString(String name, JSONObject json, boolean decode) {
String returnValue = null;
try {
returnValue = json.getString(name);
if (decode) {
try {
returnValue = URLDecoder.decode(returnValue, "UTF-8");
} catch (UnsupportedEncodingException ignore) {
}
}
} catch (JSONException ignore) {
// refresh_url could be missing
}
return returnValue;
}
protected static boolean getChildBoolean(String str, Element elem) {
String value = getTextContent(str, elem);
return Boolean.valueOf(value);
}
protected static Date getChildDate(String str, Element elem) throws HttpException {
return getChildDate(str, elem, "EEE MMM d HH:mm:ss z yyyy");
}
protected static Date getChildDate(String str, Element elem, String format) throws HttpException {
return parseDate(getChildText(str, elem),format);
}
protected static Date parseDate(String str, String format) throws HttpException{
if(str==null||"".equals(str)){
return null;
}
SimpleDateFormat sdf = formatMap.get(format);
if (null == sdf) {
sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
formatMap.put(format, sdf);
}
try {
synchronized(sdf){
// SimpleDateFormat is not thread safe
return sdf.parse(str);
}
} catch (ParseException pe) {
throw new HttpException("Unexpected format(" + str + ") returned from sina.com.cn");
}
}
protected static int getInt(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return -1;
}
return Integer.parseInt(str);
}
protected static String getString(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return "";
}
return String.valueOf(str);
}
protected static long getLong(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return -1;
}
return Long.parseLong(str);
}
protected static boolean getBoolean(String key, JSONObject json) throws JSONException {
String str = json.getString(key);
if(null == str || "".equals(str)||"null".equals(str)){
return false;
}
return Boolean.valueOf(str);
}
public int getRateLimitLimit() {
return rateLimitLimit;
}
public int getRateLimitRemaining() {
return rateLimitRemaining;
}
public long getRateLimitReset() {
return rateLimitReset;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.database.Cursor;
import android.util.Log;
import com.ch_linghu.fanfoudroid.db.MessageTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.db.UserInfoTable;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Basic user information element
*/
public class User extends WeiboResponse implements java.io.Serializable {
static final String[] POSSIBLE_ROOT_NAMES = new String[]{"user", "sender", "recipient", "retweeting_user"};
private Weibo weibo;
private String id;
private String name;
private String screenName;
private String location;
private String description;
private String birthday;
private String gender;
private String profileImageUrl;
private String url;
private boolean isProtected;
private int followersCount;
private Date statusCreatedAt;
private String statusId = "";
private String statusText = null;
private String statusSource = null;
private boolean statusTruncated = false;
private String statusInReplyToStatusId = "";
private String statusInReplyToUserId = "";
private boolean statusFavorited = false;
private String statusInReplyToScreenName = null;
private String profileBackgroundColor;
private String profileTextColor;
private String profileLinkColor;
private String profileSidebarFillColor;
private String profileSidebarBorderColor;
private int friendsCount;
private Date createdAt;
private int favouritesCount;
private int utcOffset;
private String timeZone;
private String profileBackgroundImageUrl;
private String profileBackgroundTile;
private boolean following;
private boolean notificationEnabled;
private int statusesCount;
private boolean geoEnabled;
private boolean verified;
private static final long serialVersionUID = -6345893237975349030L;
/*package*/User(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(elem, weibo);
}
/*package*/public User(Response res, Element elem, Weibo weibo) throws HttpException {
super(res);
init(elem, weibo);
}
/*package*/public User(JSONObject json) throws HttpException {
super();
init(json);
}
/*package*/User(Response res) throws HttpException {
super();
init(res.asJSONObject());
}
User(){
}
private void init(JSONObject json) throws HttpException {
try {
id = json.getString("id");
name = json.getString("name");
screenName = json.getString("screen_name");
location = json.getString("location");
gender = json.getString("gender");
birthday = json.getString("birthday");
description = json.getString("description");
profileImageUrl = json.getString("profile_image_url");
url = json.getString("url");
isProtected = json.getBoolean("protected");
followersCount = json.getInt("followers_count");
profileBackgroundColor = json.getString("profile_background_color");
profileTextColor = json.getString("profile_text_color");
profileLinkColor = json.getString("profile_link_color");
profileSidebarFillColor = json.getString("profile_sidebar_fill_color");
profileSidebarBorderColor = json.getString("profile_sidebar_border_color");
friendsCount = json.getInt("friends_count");
createdAt = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
favouritesCount = json.getInt("favourites_count");
utcOffset = getInt("utc_offset", json);
// timeZone = json.getString("time_zone");
profileBackgroundImageUrl = json.getString("profile_background_image_url");
profileBackgroundTile = json.getString("profile_background_tile");
following = getBoolean("following", json);
notificationEnabled = getBoolean("notifications", json);
statusesCount = json.getInt("statuses_count");
if (!json.isNull("status")) {
JSONObject status = json.getJSONObject("status");
statusCreatedAt = parseDate(status.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
statusId = status.getString("id");
statusText = status.getString("text");
statusSource = status.getString("source");
statusTruncated = status.getBoolean("truncated");
// statusInReplyToStatusId = status.getString("in_reply_to_status_id");
statusInReplyToStatusId = status.getString("in_reply_to_lastmsg_id"); // 饭否不知为什么把这个参数的名称改了
statusInReplyToUserId = status.getString("in_reply_to_user_id");
statusFavorited = status.getBoolean("favorited");
statusInReplyToScreenName = status.getString("in_reply_to_screen_name");
}
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
private void init(Element elem, Weibo weibo) throws HttpException {
this.weibo = weibo;
ensureRootNodeNameIs(POSSIBLE_ROOT_NAMES, elem);
id = getChildString("id", elem);
name = getChildText("name", elem);
screenName = getChildText("screen_name", elem);
location = getChildText("location", elem);
description = getChildText("description", elem);
profileImageUrl = getChildText("profile_image_url", elem);
url = getChildText("url", elem);
isProtected = getChildBoolean("protected", elem);
followersCount = getChildInt("followers_count", elem);
profileBackgroundColor = getChildText("profile_background_color", elem);
profileTextColor = getChildText("profile_text_color", elem);
profileLinkColor = getChildText("profile_link_color", elem);
profileSidebarFillColor = getChildText("profile_sidebar_fill_color", elem);
profileSidebarBorderColor = getChildText("profile_sidebar_border_color", elem);
friendsCount = getChildInt("friends_count", elem);
createdAt = getChildDate("created_at", elem);
favouritesCount = getChildInt("favourites_count", elem);
utcOffset = getChildInt("utc_offset", elem);
// timeZone = getChildText("time_zone", elem);
profileBackgroundImageUrl = getChildText("profile_background_image_url", elem);
profileBackgroundTile = getChildText("profile_background_tile", elem);
following = getChildBoolean("following", elem);
notificationEnabled = getChildBoolean("notifications", elem);
statusesCount = getChildInt("statuses_count", elem);
geoEnabled = getChildBoolean("geo_enabled", elem);
verified = getChildBoolean("verified", elem);
NodeList statuses = elem.getElementsByTagName("status");
if (statuses.getLength() != 0) {
Element status = (Element) statuses.item(0);
statusCreatedAt = getChildDate("created_at", status);
statusId = getChildString("id", status);
statusText = getChildText("text", status);
statusSource = getChildText("source", status);
statusTruncated = getChildBoolean("truncated", status);
statusInReplyToStatusId = getChildString("in_reply_to_status_id", status);
statusInReplyToUserId = getChildString("in_reply_to_user_id", status);
statusFavorited = getChildBoolean("favorited", status);
statusInReplyToScreenName = getChildText("in_reply_to_screen_name", status);
}
}
/**
* Returns the id of the user
*
* @return the id of the user
*/
public String getId() {
return id;
}
/**
* Returns the name of the user
*
* @return the name of the user
*/
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getBirthday() {
return birthday;
}
/**
* Returns the screen name of the user
*
* @return the screen name of the user
*/
public String getScreenName() {
return screenName;
}
/**
* Returns the location of the user
*
* @return the location of the user
*/
public String getLocation() {
return location;
}
/**
* Returns the description of the user
*
* @return the description of the user
*/
public String getDescription() {
return description;
}
/**
* Returns the profile image url of the user
*
* @return the profile image url of the user
*/
public URL getProfileImageURL() {
try {
return new URL(profileImageUrl);
} catch (MalformedURLException ex) {
return null;
}
}
/**
* Returns the url of the user
*
* @return the url of the user
*/
public URL getURL() {
try {
return new URL(url);
} catch (MalformedURLException ex) {
return null;
}
}
/**
* Test if the user status is protected
*
* @return true if the user status is protected
*/
public boolean isProtected() {
return isProtected;
}
/**
* Returns the number of followers
*
* @return the number of followers
* @since Weibo4J 1.0.4
*/
public int getFollowersCount() {
return followersCount;
}
//TODO: uncomment
// public DirectMessage sendDirectMessage(String text) throws WeiboException {
// return weibo.sendDirectMessage(this.getName(), text);
// }
public static List<User> constructUsers(Response res, Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<User>(0);
} else {
try {
ensureRootNodeNameIs("users", doc);
// NodeList list = doc.getDocumentElement().getElementsByTagName(
// "user");
// int size = list.getLength();
// List<User> users = new ArrayList<User>(size);
// for (int i = 0; i < size; i++) {
// users.add(new User(res, (Element) list.item(i), weibo));
// }
//去除掉嵌套的bug
NodeList list=doc.getDocumentElement().getChildNodes();
List<User> users = new ArrayList<User>(list.getLength());
Node node;
for(int i=0;i<list.getLength();i++){
node=list.item(i);
if(node.getNodeName().equals("user")){
users.add(new User(res, (Element) node, weibo));
}
}
return users;
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new ArrayList<User>(0);
} else {
throw te;
}
}
}
}
public static UserWapper constructWapperUsers(Response res, Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
} else {
try {
ensureRootNodeNameIs("users_list", doc);
Element root = doc.getDocumentElement();
NodeList user = root.getElementsByTagName("users");
int length = user.getLength();
if (length == 0) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
}
//
Element listsRoot = (Element) user.item(0);
NodeList list=listsRoot.getChildNodes();
List<User> users = new ArrayList<User>(list.getLength());
Node node;
for(int i=0;i<list.getLength();i++){
node=list.item(i);
if(node.getNodeName().equals("user")){
users.add(new User(res, (Element) node, weibo));
}
}
//
long previousCursor = getChildLong("previous_curosr", root);
long nextCursor = getChildLong("next_curosr", root);
if (nextCursor == -1) { // 兼容不同标签名称
nextCursor = getChildLong("nextCurosr", root);
}
return new UserWapper(users, previousCursor, nextCursor);
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new UserWapper(new ArrayList<User>(0), 0, 0);
} else {
throw te;
}
}
}
}
public static List<User> constructUsers(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(list.getJSONObject(i)));
}
return users;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
/**
*
* @param res
* @return
* @throws HttpException
*/
public static UserWapper constructWapperUsers(Response res) throws HttpException {
JSONObject jsonUsers = res.asJSONObject(); //asJSONArray();
try {
JSONArray user = jsonUsers.getJSONArray("users");
int size = user.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(user.getJSONObject(i)));
}
long previousCursor = jsonUsers.getLong("previous_curosr");
long nextCursor = jsonUsers.getLong("next_cursor");
if (nextCursor == -1) { // 兼容不同标签名称
nextCursor = jsonUsers.getLong("nextCursor");
}
return new UserWapper(users, previousCursor, nextCursor);
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
/**
* @param res
* @return
* @throws HttpException
*/
static List<User> constructResult(Response res) throws HttpException {
JSONArray list = res.asJSONArray();
try {
int size = list.length();
List<User> users = new ArrayList<User>(size);
for (int i = 0; i < size; i++) {
users.add(new User(list.getJSONObject(i)));
}
return users;
} catch (JSONException e) {
}
return null;
}
/**
* @return created_at or null if the user is protected
* @since Weibo4J 1.1.0
*/
public Date getStatusCreatedAt() {
return statusCreatedAt;
}
/**
*
* @return status id or -1 if the user is protected
*/
public String getStatusId() {
return statusId;
}
/**
*
* @return status text or null if the user is protected
*/
public String getStatusText() {
return statusText;
}
/**
*
* @return source or null if the user is protected
* @since 1.1.4
*/
public String getStatusSource() {
return statusSource;
}
/**
*
* @return truncated or false if the user is protected
* @since 1.1.4
*/
public boolean isStatusTruncated() {
return statusTruncated;
}
/**
*
* @return in_reply_to_status_id or -1 if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToStatusId() {
return statusInReplyToStatusId;
}
/**
*
* @return in_reply_to_user_id or -1 if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToUserId() {
return statusInReplyToUserId;
}
/**
*
* @return favorited or false if the user is protected
* @since 1.1.4
*/
public boolean isStatusFavorited() {
return statusFavorited;
}
/**
*
* @return in_reply_to_screen_name or null if the user is protected
* @since 1.1.4
*/
public String getStatusInReplyToScreenName() {
return "" != statusInReplyToUserId ? statusInReplyToScreenName : null;
}
public String getProfileBackgroundColor() {
return profileBackgroundColor;
}
public String getProfileTextColor() {
return profileTextColor;
}
public String getProfileLinkColor() {
return profileLinkColor;
}
public String getProfileSidebarFillColor() {
return profileSidebarFillColor;
}
public String getProfileSidebarBorderColor() {
return profileSidebarBorderColor;
}
public int getFriendsCount() {
return friendsCount;
}
public Date getCreatedAt() {
return createdAt;
}
public int getFavouritesCount() {
return favouritesCount;
}
public int getUtcOffset() {
return utcOffset;
}
public String getTimeZone() {
return timeZone;
}
public String getProfileBackgroundImageUrl() {
return profileBackgroundImageUrl;
}
public String getProfileBackgroundTile() {
return profileBackgroundTile;
}
/**
*
*/
public boolean isFollowing() {
return following;
}
/**
* @deprecated use isNotificationsEnabled() instead
*/
public boolean isNotifications() {
return notificationEnabled;
}
/**
*
* @since Weibo4J 2.0.1
*/
public boolean isNotificationEnabled() {
return notificationEnabled;
}
public int getStatusesCount() {
return statusesCount;
}
/**
* @return the user is enabling geo location
* @since Weibo4J 2.0.10
*/
public boolean isGeoEnabled() {
return geoEnabled;
}
/**
* @return returns true if the user is a verified celebrity
* @since Weibo4J 2.0.10
*/
public boolean isVerified() {
return verified;
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
return obj instanceof User && ((User) obj).id.equals(this.id);
}
@Override
public String toString() {
return "User{" +
"weibo=" + weibo +
", id=" + id +
", name='" + name + '\'' +
", screenName='" + screenName + '\'' +
", location='" + location + '\'' +
", description='" + description + '\'' +
", profileImageUrl='" + profileImageUrl + '\'' +
", url='" + url + '\'' +
", isProtected=" + isProtected +
", followersCount=" + followersCount +
", statusCreatedAt=" + statusCreatedAt +
", statusId=" + statusId +
", statusText='" + statusText + '\'' +
", statusSource='" + statusSource + '\'' +
", statusTruncated=" + statusTruncated +
", statusInReplyToStatusId=" + statusInReplyToStatusId +
", statusInReplyToUserId=" + statusInReplyToUserId +
", statusFavorited=" + statusFavorited +
", statusInReplyToScreenName='" + statusInReplyToScreenName + '\'' +
", profileBackgroundColor='" + profileBackgroundColor + '\'' +
", profileTextColor='" + profileTextColor + '\'' +
", profileLinkColor='" + profileLinkColor + '\'' +
", profileSidebarFillColor='" + profileSidebarFillColor + '\'' +
", profileSidebarBorderColor='" + profileSidebarBorderColor + '\'' +
", friendsCount=" + friendsCount +
", createdAt=" + createdAt +
", favouritesCount=" + favouritesCount +
", utcOffset=" + utcOffset +
// ", timeZone='" + timeZone + '\'' +
", profileBackgroundImageUrl='" + profileBackgroundImageUrl + '\'' +
", profileBackgroundTile='" + profileBackgroundTile + '\'' +
", following=" + following +
", notificationEnabled=" + notificationEnabled +
", statusesCount=" + statusesCount +
", geoEnabled=" + geoEnabled +
", verified=" + verified +
'}';
}
//TODO:增加从游标解析User的方法,用于和data里User转换一条数据
public static User parseUser(Cursor cursor){
if (null == cursor || 0 == cursor.getCount()||cursor.getCount()>1) {
Log.w("User.ParseUser", "Cann't parse Cursor, bacause cursor is null or empty.");
}
cursor.moveToFirst();
User u=new User();
u.id = cursor.getString(cursor.getColumnIndex(UserInfoTable._ID));
u.name = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_USER_NAME));
u.screenName = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_USER_SCREEN_NAME));
u.location = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_LOCALTION));
u.description = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_DESCRIPTION));
u.profileImageUrl = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_PROFILE_IMAGE_URL));
u.url = cursor.getString(cursor.getColumnIndex(UserInfoTable.FIELD_URL));
u.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_PROTECTED))) ? false : true;
u.followersCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FOLLOWERS_COUNT));
u.friendsCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FRIENDS_COUNT));
u.favouritesCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FAVORITES_COUNT));
u.statusesCount = cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_STATUSES_COUNT));
u.following = (0 == cursor.getInt(cursor.getColumnIndex(UserInfoTable.FIELD_FOLLOWING))) ? false : true;
try {
String createAtStr=cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT));
if(createAtStr!=null){
u.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(createAtStr);
}
} catch (ParseException e) {
Log.w("User", "Invalid created at data.");
}
return u;
}
public com.ch_linghu.fanfoudroid.data.User parseUser(){
com.ch_linghu.fanfoudroid.data.User user=new com.ch_linghu.fanfoudroid.data.User();
user.id=this.id;
user.name=this.name;
user.screenName=this.screenName;
user.location=this.location;
user.description=this.description;
user.profileImageUrl=this.profileImageUrl;
user.url=this.url;
user.isProtected=this.isProtected;
user.followersCount=this.followersCount;
user.friendsCount=this.friendsCount;
user.favoritesCount=this.favouritesCount;
user.statusesCount=this.statusesCount;
user.isFollowing=this.following;
user.createdAt = this.createdAt;
return user;
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import org.json.JSONException;
import org.json.JSONObject;
/**
* A data class representing Treand.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.2
*/
public class Trend implements java.io.Serializable{
private String name;
private String url = null;
private String query = null;
private static final long serialVersionUID = 1925956704460743946L;
public Trend(JSONObject json) throws JSONException {
this.name = json.getString("name");
if (!json.isNull("url")) {
this.url = json.getString("url");
}
if (!json.isNull("query")) {
this.query = json.getString("query");
}
}
public String getName() {
return name;
}
public String getUrl() {
return url;
}
public String getQuery() {
return query;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Trend)) return false;
Trend trend = (Trend) o;
if (!name.equals(trend.name)) return false;
if (query != null ? !query.equals(trend.query) : trend.query != null)
return false;
if (url != null ? !url.equals(trend.url) : trend.url != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (url != null ? url.hashCode() : 0);
result = 31 * result + (query != null ? query.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Trend{" +
"name='" + name + '\'' +
", url='" + url + '\'' +
", query='" + query + '\'' +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing one single retweet details.
*
* @author Yusuke Yamamoto - yusuke at mac.com
* @since Weibo4J 2.0.10
*/
public class RetweetDetails extends WeiboResponse implements
java.io.Serializable {
private long retweetId;
private Date retweetedAt;
private User retweetingUser;
static final long serialVersionUID = 1957982268696560598L;
public RetweetDetails(Response res, Weibo weibo) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
init(res, elem, weibo);
}
public RetweetDetails(JSONObject json) throws HttpException {
super();
init(json);
}
private void init(JSONObject json) throws HttpException{
try {
retweetId = json.getInt("retweetId");
retweetedAt = parseDate(json.getString("retweetedAt"), "EEE MMM dd HH:mm:ss z yyyy");
retweetingUser=new User(json.getJSONObject("retweetingUser"));
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
/*package*/public RetweetDetails(Response res, Element elem, Weibo weibo) throws
HttpException {
super(res);
init(res, elem, weibo);
}
private void init(Response res, Element elem, Weibo weibo) throws
HttpException {
ensureRootNodeNameIs("retweet_details", elem);
retweetId = getChildLong("retweet_id", elem);
retweetedAt = getChildDate("retweeted_at", elem);
retweetingUser = new User(res, (Element) elem.getElementsByTagName("retweeting_user").item(0)
, weibo);
}
public long getRetweetId() {
return retweetId;
}
public Date getRetweetedAt() {
return retweetedAt;
}
public User getRetweetingUser() {
return retweetingUser;
}
/*modify by sycheng add json*/
/*package*/
static List<RetweetDetails> createRetweetDetails(Response res) throws HttpException {
try {
JSONArray list = res.asJSONArray();
int size = list.length();
List<RetweetDetails> retweets = new ArrayList<RetweetDetails>(size);
for (int i = 0; i < size; i++) {
retweets.add(new RetweetDetails(list.getJSONObject(i)));
}
return retweets;
} catch (JSONException jsone) {
throw new HttpException(jsone);
} catch (HttpException te) {
throw te;
}
}
/*package*/
static List<RetweetDetails> createRetweetDetails(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<RetweetDetails>(0);
} else {
try {
ensureRootNodeNameIs("retweets", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"retweet_details");
int size = list.getLength();
List<RetweetDetails> statuses = new ArrayList<RetweetDetails>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
statuses.add(new RetweetDetails(res, status, weibo));
}
return statuses;
} catch (HttpException te) {
ensureRootNodeNameIs("nil-classes", doc);
return new ArrayList<RetweetDetails>(0);
}
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof RetweetDetails)) return false;
RetweetDetails that = (RetweetDetails) o;
return retweetId == that.retweetId;
}
@Override
public int hashCode() {
int result = (int) (retweetId ^ (retweetId >>> 32));
result = 31 * result + retweetedAt.hashCode();
result = 31 * result + retweetingUser.hashCode();
return result;
}
@Override
public String toString() {
return "RetweetDetails{" +
"retweetId=" + retweetId +
", retweetedAt=" + retweetedAt +
", retweetingUser=" + retweetingUser +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing sent/received direct message.
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class DirectMessage extends WeiboResponse implements java.io.Serializable {
private String id;
private String text;
private String sender_id;
private String recipient_id;
private Date created_at;
private String sender_screen_name;
private String recipient_screen_name;
private static final long serialVersionUID = -3253021825891789737L;
/*package*/DirectMessage(Response res, Weibo weibo) throws HttpException {
super(res);
init(res, res.asDocument().getDocumentElement(), weibo);
}
/*package*/DirectMessage(Response res, Element elem, Weibo weibo) throws HttpException {
super(res);
init(res, elem, weibo);
}
/*modify by sycheng add json call*/
/*package*/DirectMessage(JSONObject json) throws HttpException {
try {
id = json.getString("id");
text = json.getString("text");
sender_id = json.getString("sender_id");
recipient_id = json.getString("recipient_id");
created_at = parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy");
sender_screen_name = json.getString("sender_screen_name");
recipient_screen_name = json.getString("recipient_screen_name");
if(!json.isNull("sender"))
sender = new User(json.getJSONObject("sender"));
if(!json.isNull("recipient"))
recipient = new User(json.getJSONObject("recipient"));
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
private void init(Response res, Element elem, Weibo weibo) throws HttpException{
ensureRootNodeNameIs("direct_message", elem);
sender = new User(res, (Element) elem.getElementsByTagName("sender").item(0),
weibo);
recipient = new User(res, (Element) elem.getElementsByTagName("recipient").item(0),
weibo);
id = getChildString("id", elem);
text = getChildText("text", elem);
sender_id = getChildString("sender_id", elem);
recipient_id = getChildString("recipient_id", elem);
created_at = getChildDate("created_at", elem);
sender_screen_name = getChildText("sender_screen_name", elem);
recipient_screen_name = getChildText("recipient_screen_name", elem);
}
public String getId() {
return id;
}
public String getText() {
return text;
}
public String getSenderId() {
return sender_id;
}
public String getRecipientId() {
return recipient_id;
}
/**
* @return created_at
* @since Weibo4J 1.1.0
*/
public Date getCreatedAt() {
return created_at;
}
public String getSenderScreenName() {
return sender_screen_name;
}
public String getRecipientScreenName() {
return recipient_screen_name;
}
private User sender;
public User getSender() {
return sender;
}
private User recipient;
public User getRecipient() {
return recipient;
}
/*package*/
static List<DirectMessage> constructDirectMessages(Response res,
Weibo weibo) throws HttpException {
Document doc = res.asDocument();
if (isRootNodeNilClasses(doc)) {
return new ArrayList<DirectMessage>(0);
} else {
try {
ensureRootNodeNameIs("direct-messages", doc);
NodeList list = doc.getDocumentElement().getElementsByTagName(
"direct_message");
int size = list.getLength();
List<DirectMessage> messages = new ArrayList<DirectMessage>(size);
for (int i = 0; i < size; i++) {
Element status = (Element) list.item(i);
messages.add(new DirectMessage(res, status, weibo));
}
return messages;
} catch (HttpException te) {
if (isRootNodeNilClasses(doc)) {
return new ArrayList<DirectMessage>(0);
} else {
throw te;
}
}
}
}
/*package*/
static List<DirectMessage> constructDirectMessages(Response res
) throws HttpException {
JSONArray list= res.asJSONArray();
try {
int size = list.length();
List<DirectMessage> messages = new ArrayList<DirectMessage>(size);
for (int i = 0; i < size; i++) {
messages.add(new DirectMessage(list.getJSONObject(i)));
}
return messages;
} catch (JSONException jsone) {
throw new HttpException(jsone);
}
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (null == obj) {
return false;
}
if (this == obj) {
return true;
}
return obj instanceof DirectMessage && ((DirectMessage) obj).id.equals(this.id);
}
@Override
public String toString() {
return "DirectMessage{" +
"id=" + id +
", text='" + text + '\'' +
", sender_id=" + sender_id +
", recipient_id=" + recipient_id +
", created_at=" + created_at +
", sender_screen_name='" + sender_screen_name + '\'' +
", recipient_screen_name='" + recipient_screen_name + '\'' +
", sender=" + sender +
", recipient=" + recipient +
'}';
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import org.json.JSONException;
import org.json.JSONObject;
import com.ch_linghu.fanfoudroid.http.HttpException;
/**
* A data class representing Basic user information element
*/
public class Photo extends WeiboResponse implements java.io.Serializable {
private Weibo weibo;
private String thumbnail_pic;
private String bmiddle_pic;
private String original_pic;
private boolean verified;
private static final long serialVersionUID = -6345893237975349030L;
public Photo(JSONObject json) throws HttpException {
super();
init(json);
}
private void init(JSONObject json) throws HttpException {
try {
//System.out.println(json);
thumbnail_pic = json.getString("thumburl");
bmiddle_pic = json.getString("imageurl");
original_pic = json.getString("largeurl");
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
public String getThumbnail_pic() {
return thumbnail_pic;
}
public void setThumbnail_pic(String thumbnail_pic) {
this.thumbnail_pic = thumbnail_pic;
}
public String getBmiddle_pic() {
return bmiddle_pic;
}
public void setBmiddle_pic(String bmiddle_pic) {
this.bmiddle_pic = bmiddle_pic;
}
public String getOriginal_pic() {
return original_pic;
}
public void setOriginal_pic(String original_pic) {
this.original_pic = original_pic;
}
@Override
public String toString() {
return "Photo [thumbnail_pic=" + thumbnail_pic + ", bmiddle_pic="
+ bmiddle_pic + ", original_pic=" + original_pic + "]";
}
}
| Java |
/*
Copyright (c) 2007-2009, Yusuke Yamamoto
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Yusuke Yamamoto nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY Yusuke Yamamoto ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Yusuke Yamamoto BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.ch_linghu.fanfoudroid.fanfou;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Element;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
/**
* A data class representing Weibo rate limit status
* @author Yusuke Yamamoto - yusuke at mac.com
*/
public class RateLimitStatus extends WeiboResponse {
private int remainingHits;
private int hourlyLimit;
private int resetTimeInSeconds;
private Date resetTime;
private static final long serialVersionUID = 933996804168952707L;
/* package */ RateLimitStatus(Response res) throws HttpException {
super(res);
Element elem = res.asDocument().getDocumentElement();
remainingHits = getChildInt("remaining-hits", elem);
hourlyLimit = getChildInt("hourly-limit", elem);
resetTimeInSeconds = getChildInt("reset-time-in-seconds", elem);
resetTime = getChildDate("reset-time", elem, "EEE MMM d HH:mm:ss z yyyy");
}
/*modify by sycheng add json call*/
/* package */ RateLimitStatus(Response res,Weibo w) throws HttpException {
super(res);
JSONObject json= res.asJSONObject();
try {
remainingHits = json.getInt("remaining_hits");
hourlyLimit = json.getInt("hourly_limit");
resetTimeInSeconds = json.getInt("reset_time_in_seconds");
resetTime = parseDate(json.getString("reset_time"), "EEE MMM dd HH:mm:ss z yyyy");
} catch (JSONException jsone) {
throw new HttpException(jsone.getMessage() + ":" + json.toString(), jsone);
}
}
public int getRemainingHits() {
return remainingHits;
}
public int getHourlyLimit() {
return hourlyLimit;
}
public int getResetTimeInSeconds() {
return resetTimeInSeconds;
}
/**
*
* @deprecated use getResetTime() instead
*/
@Deprecated
public Date getDateTime() {
return resetTime;
}
/**
* @since Weibo4J 2.0.9
*/
public Date getResetTime() {
return resetTime;
}
@Override
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append("RateLimitStatus{remainingHits:");
sb.append(remainingHits);
sb.append(";hourlyLimit:");
sb.append(hourlyLimit);
sb.append(";resetTimeInSeconds:");
sb.append(resetTimeInSeconds);
sb.append(";resetTime:");
sb.append(resetTime);
sb.append("}");
return sb.toString();
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.os.Bundle;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
/**
* 随便看看
*
* @author jmx
*
*/
public class BrowseActivity extends TwitterCursorBaseActivity {
private static final String TAG = "BrowseActivity";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
mNavbar.setHeaderTitle(getActivityTitle());
getTweetList().removeFooterView(mListFooter); // 随便看看没有获取更多功能
return true;
} else {
return false;
}
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_browse);
}
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_BROWSE,
isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
return getApi().getPublicTimeline();
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
public String fetchMinId() {
// 随便看看没有获取更多的功能
return null;
}
@Override
public List<Status> getMoreMessageFromId(String minId) throws HttpException {
// 随便看看没有获取更多的功能
return null;
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_BROWSE;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
}
| Java |
/*
* Copyright (C) 2009 Google Inc.
*
* 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.ch_linghu.fanfoudroid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.ImageManager;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetEdit;
import com.ch_linghu.fanfoudroid.util.FileHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class WriteActivity extends BaseActivity {
// FIXME: for debug, delete me
private long startTime = -1;
private long endTime = -1;
public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW";
public static final String REPLY_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPLY";
public static final String REPOST_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPOST";
public static final String EXTRA_REPLY_TO_NAME = "reply_to_name";
public static final String EXTRA_REPLY_ID = "reply_id";
public static final String EXTRA_REPOST_ID = "repost_status_id";
private static final String TAG = "WriteActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
private static final int REQUEST_IMAGE_CAPTURE = 2;
private static final int REQUEST_PHOTO_LIBRARY = 3;
// View
private TweetEdit mTweetEdit;
private EditText mTweetEditText;
private TextView mProgressText;
private ImageButton mLocationButton;
private ImageButton chooseImagesButton;
private ImageButton mCameraButton;
private ProgressDialog dialog;
private NavBar mNavbar;
// Picture
private boolean withPic=false ;
private File mFile;
private ImageView mPreview;
private ImageView imageDelete;
private static final int MAX_BITMAP_SIZE = 400;
private File mImageFile;
private Uri mImageUri;
// Task
private GenericTask mSendTask;
private TaskListener mSendTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onSendBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
endTime = System.currentTimeMillis();
Log.d("LDS", "Sended a status in " + (endTime - startTime));
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onSendSuccess();
} else if (result == TaskResult.IO_ERROR) {
onSendFailure();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "SendTask";
}
};
private String _reply_id;
private String _repost_id;
private String _reply_to_name;
// sub menu
protected void openImageCaptureMenu() {
try {
// TODO: API < 1.6, images size too small
mImageFile = new File(FileHelper.getBasePath(), "upload.jpg");
mImageUri = Uri.fromFile(mImageFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
protected void openPhotoLibraryMenu() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_PHOTO_LIBRARY);
}
/**
* @deprecated 已废弃, 分解成两个按钮
*/
protected void createInsertPhotoDialog() {
final CharSequence[] items = {
getString(R.string.write_label_take_a_picture),
getString(R.string.write_label_choose_a_picture) };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.write_label_insert_picture));
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
openImageCaptureMenu();
break;
case 1:
openPhotoLibraryMenu();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaColumns.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void getPic(Intent intent, Uri uri) {
// layout for picture mode
changeStyleWithPic();
withPic = true;
mFile = null;
mImageUri = uri;
if (uri.getScheme().equals("content")) {
mFile = new File(getRealPathFromURI(mImageUri));
} else {
mFile = new File(mImageUri.getPath());
}
// TODO:想将图片放在EditText左边
mPreview.setImageBitmap(createThumbnailBitmap(mImageUri,
MAX_BITMAP_SIZE));
if (mFile == null) {
updateProgress("Could not locate picture file. Sorry!");
disableEntry();
}
}
private File bitmapToFile(Bitmap bitmap) {
try {
File file = new File(FileHelper.getBasePath(), "upload.jpg");
FileOutputStream out = new FileOutputStream(file);
if (bitmap.compress(Bitmap.CompressFormat.JPEG,
ImageManager.DEFAULT_COMPRESS_QUALITY, out)) {
out.flush();
out.close();
}
return file;
} catch (FileNotFoundException e) {
Log.e(TAG, "Sorry, the file can not be created. " + e.getMessage());
return null;
} catch (IOException e) {
Log.e(TAG,
"IOException occurred when save upload file. "
+ e.getMessage());
return null;
}
}
private void changeStyleWithPic() {
// 修改布局 ,以前 图片居中,现在在左边
// mPreview.setLayoutParams(
// new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,
// LayoutParams.FILL_PARENT)
// );
mPreview.setVisibility(View.VISIBLE);
imageDelete.setVisibility(View.VISIBLE);
mTweetEditText.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 2f));
}
/**
* 制作微缩图
*
* @param uri
* @param size
* @return
*/
private Bitmap createThumbnailBitmap(Uri uri, int size) {
InputStream input = null;
try {
input = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, options);
input.close();
// Compute the scale.
int scale = 1;
while ((options.outWidth / scale > size)
|| (options.outHeight / scale > size)) {
scale *= 2;
}
options.inJustDecodeBounds = false;
options.inSampleSize = scale;
input = getContentResolver().openInputStream(uri);
return BitmapFactory.decodeStream(input, null, options);
} catch (IOException e) {
Log.w(TAG, e);
return null;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
// init View
setContentView(R.layout.write);
mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this);
// Intent & Action & Extras
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
Bundle extras = intent.getExtras();
String text = null;
Uri uri = null;
if (extras != null) {
String subject = extras.getString(Intent.EXTRA_SUBJECT);
text = extras.getString(Intent.EXTRA_TEXT);
uri = (Uri) (extras.get(Intent.EXTRA_STREAM));
if (!TextUtils.isEmpty(subject)) {
text = subject + " " + text;
}
if ((type != null && type.startsWith("text")) && uri != null) {
text = text + " " + uri.toString();
uri = null;
}
}
_reply_id = null;
_repost_id = null;
_reply_to_name = null;
// View
mProgressText = (TextView) findViewById(R.id.progress_text);
mTweetEditText = (EditText) findViewById(R.id.tweet_edit);
// TODO: @某人-- 类似饭否自动补全
ImageButton mAddUserButton = (ImageButton) findViewById(R.id.add_user);
mAddUserButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int start = mTweetEditText.getSelectionStart();
int end = mTweetEditText.getSelectionEnd();
mTweetEditText.getText().replace(Math.min(start, end),
Math.max(start, end), "@");
}
});
// 插入图片
chooseImagesButton = (ImageButton) findViewById(R.id.choose_images_button);
chooseImagesButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "chooseImagesButton onClick");
openPhotoLibraryMenu();
}
});
// 打开相机
mCameraButton = (ImageButton) findViewById(R.id.camera_button);
mCameraButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG, "mCameraButton onClick");
openImageCaptureMenu();
}
});
// With picture
imageDelete = (ImageView) findViewById(R.id.image_delete);
imageDelete.setOnClickListener(deleteListener);
mPreview = (ImageView) findViewById(R.id.preview);
if (Intent.ACTION_SEND.equals(intent.getAction()) && uri != null) {
getPic(intent, uri);
}
// Update status
mTweetEdit = new TweetEdit(mTweetEditText,
(TextView) findViewById(R.id.chars_text));
if (TwitterApplication.mPref.getBoolean(Preferences.USE_ENTER_SEND, false)){
mTweetEdit.setOnKeyListener(tweetEnterHandler);
}
mTweetEdit.addTextChangedListener(new MyTextWatcher(
WriteActivity.this));
if (NEW_TWEET_ACTION.equals(action) || Intent.ACTION_SEND.equals(action)){
if (!TextUtils.isEmpty(text)){
//始终将光标置于最末尾,以方便回复消息时保持@用户在最前面
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(text);
Editable etext = inputField.getText();
int position = etext.length();
Selection.setSelection(etext, position);
}
}else if (REPLY_TWEET_ACTION.equals(action)) {
_reply_id = intent.getStringExtra(EXTRA_REPLY_ID);
_reply_to_name = intent.getStringExtra(EXTRA_REPLY_TO_NAME);
if (!TextUtils.isEmpty(text)){
String reply_to_name = "@"+_reply_to_name + " ";
String other_replies = "";
for (String mention : TextHelper.getMentions(text)){
//获取名字时不包括自己和回复对象
if (!mention.equals(TwitterApplication.getMyselfName()) &&
!mention.equals(_reply_to_name)){
other_replies += "@"+mention+" ";
}
}
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(reply_to_name + other_replies);
//将除了reply_to_name的其他名字默认选中
Editable etext = inputField.getText();
int start = reply_to_name.length();
int stop = etext.length();
Selection.setSelection(etext, start, stop);
}
}else if (REPOST_TWEET_ACTION.equals(action)) {
if (!TextUtils.isEmpty(text)){
// 如果是转发消息,则根据用户习惯,将光标放置在转发消息的头部或尾部
SharedPreferences prefereces = getPreferences();
boolean isAppendToTheBeginning = prefereces.getBoolean(
Preferences.RT_INSERT_APPEND, true);
EditText inputField = mTweetEdit.getEditText();
inputField.setTextKeepState(text);
Editable etext = inputField.getText();
int position = (isAppendToTheBeginning) ? 0 : etext.length();
Selection.setSelection(etext, position);
}
}
mLocationButton = (ImageButton) findViewById(R.id.location_button);
mLocationButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(WriteActivity.this, "LBS地理定位功能开发中, 敬请期待",
Toast.LENGTH_SHORT).show();
}
});
Button mTopSendButton = (Button) findViewById(R.id.top_send_btn);
mTopSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doSend();
}
});
return true;
} else {
return false;
}
}
private View.OnClickListener deleteListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getIntent();
intent.setAction(null);
withPic = false;
mPreview.setVisibility(View.INVISIBLE);
imageDelete.setVisibility(View.INVISIBLE);
}
};
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
// Doesn't really cancel execution (we let it continue running).
// See the SendTask code for more details.
mSendTask.cancel(true);
}
// Don't need to cancel FollowersTask (assuming it ends properly).
if (dialog != null) {
dialog.dismiss();
}
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
public static Intent createNewTweetIntent(String text) {
Intent intent = new Intent(NEW_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_TEXT, text);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
return intent;
}
public static Intent createNewReplyIntent(String tweetText, String screenName, String replyId) {
Intent intent = new Intent(WriteActivity.REPLY_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
intent.putExtra(Intent.EXTRA_TEXT, TextHelper.getSimpleTweetText(tweetText));
intent.putExtra(WriteActivity.EXTRA_REPLY_TO_NAME, screenName);
intent.putExtra(WriteActivity.EXTRA_REPLY_ID, replyId);
return intent;
}
public static Intent createNewRepostIntent(Context content,
String tweetText, String screenName, String repostId) {
SharedPreferences mPreferences = PreferenceManager
.getDefaultSharedPreferences(content);
String prefix = mPreferences.getString(Preferences.RT_PREFIX_KEY,
content.getString(R.string.pref_rt_prefix_default));
String retweet = " " + prefix + " @" + screenName + " "
+ TextHelper.getSimpleTweetText(tweetText);
Intent intent = new Intent(WriteActivity.REPOST_TWEET_ACTION);
intent.putExtra(Intent.EXTRA_SUBJECT, "");
intent.putExtra(Intent.EXTRA_TEXT, retweet);
intent.putExtra(WriteActivity.EXTRA_REPOST_ID, repostId);
return intent;
}
public static Intent createImageIntent(Activity activity, Uri uri) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
WriteActivity writeActivity = (WriteActivity) activity;
intent.putExtra(Intent.EXTRA_TEXT,
writeActivity.mTweetEdit.getText());
intent.putExtra(WriteActivity.EXTRA_REPLY_TO_NAME,
writeActivity._reply_to_name);
intent.putExtra(WriteActivity.EXTRA_REPLY_ID,
writeActivity._reply_id);
intent.putExtra(WriteActivity.EXTRA_REPOST_ID,
writeActivity._repost_id);
} catch (ClassCastException e) {
// do nothing
}
return intent;
}
private class MyTextWatcher implements TextWatcher {
private WriteActivity _activity;
public MyTextWatcher(WriteActivity activity) {
_activity = activity;
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
_activity._reply_id = null;
_activity._reply_to_name = null;
_activity._repost_id = null;
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
private View.OnKeyListener tweetEnterHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
WriteActivity t = (WriteActivity) (v.getContext());
doSend();
}
return true;
}
return false;
}
};
private void doSend() {
Log.d(TAG, "dosend "+withPic);
startTime = System.currentTimeMillis();
Log.d(TAG, String.format("doSend, reply_id=%s", _reply_id));
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
String status = mTweetEdit.getText().toString();
if (!TextUtils.isEmpty(status) || withPic) {
int mode = SendTask.TYPE_NORMAL;
if (withPic) {
mode = SendTask.TYPE_PHOTO;
} else if (null != _reply_id) {
mode = SendTask.TYPE_REPLY;
} else if (null != _repost_id) {
mode = SendTask.TYPE_REPOST;
}
mSendTask = new SendTask();
mSendTask.setListener(mSendTaskListener);
TaskParams params = new TaskParams();
params.put("mode", mode);
mSendTask.execute(params);
} else {
updateProgress(getString(R.string.page_text_is_null));
}
}
}
private class SendTask extends GenericTask {
public static final int TYPE_NORMAL = 0;
public static final int TYPE_REPLY = 1;
public static final int TYPE_REPOST = 2;
public static final int TYPE_PHOTO = 3;
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String status = mTweetEdit.getText().toString();
int mode = param.getInt("mode");
Log.d(TAG, "Send Status. Mode : " + mode);
// Send status in different way
switch (mode) {
case TYPE_REPLY:
// 增加容错性,即使reply_id为空依然允许发送
if (null == WriteActivity.this._reply_id) {
Log.e(TAG,
"Cann't send status in REPLY mode, reply_id is null");
}
getApi().updateStatus(status, WriteActivity.this._reply_id);
break;
case TYPE_REPOST:
// 增加容错性,即使repost_id为空依然允许发送
if (null == WriteActivity.this._repost_id) {
Log.e(TAG,
"Cann't send status in REPOST mode, repost_id is null");
}
getApi().repost(status, WriteActivity.this._repost_id);
break;
case TYPE_PHOTO:
if (null != mFile) {
// Compress image
try {
mFile = getImageManager().compressImage(mFile, 100);
//ImageManager.DEFAULT_COMPRESS_QUALITY);
} catch (IOException ioe) {
Log.e(TAG, "Cann't compress images.");
}
getApi().updateStatus(status, mFile);
} else {
Log.e(TAG,
"Cann't send status in PICTURE mode, photo is null");
}
break;
case TYPE_NORMAL:
default:
getApi().updateStatus(status); // just send a status
break;
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
if (e.getStatusCode() == HttpClient.NOT_AUTHORIZED) {
return TaskResult.AUTH_ERROR;
}
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
private ImageManager getImageManager() {
return TwitterApplication.mImageLoader.getImageManager();
}
}
private void onSendBegin() {
disableEntry();
dialog = ProgressDialog.show(WriteActivity.this, "",
getString(R.string.page_status_updating), true);
if (dialog != null) {
dialog.setCancelable(false);
}
updateProgress(getString(R.string.page_status_updating));
}
private void onSendSuccess() {
if (dialog != null) {
dialog.setMessage(getString(R.string.page_status_update_success));
dialog.dismiss();
}
_reply_id = null;
_repost_id = null;
updateProgress(getString(R.string.page_status_update_success));
enableEntry();
// FIXME: 不理解这段代码的含义,暂时注释掉
// try {
// Thread.currentThread();
// Thread.sleep(500);
// updateProgress("");
// } catch (InterruptedException e) {
// Log.d(TAG, e.getMessage());
// }
updateProgress("");
// 发送成功就自动关闭界面
finish();
// 关闭软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(),
0);
}
private void onSendFailure() {
dialog.setMessage(getString(R.string.page_status_unable_to_update));
dialog.dismiss();
updateProgress(getString(R.string.page_status_unable_to_update));
enableEntry();
}
private void enableEntry() {
mTweetEdit.setEnabled(true);
mLocationButton.setEnabled(true);
chooseImagesButton.setEnabled(true);
}
private void disableEntry() {
mTweetEdit.setEnabled(false);
mLocationButton.setEnabled(false);
chooseImagesButton.setEnabled(false);
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Intent intent = WriteActivity.createImageIntent(this, mImageUri);
//照相完后不重新起一个WriteActivity
getPic(intent, mImageUri);
/*intent.setClass(this, WriteActivity.class);
startActivity(intent);
// 打开发送图片界面后将自身关闭
finish();*/
} else if (requestCode == REQUEST_PHOTO_LIBRARY
&& resultCode == RESULT_OK) {
mImageUri = data.getData();
Intent intent = WriteActivity.createImageIntent(this, mImageUri);
//选图片后不重新起一个WriteActivity
getPic(intent, mImageUri);
/*intent.setClass(this, WriteActivity.class);
startActivity(intent);
// 打开发送图片界面后将自身关闭
finish();*/
}
}
} | Java |
package com.ch_linghu.fanfoudroid;
import com.ch_linghu.fanfoudroid.app.Preferences;
import android.app.Activity;
import android.content.ComponentName;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AboutActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
//set real version
ComponentName comp = new ComponentName(this, getClass());
PackageInfo pinfo = null;
try {
pinfo = getPackageManager().getPackageInfo(comp.getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView version = (TextView)findViewById(R.id.version);
version.setText(String.format("v %s", pinfo.versionName));
//bind button click event
Button okBtn = (Button)findViewById(R.id.ok_btn);
okBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.HashSet;
//import org.acra.ReportingInteractionMode;
//import org.acra.annotation.ReportsCrashes;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
//@ReportsCrashes(formKey="dHowMk5LMXQweVJkWGthb1E1T1NUUHc6MQ",
// mode = ReportingInteractionMode.NOTIFICATION,
// resNotifTickerText = R.string.crash_notif_ticker_text,
// resNotifTitle = R.string.crash_notif_title,
// resNotifText = R.string.crash_notif_text,
// resNotifIcon = android.R.drawable.stat_notify_error, // optional. default is a warning sign
// resDialogText = R.string.crash_dialog_text,
// resDialogIcon = android.R.drawable.ic_dialog_info, //optional. default is a warning sign
// resDialogTitle = R.string.crash_dialog_title, // optional. default is your application name
// resDialogCommentPrompt = R.string.crash_dialog_comment_prompt, // optional. when defined, adds a user text field input with this text resource as a label
// resDialogOkToast = R.string.crash_dialog_ok_toast // optional. displays a Toast message when the user accepts to send a report.
//)
public class TwitterApplication extends Application {
public static final String TAG = "TwitterApplication";
// public static ImageManager mImageManager;
public static LazyImageLoader mImageLoader;
public static TwitterDatabase mDb;
public static Weibo mApi; // new API
public static Context mContext;
public static SharedPreferences mPref;
public static int networkType = 0;
public final static boolean DEBUG = Configuration.getDebug();
// FIXME:获取登录用户id, 据肉眼观察,刚注册的用户系统分配id都是~开头的,因为不知道
// 用户何时去修改这个ID,目前只有把所有以~开头的ID在每次需要UserId时都去服务器
// 取一次数据,看看新的ID是否已经设定,判断依据是是否以~开头。这么判断会把有些用户
// 就是把自己ID设置的以~开头的造成,每次都需要去服务器取数。
// 只是简单处理了mPref没有CURRENT_USER_ID的情况,因为用户在登陆时,肯定会记一个CURRENT_USER_ID
// 到mPref.
private static void fetchMyselfInfo() {
User myself;
try {
myself = TwitterApplication.mApi.showUser(TwitterApplication.mApi.getUserId());
TwitterApplication.mPref.edit().putString(
Preferences.CURRENT_USER_ID, myself.getId()).commit();
TwitterApplication.mPref.edit().putString(
Preferences.CURRENT_USER_SCREEN_NAME, myself.getScreenName()).commit();
} catch (HttpException e) {
e.printStackTrace();
}
}
public static String getMyselfId() {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")) {
fetchMyselfInfo();
}
return mPref.getString(Preferences.CURRENT_USER_ID, "~");
}
public static String getMyselfName() {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| !mPref.contains(Preferences.CURRENT_USER_SCREEN_NAME)
|| mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")) {
fetchMyselfInfo();
}
return mPref.getString(Preferences.CURRENT_USER_SCREEN_NAME, "");
}
@Override
public void onCreate() {
// FIXME: StrictMode类在1.6以下的版本中没有,会导致类加载失败。
// 因此将这些代码设成关闭状态,仅在做性能调试时才打开。
// //NOTE: StrictMode模式需要2.3+ API支持。
// if (DEBUG){
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// }
super.onCreate();
mContext = this.getApplicationContext();
// mImageManager = new ImageManager(this);
mImageLoader = new LazyImageLoader();
mApi = new Weibo();
mDb = TwitterDatabase.getInstance(this);
mPref = PreferenceManager.getDefaultSharedPreferences(this);
String username = mPref.getString(Preferences.USERNAME_KEY, "");
String password = mPref.getString(Preferences.PASSWORD_KEY, "");
password = LoginActivity.decryptPassword(password);
if (Weibo.isValidCredentials(username, password)) {
mApi.setCredentials(username, password); // Setup API and HttpClient
}
// 为cmwap用户设置代理上网
String type = getNetworkType();
if (null != type && type.equalsIgnoreCase("cmwap")) {
Toast.makeText(this, "您当前正在使用cmwap网络上网.", Toast.LENGTH_SHORT);
mApi.getHttpClient().setProxy("10.0.0.172", 80, "http");
}
}
public String getNetworkType() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
//NetworkInfo mobNetInfo = connectivityManager
// .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (activeNetInfo != null){
return activeNetInfo.getExtraInfo(); // 接入点名称: 此名称可被用户任意更改 如: cmwap, cmnet,
// internet ...
}else{
return null;
}
}
@Override
public void onTerminate() {
//FIXME: 根据android文档,onTerminate不会在真实机器上被执行到
//因此这些清理动作需要再找合适的地方放置,以确保执行。
cleanupImages();
mDb.close();
Toast.makeText(this, "exit app", Toast.LENGTH_LONG);
super.onTerminate();
}
private void cleanupImages() {
HashSet<String> keepers = new HashSet<String>();
Cursor cursor = mDb.fetchAllTweets(StatusTable.TYPE_HOME);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
cursor = mDb.fetchAllDms(-1);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
mImageLoader.getImageManager().cleanup(keepers);
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.Html;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.TextView;
import android.widget.TextView.BufferType;
public class TextHelper {
private static final String TAG = "TextHelper";
public static String stringifyStream(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}
private static HashMap<String, String> _userLinkMapping = new HashMap<String, String>();
private static final Pattern NAME_MATCHER = Pattern.compile("@.+?\\s");
private static final Linkify.MatchFilter NAME_MATCHER_MATCH_FILTER = new Linkify.MatchFilter() {
@Override
public final boolean acceptMatch(final CharSequence s, final int start,
final int end) {
String name = s.subSequence(start + 1, end).toString().trim();
boolean result = _userLinkMapping.containsKey(name);
return result;
}
};
private static final Linkify.TransformFilter NAME_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
// TODO Auto-generated method stub
String name = url.subSequence(1, url.length()).toString().trim();
return _userLinkMapping.get(name);
}
};
private static final String TWITTA_USER_URL = "twitta://users/";
public static void linkifyUsers(TextView view) {
Linkify.addLinks(view, NAME_MATCHER, TWITTA_USER_URL,
NAME_MATCHER_MATCH_FILTER, NAME_MATCHER_TRANSFORM_FILTER);
}
private static final Pattern TAG_MATCHER = Pattern.compile("#\\w+#");
private static final Linkify.TransformFilter TAG_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public final String transformUrl(Matcher match, String url) {
String result = url.substring(1, url.length() - 1);
return "%23" + result + "%23";
}
};
private static final String TWITTA_SEARCH_URL = "twitta://search/";
public static void linkifyTags(TextView view) {
Linkify.addLinks(view, TAG_MATCHER, TWITTA_SEARCH_URL, null,
TAG_MATCHER_TRANSFORM_FILTER);
}
private static Pattern USER_LINK = Pattern
.compile("@<a href=\"http:\\/\\/fanfou\\.com\\/(.*?)\" class=\"former\">(.*?)<\\/a>");
private static String preprocessText(String text) {
// 处理HTML格式返回的用户链接
Matcher m = USER_LINK.matcher(text);
while (m.find()) {
_userLinkMapping.put(m.group(2), m.group(1));
Log.d(TAG,
String.format("Found mapping! %s=%s", m.group(2),
m.group(1)));
}
// 将User Link的连接去掉
StringBuffer sb = new StringBuffer();
m = USER_LINK.matcher(text);
while (m.find()) {
m.appendReplacement(sb, "@$2");
}
m.appendTail(sb);
return sb.toString();
}
public static String getSimpleTweetText(String text) {
return Html.fromHtml(text).toString();
}
public static void setSimpleTweetText(TextView textView, String text) {
String processedText = getSimpleTweetText(text);
textView.setText(processedText);
}
public static void setTweetText(TextView textView, String text) {
String processedText = preprocessText(text);
textView.setText(Html.fromHtml(processedText), BufferType.SPANNABLE);
Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
linkifyUsers(textView);
linkifyTags(textView);
_userLinkMapping.clear();
}
/**
* 从消息中获取全部提到的人,将它们按先后顺序放入一个列表
* @param msg 消息文本
* @return 消息中@的人的列表,按顺序存放
*/
public static List<String> getMentions(String msg){
ArrayList<String> mentionList = new ArrayList<String>();
final Pattern p = Pattern.compile("@(.*?)\\s");
final int MAX_NAME_LENGTH = 12; //简化判断,无论中英文最长12个字
Matcher m = p.matcher(msg);
while(m.find()){
String mention = m.group(1);
//过长的名字就忽略(不是合法名字) +1是为了补上“@”所占的长度
if (mention.length() <= MAX_NAME_LENGTH+1){
//避免重复名字
if (!mentionList.contains(mention)){
mentionList.add(m.group(1));
}
}
}
return mentionList;
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamUtils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
} | Java |
package com.ch_linghu.fanfoudroid.util;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.HashMap;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
/**
* Debug Timer
*
* Usage:
* --------------------------------
* DebugTimer.start();
* DebugTimer.mark("my_mark1"); // optional
* DebugTimer.stop();
*
* System.out.println(DebugTimer.__toString()); // get report
* --------------------------------
*
* @author LDS
*/
public class DebugTimer {
public static final int START = 0;
public static final int END = 1;
private static HashMap<String, Long> mTime = new HashMap<String, Long>();
private static long mStartTime = 0;
private static long mLastTime = 0;
/**
* Start a timer
*/
public static void start() {
reset();
mStartTime = touch();
}
/**
* Mark current time
*
* @param tag mark tag
* @return
*/
public static long mark(String tag) {
long time = System.currentTimeMillis() - mStartTime;
mTime.put(tag, time);
return time;
}
/**
* Mark current time
*
* @param tag mark tag
* @return
*/
public static long between(String tag, int startOrEnd) {
if(TwitterApplication.DEBUG){
Log.v("DEBUG", tag + " " + startOrEnd);
}
switch (startOrEnd) {
case START:
return mark(tag);
case END:
long time = System.currentTimeMillis() - mStartTime - get(tag, mStartTime);
mTime.put(tag, time);
//touch();
return time;
default:
return -1;
}
}
public static long betweenStart(String tag) {
return between(tag, START);
}
public static long betweenEnd(String tag) {
return between(tag, END);
}
/**
* Stop timer
*
* @return result
*/
public static String stop() {
mTime.put("_TOTLE", touch() - mStartTime);
return __toString();
}
public static String stop(String tag) {
mark(tag);
return stop();
}
/**
* Get a mark time
*
* @param tag mark tag
* @return time(milliseconds) or NULL
*/
public static long get(String tag) {
return get(tag, 0);
}
public static long get(String tag, long defaultValue) {
if (mTime.containsKey(tag)) {
return mTime.get(tag);
}
return defaultValue;
}
/**
* Reset timer
*/
public static void reset() {
mTime = new HashMap<String, Long>();
mStartTime = 0;
mLastTime = 0;
}
/**
* static toString()
*
* @return
*/
public static String __toString() {
return "Debuger [time =" + mTime.toString() + "]";
}
private static long touch() {
return mLastTime = System.currentTimeMillis();
}
public static DebugProfile[] getProfile() {
DebugProfile[] profile = new DebugProfile[mTime.size()];
long totel = mTime.get("_TOTLE");
int i = 0;
for (String key : mTime.keySet()) {
long time = mTime.get(key);
profile[i] = new DebugProfile(key, time, time/(totel*1.0) );
i++;
}
try {
Arrays.sort(profile);
} catch (NullPointerException e) {
// in case item is null, do nothing
}
return profile;
}
public static String getProfileAsString() {
StringBuilder sb = new StringBuilder();
for (DebugProfile p : getProfile()) {
sb.append("TAG: ");
sb.append(p.tag);
sb.append("\t INC: ");
sb.append(p.inc);
sb.append("\t INCP: ");
sb.append(p.incPercent);
sb.append("\n");
}
return sb.toString();
}
@Override
public String toString() {
return __toString();
}
}
class DebugProfile implements Comparable<DebugProfile> {
private static NumberFormat percent = NumberFormat.getPercentInstance();
public String tag;
public long inc;
public String incPercent;
public DebugProfile(String tag, long inc, double incPercent) {
this.tag = tag;
this.inc = inc;
percent = new DecimalFormat("0.00#%");
this.incPercent = percent.format(incPercent);
}
@Override
public int compareTo(DebugProfile o) {
// TODO Auto-generated method stub
return (int) (o.inc - this.inc);
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.File;
import java.io.IOException;
import android.os.Environment;
/**
* 对SD卡文件的管理
* @author ch.linghu
*
*/
public class FileHelper {
private static final String TAG = "FileHelper";
private static final String BASE_PATH="fanfoudroid";
public static File getBasePath() throws IOException{
File basePath = new File(Environment.getExternalStorageDirectory(),
BASE_PATH);
if (!basePath.exists()){
if (!basePath.mkdirs()){
throw new IOException(String.format("%s cannot be created!", basePath.toString()));
}
}
if (!basePath.isDirectory()){
throw new IOException(String.format("%s is not a directory!", basePath.toString()));
}
return basePath;
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.util.Log;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
public class DateTimeHelper {
private static final String TAG = "DateTimeHelper";
// Wed Dec 15 02:53:36 +0000 2010
public static final DateFormat TWITTER_DATE_FORMATTER = new SimpleDateFormat(
"E MMM d HH:mm:ss Z yyyy", Locale.US);
public static final DateFormat TWITTER_SEARCH_API_DATE_FORMATTER = new SimpleDateFormat(
"E, d MMM yyyy HH:mm:ss Z", Locale.US); // TODO: Z -> z ?
public static final Date parseDateTime(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString));
return TWITTER_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
// Handle "yyyy-MM-dd'T'HH:mm:ss.SSS" from sqlite
public static final Date parseDateTimeFromSqlite(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString));
return TwitterDatabase.DB_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
public static final Date parseSearchApiDateTime(String dateString) {
try {
return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter search date string: "
+ dateString);
return null;
}
}
public static final DateFormat AGO_FULL_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm");
public static String getRelativeDate(Date date) {
Date now = new Date();
String prefix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_prefix);
String sec = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_sec);
String min = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_min);
String hour = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_hour);
String day = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_day);
String suffix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_suffix);
// Seconds.
long diff = (now.getTime() - date.getTime()) / 1000;
if (diff < 0) {
diff = 0;
}
if (diff < 60) {
return diff + sec + suffix;
}
// Minutes.
diff /= 60;
if (diff < 60) {
return prefix + diff + min + suffix;
}
// Hours.
diff /= 60;
if (diff < 24) {
return prefix + diff + hour + suffix;
}
return AGO_FULL_DATE_FORMATTER.format(date);
}
public static long getNowTime() {
return Calendar.getInstance().getTime().getTime();
}
}
| Java |
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.
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.commonsware.cwac.sacklist;
import java.util.ArrayList;
import java.util.List;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
/**
* Adapter that simply returns row views from a list.
*
* If you supply a size, you must implement newView(), to
* create a required view. The adapter will then cache these
* views.
*
* If you supply a list of views in the constructor, that
* list will be used directly. If any elements in the list
* are null, then newView() will be called just for those
* slots.
*
* Subclasses may also wish to override areAllItemsEnabled()
* (default: false) and isEnabled() (default: false), if some
* of their rows should be selectable.
*
* It is assumed each view is unique, and therefore will not
* get recycled.
*
* Note that this adapter is not designed for long lists. It
* is more for screens that should behave like a list. This
* is particularly useful if you combine this with other
* adapters (e.g., SectionedAdapter) that might have an
* arbitrary number of rows, so it all appears seamless.
*/
public class SackOfViewsAdapter extends BaseAdapter {
private List<View> views=null;
/**
* Constructor creating an empty list of views, but with
* a specified count. Subclasses must override newView().
*/
public SackOfViewsAdapter(int count) {
super();
views=new ArrayList<View>(count);
for (int i=0;i<count;i++) {
views.add(null);
}
}
/**
* Constructor wrapping a supplied list of views.
* Subclasses must override newView() if any of the elements
* in the list are null.
*/
public SackOfViewsAdapter(List<View> views) {
super();
this.views=views;
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
@Override
public Object getItem(int position) {
return(views.get(position));
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
@Override
public int getCount() {
return(views.size());
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
@Override
public int getViewTypeCount() {
return(getCount());
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
@Override
public int getItemViewType(int position) {
return(position);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
@Override
public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
@Override
public boolean isEnabled(int position) {
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
View result=views.get(position);
if (result==null) {
result=newView(position, parent);
views.set(position, result);
}
return(result);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
return(position);
}
/**
* Create a new View to go into the list at the specified
* position.
* @param position Position of the item whose data we want
* @param parent ViewGroup containing the returned View
*/
protected View newView(int position, ViewGroup parent) {
throw new RuntimeException("You must override newView()!");
}
} | Java |
/***
Copyright (c) 2008-2009 CommonsWare, LLC
Portions (c) 2009 Google, Inc.
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.commonsware.cwac.merge;
import java.util.ArrayList;
import java.util.List;
import android.database.DataSetObserver;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.SectionIndexer;
import com.commonsware.cwac.sacklist.SackOfViewsAdapter;
/**
* Adapter that merges multiple child adapters and views
* into a single contiguous whole.
*
* Adapters used as pieces within MergeAdapter must
* have view type IDs monotonically increasing from 0. Ideally,
* adapters also have distinct ranges for their row ids, as
* returned by getItemId().
*
*/
public class MergeAdapter extends BaseAdapter implements SectionIndexer {
private ArrayList<ListAdapter> pieces=new ArrayList<ListAdapter>();
/**
* Stock constructor, simply chaining to the superclass.
*/
public MergeAdapter() {
super();
}
/**
* Adds a new adapter to the roster of things to appear
* in the aggregate list.
* @param adapter Source for row views for this section
*/
public void addAdapter(ListAdapter adapter) {
pieces.add(adapter);
adapter.registerDataSetObserver(new CascadeDataSetObserver());
}
/**
* Adds a new View to the roster of things to appear
* in the aggregate list.
* @param view Single view to add
*/
public void addView(View view) {
addView(view, false);
}
/**
* Adds a new View to the roster of things to appear
* in the aggregate list.
* @param view Single view to add
* @param enabled false if views are disabled, true if enabled
*/
public void addView(View view, boolean enabled) {
ArrayList<View> list=new ArrayList<View>(1);
list.add(view);
addViews(list, enabled);
}
/**
* Adds a list of views to the roster of things to appear
* in the aggregate list.
* @param views List of views to add
*/
public void addViews(List<View> views) {
addViews(views, false);
}
/**
* Adds a list of views to the roster of things to appear
* in the aggregate list.
* @param views List of views to add
* @param enabled false if views are disabled, true if enabled
*/
public void addViews(List<View> views, boolean enabled) {
if (enabled) {
addAdapter(new EnabledSackAdapter(views));
}
else {
addAdapter(new SackOfViewsAdapter(views));
}
}
/**
* Get the data item associated with the specified
* position in the data set.
* @param position Position of the item whose data we want
*/
@Override
public Object getItem(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getItem(position));
}
position-=size;
}
return(null);
}
/**
* Get the adapter associated with the specified
* position in the data set.
* @param position Position of the item whose adapter we want
*/
public ListAdapter getAdapter(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece);
}
position-=size;
}
return(null);
}
/**
* How many items are in the data set represented by this
* Adapter.
*/
@Override
public int getCount() {
int total=0;
for (ListAdapter piece : pieces) {
total+=piece.getCount();
}
return(total);
}
/**
* Returns the number of types of Views that will be
* created by getView().
*/
@Override
public int getViewTypeCount() {
int total=0;
for (ListAdapter piece : pieces) {
total+=piece.getViewTypeCount();
}
return(Math.max(total, 1)); // needed for setListAdapter() before content add'
}
/**
* Get the type of View that will be created by getView()
* for the specified item.
* @param position Position of the item whose data we want
*/
@Override
public int getItemViewType(int position) {
int typeOffset=0;
int result=-1;
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
result=typeOffset+piece.getItemViewType(position);
break;
}
position-=size;
typeOffset+=piece.getViewTypeCount();
}
return(result);
}
/**
* Are all items in this ListAdapter enabled? If yes it
* means all items are selectable and clickable.
*/
@Override
public boolean areAllItemsEnabled() {
return(false);
}
/**
* Returns true if the item at the specified position is
* not a separator.
* @param position Position of the item whose data we want
*/
@Override
public boolean isEnabled(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.isEnabled(position));
}
position-=size;
}
return(false);
}
/**
* Get a View that displays the data at the specified
* position in the data set.
* @param position Position of the item whose data we want
* @param convertView View to recycle, if not null
* @param parent ViewGroup containing the returned View
*/
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getView(position, convertView, parent));
}
position-=size;
}
return(null);
}
/**
* Get the row id associated with the specified position
* in the list.
* @param position Position of the item whose data we want
*/
@Override
public long getItemId(int position) {
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
return(piece.getItemId(position));
}
position-=size;
}
return(-1);
}
@Override
public int getPositionForSection(int section) {
int position=0;
for (ListAdapter piece : pieces) {
if (piece instanceof SectionIndexer) {
Object[] sections=((SectionIndexer)piece).getSections();
int numSections=0;
if (sections!=null) {
numSections=sections.length;
}
if (section<numSections) {
return(position+((SectionIndexer)piece).getPositionForSection(section));
}
else if (sections!=null) {
section-=numSections;
}
}
position+=piece.getCount();
}
return(0);
}
@Override
public int getSectionForPosition(int position) {
int section=0;
for (ListAdapter piece : pieces) {
int size=piece.getCount();
if (position<size) {
if (piece instanceof SectionIndexer) {
return(section+((SectionIndexer)piece).getSectionForPosition(position));
}
return(0);
}
else {
if (piece instanceof SectionIndexer) {
Object[] sections=((SectionIndexer)piece).getSections();
if (sections!=null) {
section+=sections.length;
}
}
}
position-=size;
}
return(0);
}
@Override
public Object[] getSections() {
ArrayList<Object> sections=new ArrayList<Object>();
for (ListAdapter piece : pieces) {
if (piece instanceof SectionIndexer) {
Object[] curSections=((SectionIndexer)piece).getSections();
if (curSections!=null) {
for (Object section : curSections) {
sections.add(section);
}
}
}
}
if (sections.size()==0) {
return(null);
}
return(sections.toArray(new Object[0]));
}
private static class EnabledSackAdapter extends SackOfViewsAdapter {
public EnabledSackAdapter(List<View> views) {
super(views);
}
@Override
public boolean areAllItemsEnabled() {
return(true);
}
@Override
public boolean isEnabled(int position) {
return(true);
}
}
private class CascadeDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
}
} | Java |
package com.hlidskialf.android.hardware;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class ShakeListener implements SensorEventListener {
private static final int FORCE_THRESHOLD = 350;
private static final int TIME_THRESHOLD = 100;
private static final int SHAKE_TIMEOUT = 500;
private static final int SHAKE_DURATION = 1000;
private static final int SHAKE_COUNT = 3;
private SensorManager mSensorMgr;
private Sensor mSensor;
private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f;
private long mLastTime;
private OnShakeListener mShakeListener;
private Context mContext;
private int mShakeCount = 0;
private long mLastShake;
private long mLastForce;
public interface OnShakeListener {
public void onShake();
}
public ShakeListener(Context context) {
mContext = context;
resume();
}
public void setOnShakeListener(OnShakeListener listener) {
mShakeListener = listener;
}
public void resume() {
mSensorMgr = (SensorManager) mContext
.getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorMgr
.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER);
if (mSensorMgr == null) {
throw new UnsupportedOperationException("Sensors not supported");
}
boolean supported = mSensorMgr.registerListener(this,
mSensor,
SensorManager.SENSOR_DELAY_GAME);
if (!supported) {
mSensorMgr.unregisterListener(this, mSensor);
throw new UnsupportedOperationException(
"Accelerometer not supported");
}
}
public void pause() {
if (mSensorMgr != null) {
mSensorMgr.unregisterListener(this,
mSensor);
mSensorMgr = null;
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
if (sensor.getType() != SensorManager.SENSOR_ACCELEROMETER)
return;
long now = System.currentTimeMillis();
if ((now - mLastForce) > SHAKE_TIMEOUT) {
mShakeCount = 0;
}
if ((now - mLastTime) > TIME_THRESHOLD) {
long diff = now - mLastTime;
float speed = Math.abs(values[SensorManager.DATA_X]
+ values[SensorManager.DATA_Y]
+ values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ)
/ diff * 10000;
if (speed > FORCE_THRESHOLD) {
if ((++mShakeCount >= SHAKE_COUNT)
&& (now - mLastShake > SHAKE_DURATION)) {
mLastShake = now;
mShakeCount = 0;
if (mShakeListener != null) {
mShakeListener.onShake();
}
}
mLastForce = now;
}
mLastTime = now;
mLastX = values[SensorManager.DATA_X];
mLastY = values[SensorManager.DATA_Y];
mLastZ = values[SensorManager.DATA_Z];
}
}
}
| Java |
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.DigitalIOButton;
/**
* This class is the glue that binds the controls on the physical operator
* interface to the commands and command groups that allow control of the robot.
*/
public class OI {
//// CREATING BUTTONS
// One type of button is a joystick button which is any button on a joystick.
// You create one by telling it which joystick it's on and which button
// number it is.
// Joystick stick = new Joystick(port);
// Button button = new JoystickButton(stick, buttonNumber);
static Joystick xbox;
private static final int XBOX_PORT = 1;
public OI(){
xbox = new Joystick(XBOX_PORT);
}
// Another type of button you can create is a DigitalIOButton, which is
// a button or switch hooked up to the cypress module. These are useful if
// you want to build a customized operator interface.
// Button button = new DigitalIOButton(1);
// There are a few additional built in buttons you can use. Additionally,
// by subclassing Button you can create custom triggers and bind those to
// commands the same as any other Button.
public static Joystick getStick(){
return xbox;
}
//// TRIGGERING COMMANDS WITH BUTTONS
// Once you have a button, it's trivial to bind it to a button in one of
// three ways:
// Start the command when the button is pressed and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenPressed(new ExampleCommand());
// Run the command while the button is being held down and interrupt it once
// the button is released.
// button.whileHeld(new ExampleCommand());
// Start the command when the button is released and let it run the command
// until it is finished as determined by it's isFinished method.
// button.whenReleased(new ExampleCommand());
}
| Java |
package edu.wpi.first.wpilibj.templates;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
public static final int frontLeftJaguarID = 1,
rearLeftJaguarID = 2,
frontRightJaguarID = 4,
rearRightJaguarID = 3,
GyroPin = 1;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.templates.OI;
import edu.wpi.first.wpilibj.templates.commands.CommandBase;
/**
*
* @author Roksbot
*/
public class DriveWithJoysticks extends CommandBase {
public DriveWithJoysticks() {
requires(cb_DRIVE);
requires(cb_GYRO);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
cb_DRIVE.driveWithJoysticks(OI.getStick(),cb_GYRO.GetGyro());
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
/**
*
* @author Roksbot
*/
public class DriveForward extends CommandBase {
private static double TIME,
SPEED;
public DriveForward(double time, double speed) {
requires(cb_DRIVE);
requires(cb_GYRO);
TIME=time;
SPEED=speed;
setTimeout(TIME);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
cb_DRIVE.driveFoward(SPEED, cb_GYRO);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return isTimedOut();
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
/**
*
* @author Roksbot
*/
public class TurnLeft extends CommandBase {
private static double SPEED,
TARGET_ANGLE;
private static boolean IS_FINISHED;
public TurnLeft(double speed, double angle) {
requires(cb_DRIVE);
requires(cb_GYRO);
SPEED = speed;
TARGET_ANGLE = angle;
}
// Called just before this Command runs the first time
protected void initialize() {
IS_FINISHED = cb_DRIVE.turnLeft(SPEED, TARGET_ANGLE, cb_GYRO);
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return IS_FINISHED;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| Java |
package edu.wpi.first.wpilibj.templates.commands;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.templates.OI;
import edu.wpi.first.wpilibj.templates.subsystems.DriveTrain;
import edu.wpi.first.wpilibj.templates.subsystems.Gyroscope;
/**
* The base for all commands. All atomic commands should subclass CommandBase.
* CommandBase stores creates and stores each control system. To access a
* subsystem elsewhere in your code in your code use CommandBase.exampleSubsystem
* @author Author
*/
public abstract class CommandBase extends Command {
public static OI oi;
public static DriveTrain cb_DRIVE;
public static Gyroscope cb_GYRO;
public static void init() {
// This MUST be here. If the OI creates Commands (which it very likely
// will), constructing it during the construction of CommandBase (from
// which commands extend), subsystems are not guaranteed to be
// yet. Thus, their requires() statements may grab null pointers. Bad
// news. Don't move it.
oi = new OI();
// Show what command your subsystem is running on the SmartDashboard
}
public CommandBase(String name) {
super(name);
}
public CommandBase() {
super();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
/**
*
* @author Roksbot
*/
public class GyroReturnAngle extends CommandBase {
public GyroReturnAngle() {
requires(cb_GYRO);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
cb_GYRO.getAngle();
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
/**
*
* @author Roksbot
*/
public class StrafeRight extends CommandBase {
private static double SPEED;
public StrafeRight(double speed, double time ) {
requires(cb_DRIVE);
requires(cb_GYRO);
SPEED = speed;
setTimeout(time);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
cb_DRIVE.strafeRight(SPEED, cb_GYRO);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return isTimedOut();
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
/**
*
* @author Roksbot
*/
public class StrafeLeft extends CommandBase {
private static double SPEED;
public StrafeLeft(double speed, double time) {
requires(cb_DRIVE);
requires(cb_GYRO);
SPEED = speed;
setTimeout(time);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
cb_DRIVE.strafeLeft(SPEED, cb_GYRO);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return isTimedOut();
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
/**
*
* @author Roksbot
*/
public class DriveBackward extends CommandBase {
private static double SPEED;
public DriveBackward(double time, double speed) {
requires(cb_DRIVE);
requires(cb_GYRO);
SPEED = speed;
setTimeout(time);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
cb_DRIVE.driveBackward(SPEED, cb_GYRO);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return isTimedOut();
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.commands;
/**
*
* @author Roksbot
*/
public class TurnRight extends CommandBase {
private static double SPEED,
TARGET_ANGLE;
private static boolean IS_FINISHED;
public TurnRight(double speed, double angle) {
requires(cb_DRIVE);
requires(cb_GYRO);
SPEED = speed;
TARGET_ANGLE = angle;
}
// Called just before this Command runs the first time
protected void initialize() {
IS_FINISHED = cb_DRIVE.turnRight(SPEED, TARGET_ANGLE, cb_GYRO);
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return IS_FINISHED;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.subsystems;
import edu.wpi.first.wpilibj.Gyro;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.templates.commands.GyroReturnAngle;
/**
*
* @author Roksbot
*/
public class Gyroscope extends Subsystem {
private final static int GYRO_PIN = RobotMap.GyroPin;
Gyro gyro;
public Gyroscope(){
gyro = new Gyro(GYRO_PIN);
}
public void initDefaultCommand() {
setDefaultCommand(new GyroReturnAngle());
}
public Gyro GetGyro(){
return gyro;
}
public double getAngle(){
return gyro.getAngle();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.subsystems;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.templates.commands.CompressorRunAuto;
/**
*
* @author Roksbot
*/
public class CompressorSub extends Subsystem {
Compressor compressor;
public void initDefaultCommand() {
setDefaultCommand((new CompressorRunAuto()));
}
public CompressorSub(){
compressor = new Compressor(RobotMap.sensorPort, RobotMap.relayPort);
}
public void compressorRun(){
compressor.enabled();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates.subsystems;
import edu.wpi.first.wpilibj.CANJaguar;
import edu.wpi.first.wpilibj.Gyro;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.templates.RobotMap;
import edu.wpi.first.wpilibj.templates.commands.DriveWithJoysticks;
/**
*
* @author Roksbot
*/
public class DriveTrain extends Subsystem {
RobotDrive drive;
CANJaguar frontLeftJaguar,
rearLeftJaguar,
frontRightJaguar,
rearRightJaguar ;
public void initDefaultCommand() {
setDefaultCommand(new DriveWithJoysticks());
}
public DriveTrain(){
try{
frontLeftJaguar = new CANJaguar(RobotMap.frontLeftJaguarID);
rearLeftJaguar = new CANJaguar(RobotMap.rearLeftJaguarID);
frontRightJaguar = new CANJaguar(RobotMap.frontRightJaguarID);
rearRightJaguar = new CANJaguar(RobotMap.rearRightJaguarID);
drive = new RobotDrive(frontLeftJaguar,rearLeftJaguar,frontRightJaguar,rearRightJaguar);
drive.setSafetyEnabled(false);
} catch (Exception e){
System.out.println(e);
}
}
public void driveFoward(double speed, Gyroscope gyro){
drive.mecanumDrive_Cartesian(0.0, speed, 0, gyro.getAngle());
}
public void driveBackward(double speed, Gyroscope gyro){
drive.mecanumDrive_Cartesian(0.0, -speed, 0.0, gyro.getAngle());
}
public void strafeLeft(double speed, Gyroscope gyro){
drive.mecanumDrive_Cartesian(-speed, 0.0, 0.0, gyro.getAngle());
}
public void strafeRight(double speed, Gyroscope gyro){
drive.mecanumDrive_Cartesian(speed, 0.0, 0.0, gyro.getAngle());
}
public boolean turnRight(double speed, double angle, Gyroscope gyro){
double targetAngle = angle;
double startingAngle = gyro.getAngle();
for(double gyroangle=startingAngle;gyroangle<startingAngle+targetAngle;gyroangle=gyro.getAngle()){
drive.mecanumDrive_Cartesian(0.0, 0.0, speed, gyro.getAngle());
}
return true;
}
public boolean turnLeft(double speed, double angle, Gyroscope gyro){
double targetAngle = angle;
double startingAngle = gyro.getAngle();
for(double gyroangle=startingAngle;gyroangle<startingAngle-targetAngle;gyroangle=gyro.getAngle()){
drive.mecanumDrive_Cartesian(0.0, 0.0, -speed, gyro.getAngle());
}
return true;
}
public void driveWithJoysticks(Joystick stick, Gyro gyro){
drive.mecanumDrive_Cartesian(stick.getX(), stick.getY(), stick.getZ(), gyro.getAngle());
}
}
| Java |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.templates.commands.CommandBase;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends IterativeRobot {
Command autonomousCommand;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
// instantiate the command used for the autonomous period
// Initialize all subsystems
CommandBase.init();
}
public void autonomousInit() {
// schedule the autonomous command (example)
autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
}
| Java |
package org.bulatnig.smpp.net;
import org.bulatnig.smpp.pdu.Pdu;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.pdu.PduParser;
import java.io.IOException;
/**
* Connection with SMPP entity. Converts bytes to PDU and PDU to bytes. The same
* connection may be reused many times.
*
* @author Bulat Nigmatullin
*/
public interface Connection {
/**
* Incoming PDU packets parser.
*
* @param parser parser instance
*/
void setParser(PduParser parser);
/**
* Open connection.
*
* @throws IOException connection failed
*/
void open() throws IOException;
/**
* Read PDU from input. Blocks until PDU received or exception throwed.
*
* @return PDU
* @throws PduException parsing error
* @throws IOException I/O error
*/
Pdu read() throws PduException, IOException;
/**
* Write PDU to output.
*
* @param pdu PDU for sending
* @throws org.bulatnig.smpp.pdu.PduException
* PDU to bytes converting error
* @throws IOException I/O error
*/
void write(Pdu pdu) throws PduException, IOException;
/**
* Close connection.
*/
void close();
}
| Java |
package org.bulatnig.smpp.net.impl;
import org.bulatnig.smpp.net.Connection;
import org.bulatnig.smpp.pdu.Pdu;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.pdu.PduParser;
import org.bulatnig.smpp.pdu.impl.DefaultPduParser;
import org.bulatnig.smpp.util.ByteBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketAddress;
/**
* TCP/IP connection. Additionally logs on debug level all read and sent PDU's.
* <p/>
* Not thread safe. Weak against buffer overflow problem.
*
* @author Bulat Nigmatullin
*/
public class TcpConnection implements Connection {
private static final Logger logger = LoggerFactory.getLogger(TcpConnection.class);
private final SocketAddress socketAddress;
private final byte[] bytes = new byte[250];
private PduParser parser = new DefaultPduParser();
private Socket socket;
private InputStream in;
private OutputStream out;
private ByteBuffer bb;
public TcpConnection(SocketAddress socketAddress) {
this.socketAddress = socketAddress;
}
@Override
public void setParser(PduParser parser) {
this.parser = parser;
}
@Override
public void open() throws IOException {
socket = new Socket();
socket.connect(socketAddress);
socket.setSoTimeout(0); // block read forever
in = socket.getInputStream();
out = socket.getOutputStream();
bb = new ByteBuffer();
}
@Override
public Pdu read() throws PduException, IOException {
synchronized (in) {
Pdu pdu = tryToReadBuffer(); // there may be two PDU's read previous time, but only one parsed
while (pdu == null) {
int read = in.read(bytes);
if (read < 0)
throw new IOException("Connection closed by SMSC");
bb.appendBytes(bytes, read);
pdu = tryToReadBuffer();
}
logger.debug("<<< {}", pdu.buffer().hexDump());
return pdu;
}
}
@Override
public void write(Pdu pdu) throws PduException, IOException {
synchronized (out) {
out.write(pdu.buffer().array());
out.flush();
logger.debug(">>> {}", pdu.buffer().hexDump());
}
}
@Override
public void close() {
try {
socket.close();
} catch (IOException e) {
logger.debug("Connection closing error.", e);
}
socket = null;
in = null;
out = null;
bb = null;
}
private Pdu tryToReadBuffer() throws PduException {
if (bb.length() >= Pdu.HEADER_LENGTH) {
long commandLength = bb.readInt();
if (bb.length() >= commandLength)
return parser.parse(new ByteBuffer(bb.removeBytes((int) commandLength)));
}
return null;
}
}
| Java |
package org.bulatnig.smpp;
/**
* General SMPP exception.
*
* @author Bulat Nigmatullin
*/
public class SmppException extends Exception {
public SmppException() {
super();
}
public SmppException(String message) {
super(message);
}
public SmppException(String message, Throwable cause) {
super(message, cause);
}
public SmppException(Throwable cause) {
super(cause);
}
}
| Java |
package org.bulatnig.smpp.pdu;
/**
* Standard PDU identificators.
*
* @author Bulat Nigmatullin
*/
public enum CommandId {
INSTANCE;
/**
* This is a generic negative acknowledgement to an SMPP PDU submitted with
* an invalid message header. A generic_nack response is returned in the
* following cases:<br/> • Invalid command_length<br/> If the receiving
* SMPP entity, on decoding an SMPP PDU, detects an invalid command_length
* (either too short or too long), it should assume that the data is
* corrupt. In such cases a generic_nack PDU must be returned to the message
* originator. • Unknown command_id<br/> If an unknown or invalid
* command_id is received, a generic_nack PDU must also be returned to the
* originator.
*/
public static final long GENERIC_NACK = 0x80000000L;
/**
* An ESME bound as a Receiver is authorised to receive short messages from
* the SMSC and to return the corresponding SMPP message responses to the
* SMSC.
*/
public static final long BIND_RECEIVER = 0x00000001L;
/**
* BindReceiver Response PDU.
*/
public static final long BIND_RECEIVER_RESP = 0x80000001L;
/**
* An ESME bound as a Transmitter is authorised to send short messages to
* the SMSC and to receive the corresponding SMPP responses from the SMSC.
* An ESME indicates its desire not to receive (mobile) originated messages
* from other SME’s (e.g. mobile stations) by binding as a Transmitter.
*/
public static final long BIND_TRANSMITTER = 0x00000002L;
/**
* BindTransmitter Response PDU.
*/
public static final long BIND_TRANSMITTER_RESP = 0x80000002L;
/**
* This command is issued by the ESME to query the status of a previously
* submitted short message.<br/> The matching mechanism is based on the
* SMSC assigned message_id and source address. Where the original
* submit_sm, data_sm or submit_multi ‘source address’ was defaulted to
* NULL, then the source address in the query_sm command should also be set
* to NULL.
*/
public static final long QUERY_SM = 0x00000003L;
/**
* QuerySM Response PDU.
*/
public static final long QUERY_SM_RESP = 0x80000003L;
/**
* This operation is used by an ESME to submit a short message to the SMSC
* for onward transmission to a specified short message entity (SME). The
* submit_sm PDU does not support the transaction message mode.
*/
public static final long SUBMIT_SM = 0x00000004L;
/**
* SubmitSM Response PDU.
*/
public static final long SUBMIT_SM_RESP = 0x80000004L;
/**
* The deliver_sm is issued by the SMSC to send a message to an ESME. Using
* this command,the SMSC may route a short message to the ESME for delivery.
* <br/>
* <p/>
* In addition the SMSC uses the deliver_sm operation to transfer the
* following types of short messages to the ESME:-<br/> • SMSC Delivery
* Receipt. A delivery receipt relating to a a message which had been
* previously submitted with the submit_sm operation and the ESME had
* requested a delivery receipt via the registered_delivery parameter. The
* delivery receipt data relating to the original short message will be
* included in the short_message field of the deliver_sm. (Reference
* Appendix B for an example Delivery Receipt format.)<br/> • SME Delivery
* Acknowledgement. The user data of the SME delivery acknowledgement is
* included in the short_message field of the deliver_sm<br/> • SME
* Manual/User Acknowledgement. The user data of the SME delivery
* acknowledgement is included in the short_message field of the deliver_sm
* <br/> • Intermediate Notification.
*/
public static final long DELIVER_SM = 0x00000005L;
/**
* DeliverSM Response PDU.
*/
public static final long DELIVER_SM_RESP = 0x80000005L;
/**
* The purpose of the SMPP unbind operation is to deregister an instance of
* an ESME from the SMSC and inform the SMSC that the ESME no longer wishes
* to use this network connection for the submission or delivery of
* messages.<br/> Thus, the unbind operation may be viewed as a form of
* SMSC logoff request to close the current SMPP session.
*/
public static final long UNBIND = 0x00000006L;
/**
* Unbind Response PDU.
*/
public static final long UNBIND_RESP = 0x80000006L;
/**
* This command is issued by the ESME to replace a previously submitted
* short message that is still pending delivery. The matching mechanism is
* based on the message_id and source address of the original message.<br/>
* <p/>
* Where the original submit_sm ‘source address’ was defaulted to NULL, then
* the source address in the replace_sm command should also be NULL
*/
public static final long REPLACE_SM = 0x00000007L;
/**
* ReplaceSM Response PDU.
*/
public static final long REPLACE_SM_RESP = 0x80000007L;
/**
* This command is issued by the ESME to cancel one or more previously
* submitted short messages that are still pending delivery. The command may
* specify a particular message to cancel, or all messages for a particular
* source, destination and service_type are to be cancelled.<br/> • If the
* message_id is set to the ID of a previously submitted message, then
* provided the source address supplied by the ESME matches that of the
* stored message, that message will be cancelled.<br/> • If the message_id
* is NULL, all outstanding undelivered messages with matching source and
* destination addresses given in the PDU are cancelled. If provided,
* service_type is included in this matching.<br/> Where the original
* submit_sm, data_sm or submit_multi ‘source address’ was defaulted to
* NULL, then the source address in the cancel_sm command should also be
* NULL.
*/
public static final long CANCEL_SM = 0x00000008L;
/**
* CancelSM Response PDU.
*/
public static final long CANCEL_SM_RESP = 0x80000008L;
/**
* An ESME bound as a Transceiver is allowed to send messages to the SMSC
* and receive messages from the SMSC over a single SMPP session.
*/
public static final long BIND_TRANSCEIVER = 0x00000009L;
/**
* BindTransceiver Response PDU.
*/
public static final long BIND_TRANSCEIVER_RESP = 0x80000009L;
/**
* This operation is used by the SMSC to signal an ESME to originate a
* bind_receiver request to the SMSC.
*/
public static final long OUTBIND = 0x0000000BL;
/**
* This message can be sent by either the ESME or SMSC and is used to
* provide a confidencecheck of the communication path between an ESME and
* an SMSC. On receipt of this request the receiving party should respond
* with an enquire_link_resp, thus verifying that the application level
* connection between the SMSC and the ESME is functioning. The ESME may
* also respond by sending any valid SMPP primitive.
*/
public static final long ENQUIRE_LINK = 0x00000015L;
/**
* EnquireLink Response PDU.
*/
public static final long ENQUIRE_LINK_RESP = 0x80000015L;
/**
* The submit_multi operation may be used to submit an SMPP message for
* delivery to multiple recipients or to one or more Distribution Lists. The
* submit_multi PDU does not support the transaction message mode.
*/
public static final long SUBMIT_MULTI = 0x00000021L;
/**
* SubmitMulti Response PDU.
*/
public static final long SUBMIT_MULTI_RESP = 0x80000021L;
/**
* This message is sent by the SMSC to the ESME, when the SMSC has detected
* that a particular mobile subscriber has become available and a delivery
* pending flag had been set for that subscriber from a previous data_sm
* operation.<br/>
* <p/>
* It may be used for example to trigger a data content ‘Push’ to the
* subscriber from a WAP Proxy Server.<br/>
* <p/>
* Note: There is no alert_notification_resp PDU.
*/
public static final long ALERT_NOTIFICATION = 0x00000102L;
/**
* This command is used to transfer data between the SMSC and the ESME. It
* may be used by both the ESME and SMSC.<br/>
* <p/>
* This command is an alternative to the submit_sm and deliver_sm commands.
* It is introduced as a new command to be used by interactive applications
* such as those provided via a WAP framework.<br/>
* <p/>
* The ESME may use this command to request the SMSC to transfer a message
* to an MS. The SMSC may also use this command to transfer an MS originated
* message to an ESME.
* <p/>
* <br/> In addition, the data_sm operation can be used to transfer the
* following types of special messages to the ESME:-<br/> • SMSC Delivery
* Receipt.<br/> • SME Delivery Acknowledgement.The user data of the SME
* delivery acknowledgement is included in the short_message field of the
* data_sm<br/> •SME Manual/User Acknowledgement. The user data of the SME
* delivery acknowledgement is included in the short_message field of the
* data_sm<br/> • Intermediate Notification.<br/>
*/
public static final long DATA_SM = 0x00000103L;
/**
*
*/
public static final long DATA_SM_RESP = 0x80000103L;
}
| Java |
package org.bulatnig.smpp.pdu;
/**
* Type of Number (TON).
*
* @author Bulat Nigmatullin
*/
public enum Ton {
INSTANCE;
/**
* Unknown.
*/
public static final int UNKNOWN = 0;
/**
* International.
*/
public static final int INTERNATIONAL = 1;
/**
* National.
*/
public static final int NATIONAL = 2;
/**
* Network Specific.
*/
public static final int NETWORK_SPECIFIC = 3;
/**
* Subscriber number.
*/
public static final int SUBSCRIBER_NUMBER = 4;
/**
* Alphanumeric.
*/
public static final int ALPHANUMERIC = 5;
/**
* Abbreviated.
*/
public static final int ABBREVIATED = 6;
}
| Java |
package org.bulatnig.smpp.pdu;
import org.bulatnig.smpp.util.ByteBuffer;
/**
* Parses PDU's from bytes.
*
* @author Bulat Nigmatullin
*/
public interface PduParser {
/**
* Parse PDU.
*
* @param bb one pdu bytes
* @return Pdu
* @throws PduException pdu parsing failed
*/
Pdu parse(ByteBuffer bb) throws PduException;
}
| Java |
package org.bulatnig.smpp.pdu;
import org.bulatnig.smpp.SmppException;
/**
* PDU parsing failed.
*
* @author Bulat Nigmatullin
*/
public class PduException extends SmppException {
public PduException() {
super();
}
public PduException(String message) {
super(message);
}
public PduException(String message, Throwable cause) {
super(message, cause);
}
public PduException(Throwable cause) {
super(cause);
}
}
| Java |
package org.bulatnig.smpp.pdu;
/**
* Standard command statuses.
* <p/>
* The command_status field indicates the success or failure of an SMPP request.
* It is relevant only in the SMPP response PDU and it must contain a NULL value
* in an SMPP request PDU.
*
* @author Bulat Nigmatullin
*/
public enum CommandStatus {
INSTANCE;
/**
* No Error.
*/
public static final long ESME_ROK = 0x00000000L;
/**
* Message Length is invalid.
*/
public static final long ESME_RINVMSGLEN = 0x00000001L;
/**
* Command Length is invalid.
*/
public static final long ESME_RINVCMDLEN = 0x00000002L;
/**
* Invalid Command ID.
*/
public static final long ESME_RINVCMDID = 0x00000003L;
/**
* Incorrect BIND Status for given command.
*/
public static final long ESME_RINVBNDSTS = 0x00000004L;
/**
* ESME ALready in Bound State.
*/
public static final long ESME_RALYBND = 0x00000005L;
/**
* Invalid Priority Flag.
*/
public static final long ESME_RINVPRTFLG = 0x00000006L;
/**
* Invalid Registered Delivery Flag.
*/
public static final long ESME_RINVREGDLVFLG = 0x00000007L;
/**
* System Error.
*/
public static final long ESME_RSYSERR = 0x00000008L;
/**
* Invalid Source Address.
*/
public static final long ESME_RINVSRCADR = 0x0000000AL;
/**
* Invalid Dest Addr.
*/
public static final long ESME_RINVDSTADR = 0x0000000BL;
/**
* Message ID is invalid.
*/
public static final long ESME_RINVMSGID = 0x0000000CL;
/**
* Bind Failed.
*/
public static final long ESME_RBINDFAIL = 0x0000000DL;
/**
* Invalid Password.
*/
public static final long ESME_RINVPASWD = 0x0000000EL;
/**
* Invalid System ID.
*/
public static final long ESME_RINVSYSID = 0x0000000FL;
/**
* Cancel SM Failed.
*/
public static final long ESME_RCANCELFAIL = 0x00000011L;
/**
* Replace SM Failed.
*/
public static final long ESME_RREPLACEFAIL = 0x00000013L;
/**
* Message Queue Full.
*/
public static final long ESME_RMSGQFUL = 0x00000014L;
/**
* Invalid Service Type.
*/
public static final long ESME_RINVSERTYP = 0x00000015L;
/**
* Invalid number of destinations.
*/
public static final long ESME_RINVNUMDESTS = 0x00000033L;
/**
* Invalid Distribution List name.
*/
public static final long ESME_RINVDLNAME = 0x00000034L;
/**
* Destination flag is invalid (submit_multi).
*/
public static final long ESME_RINVDESTFLAG = 0x00000040L;
/**
* Invalid ‘submit with replace’ request (i.e. submit_sm with
* replace_if_present_flag set).
*/
public static final long ESME_RINVSUBREP = 0x00000042L;
/**
* Invalid esm_class field data.
*/
public static final long ESME_RINVESMCLASS = 0x00000043L;
/**
* Cannot Submit to Distribution List.
*/
public static final long ESME_RCNTSUBDL = 0x00000044L;
/**
* submit_sm or submit_multi failed.
*/
public static final long ESME_RSUBMITFAIL = 0x00000045L;
/**
* Invalid Source address TON.
*/
public static final long ESME_RINVSRCTON = 0x00000048L;
/**
* Invalid Source address NPI.
*/
public static final long ESME_RINVSRCNPI = 0x00000049L;
/**
* Invalid Destination address TON.
*/
public static final long ESME_RINVDSTTON = 0x00000050L;
/**
* Invalid Destination address NPI.
*/
public static final long ESME_RINVDSTNPI = 0x00000051L;
/**
* Invalid system_type field.
*/
public static final long ESME_RINVSYSTYP = 0x00000053L;
/**
* Invalid replace_if_present flag.
*/
public static final long ESME_RINVREPFLAG = 0x00000054L;
/**
* Invalid number of messages.
*/
public static final long ESME_RINVNUMMSGS = 0x00000055L;
/**
* Throttling error (ESME has exceeded allowed message limits).
*/
public static final long ESME_RTHROTTLED = 0x00000058L;
/**
* Invalid Scheduled Delivery Time.
*/
public static final long ESME_RINVSCHED = 0x00000061L;
/**
* Invalid message validity period (Expiry time).
*/
public static final long ESME_RINVEXPIRY = 0x00000062L;
/**
* Predefined Message Invalid or Not Found.
*/
public static final long ESME_RINVDFTMSGID = 0x00000063L;
/**
* ESME Receiver Temporary App Error Code.
*/
public static final long ESME_RX_T_APPN = 0x00000064L;
/**
* ESME Receiver Permanent App Error Code.
*/
public static final long ESME_RX_P_APPN = 0x00000065L;
/**
* ESME Receiver Reject Message Error Code.
*/
public static final long ESME_RX_R_APPN = 0x00000066L;
/**
* query_sm request failed.
*/
public static final long ESME_RQUERYFAIL = 0x00000067L;
/**
* Error in the optional part of the PDU Body.
*/
public static final long ESME_RINVOPTPARSTREAM = 0x000000C0L;
/**
* Optional Parameter not allowed.
*/
public static final long ESME_ROPTPARNOTALLWD = 0x000000C1L;
/**
* Invalid Parameter Length.
*/
public static final long ESME_RINVPARLEN = 0x000000C2L;
/**
* Expected Optional Parameter missing.
*/
public static final long ESME_RMISSINGOPTPARAM = 0x000000C3L;
/**
* Invalid Optional Parameter Value.
*/
public static final long ESME_RINVOPTPARAMVAL = 0x000000C4L;
/**
* Delivery Failure (used for data_sm_resp).
*/
public static final long ESME_RDELIVERYFAILURE = 0x000000FEL;
/**
* Unknown Error.
*/
public static final long ESME_RUNKNOWNERR = 0x000000FFL;
}
| Java |
package org.bulatnig.smpp.pdu;
import org.bulatnig.smpp.util.ByteBuffer;
/**
* Protocol Data Unit.
*
* @author Bulat Nigmatullin
*/
public interface Pdu {
/**
* Header length.
*/
public static final int HEADER_LENGTH = 16;
/**
* Calculate and return PDU bytes.
*
* @return pdu bytes
* @throws PduException pdu contains wrong values
*/
public ByteBuffer buffer() throws PduException;
public long getCommandId();
public long getCommandStatus();
public long getSequenceNumber();
public void setCommandStatus(long commandStatus);
public void setSequenceNumber(long sequenceNumber);
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.*;
import org.bulatnig.smpp.pdu.tlv.impl.DefaultTlvParser;
import org.bulatnig.smpp.pdu.tlv.TlvException;
import org.bulatnig.smpp.pdu.tlv.TlvParser;
import org.bulatnig.smpp.util.ByteBuffer;
/**
* Default PDU parser implementation.
*
* @author Bulat Nigmatullin
*/
public class DefaultPduParser implements PduParser {
public TlvParser tlvParser = new DefaultTlvParser();
@Override
public Pdu parse(ByteBuffer bb) throws PduException {
final byte[] original = bb.array();
long commandId = bb.readInt(4);
AbstractPdu result;
try {
if (CommandId.SUBMIT_SM_RESP == commandId) {
result = new SubmitSmResp(bb);
} else if (CommandId.DELIVER_SM == commandId) {
result = new DeliverSm(bb);
} else if (CommandId.GENERIC_NACK == commandId) {
result = new GenericNack(bb);
} else if (CommandId.BIND_RECEIVER == commandId) {
result = new BindReceiver(bb);
} else if (CommandId.BIND_RECEIVER_RESP == commandId) {
result = new BindReceiverResp(bb);
} else if (CommandId.BIND_TRANSMITTER == commandId) {
result = new BindTransmitter(bb);
} else if (CommandId.BIND_TRANSMITTER_RESP == commandId) {
result = new BindTransmitterResp(bb);
} else if (CommandId.QUERY_SM == commandId) {
result = new QuerySm(bb);
} else if (CommandId.QUERY_SM_RESP== commandId) {
result = new QuerySmResp(bb);
} else if (CommandId.SUBMIT_SM == commandId) {
result = new SubmitSm(bb);
} else if (CommandId.DELIVER_SM_RESP == commandId) {
result = new DeliverSmResp(bb);
} else if (CommandId.UNBIND == commandId) {
result = new Unbind(bb);
} else if (CommandId.UNBIND_RESP == commandId) {
result = new UnbindResp(bb);
} else if (CommandId.BIND_TRANSCEIVER == commandId) {
result = new BindTransceiver(bb);
} else if (CommandId.BIND_TRANSCEIVER_RESP == commandId) {
result = new BindTransceiverResp(bb);
} else if (CommandId.ENQUIRE_LINK == commandId) {
result = new EnquireLink(bb);
} else if (CommandId.ENQUIRE_LINK_RESP == commandId) {
result = new EnquireLinkResp(bb);
} else if (CommandId.ALERT_NOTIFICATION == commandId) {
result = new AlertNotification(bb);
} else {
throw new PduException("Corresponding PDU not found: " + bb.hexDump() + ".");
}
} catch (IndexOutOfBoundsException e) {
throw new PduException("Malformed PDU: " + new ByteBuffer(original).hexDump() + ".", e);
}
if (bb.length() > 0) {
try {
result.tlvs = tlvParser.parse(bb);
} catch (TlvException e) {
throw new PduException("TLV parsing failed. Malformed PDU: " + new ByteBuffer(original).hexDump() + ".", e);
}
}
return result;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* BindTransceiver response PDU.
*
* @author Bulat Nigmatullin
*/
public class BindTransceiverResp extends AbstractPdu {
/**
* SMSC identifier. Identifies the SMSC to the ESME.
*/
private String systemId;
public BindTransceiverResp() {
super(CommandId.BIND_TRANSCEIVER_RESP);
}
BindTransceiverResp(ByteBuffer bb) throws PduException {
super(bb);
try {
systemId = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("System id parsing failed.", e);
}
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendCString(systemId);
return bb;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
/**
* EnquireLink response PDU.
*
* @author Bulat Nigmatullin
*/
public class EnquireLinkResp extends AbstractPdu {
public EnquireLinkResp() {
super(CommandId.ENQUIRE_LINK_RESP);
}
protected EnquireLinkResp(ByteBuffer bb) throws PduException {
super(bb);
}
@Override
protected ByteBuffer body() {
return null;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import java.io.UnsupportedEncodingException;
/**
* SMSC Delivery Receipt parser.
* <p/>
* Examples:
* id:c449ab9744f47b6af1879e49e75e4f40 sub:001 dlvrd:0 submit date:0610191018 done date:0610191018 stat:ACCEPTD err:0 text:This is an Acti
* id:7220bb6bd0be98fa628de66590f80070 sub:001 dlvrd:1 submit date:0610190851 done date:0610190951 stat:DELIVRD err:0 text:This is an Acti
* id:b756c4f97aa2e1e67377dffc5e2f7d9b sub:001 dlvrd:0 submit date:0610191211 done date:0610191211 stat:REJECTD err:1 text:This is an Acti
* id:bd778cd76ae9e79da2ddc8188c68f8c1 sub:001 dlvrd:0 submit date:0610191533 done date:0610191539 stat:UNDELIV err:1 text:This is an Acti
* id:1661543146 sub:001 dlvrd:001 submit date:1101261110 done date:1101261110 stat:DELIVRD err:000 text:Hello, how are you?
*
* @author Bulat Nigmatullin
*/
public class SmscDeliveryReceipt {
private static final String CHARSET = "US-ASCII";
private static final String SPACE = " ";
private String id;
private String sub;
private String dlvrd;
private String submitDate;
private String doneDate;
private String stat;
private String err;
private String text;
/**
* Empty construtor for creating SMSC Delivery Receipt.
*/
public SmscDeliveryReceipt() {
}
/**
* Parse SMSC Delivery Receipt from bytes ( proper esm_class should be set on PDU ).
*
* @param bytes received bytes
*/
public SmscDeliveryReceipt(byte[] bytes) {
try {
String data = new String(bytes, CHARSET);
int index = data.indexOf(SPACE);
id = data.substring(3, index);
int index2 = data.indexOf(SPACE, index + 1);
sub = data.substring(index + 5, index2);
index = index2;
index2 = data.indexOf(SPACE, index + 1);
dlvrd = data.substring(index + 7, index2);
index = index2;
index2 = data.indexOf(SPACE, index + 1);
index2 = data.indexOf(SPACE, index2 + 1);
submitDate = data.substring(index + 13, index2);
index = index2;
index2 = data.indexOf(SPACE, index + 1);
index2 = data.indexOf(SPACE, index2 + 1);
doneDate = data.substring(index + 11, index2);
index = index2;
index2 = data.indexOf(SPACE, index + 1);
stat = data.substring(index + 6, index2);
index = index2;
index2 = data.indexOf(SPACE, index + 1);
err = data.substring(index + 5, index2);
index = index2;
text = data.substring(index + 6, data.length());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("US-ASCII charset is not supported. Consult developer.", e);
}
}
public byte[] toBytes() {
StringBuilder builder = new StringBuilder();
builder.append("id:");
if (id != null)
builder.append(id);
builder.append(" sub:");
if (sub != null)
builder.append(sub);
builder.append(" dlvrd:");
if (dlvrd != null)
builder.append(dlvrd);
builder.append(" submit date:");
if (submitDate != null)
builder.append(submitDate);
builder.append(" done date:");
if (doneDate != null)
builder.append(doneDate);
builder.append(" stat:");
if (stat != null)
builder.append(stat);
builder.append(" err:");
if (err != null)
builder.append(err);
builder.append(" text:");
if (text != null)
builder.append(text);
try {
return builder.toString().getBytes(CHARSET);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("US-ASCII charset is not supported. Consult developer.", e);
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSub() {
return sub;
}
public void setSub(String sub) {
this.sub = sub;
}
public String getDlvrd() {
return dlvrd;
}
public void setDlvrd(String dlvrd) {
this.dlvrd = dlvrd;
}
public String getSubmitDate() {
return submitDate;
}
public void setSubmitDate(String submitDate) {
this.submitDate = submitDate;
}
public String getDoneDate() {
return doneDate;
}
public void setDoneDate(String doneDate) {
this.doneDate = doneDate;
}
public String getStat() {
return stat;
}
public void setStat(String stat) {
this.stat = stat;
}
public String getErr() {
return err;
}
public void setErr(String err) {
this.err = err;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* An ESME bound as a Transmitter is authorised to send short messages to the
* SMSC and to receive the corresponding SMPP responses from the SMSC. An ESME
* indicates its desire not to receive (mobile) originated messages from other
* SME’s (e.g. mobile stations) by binding as a Transmitter.
*
* @author Bulat Nigmatullin
*/
public class BindTransmitter extends AbstractPdu {
/**
* Identifies the ESME system requesting to bind as a receiver with the
* SMSC.
*/
private String systemId;
/**
* The password may be used by the SMSC for security reasons to authenticate
* the ESME requesting to bind.
*/
private String password;
/**
* Identifies the type of ESME system requesting to bind as a receiver with
* the SMSC.
*/
private String systemType;
/**
* Identifies the version of the SMPP protocol supported by the ESME.
*/
private int interfaceVersion;
/**
* Type of Number (TON) for ESME address(es) served via this SMPP receiver
* session. Set to NULL if not known.
*/
private int addrTon;
/**
* Numbering Plan Indicator (NPI) for ESME address(es) served via this SMPP
* receiver session. Set to NULL if not known.
*/
private int addrNpi;
/**
* A single ESME address or a range of ESME addresses served via this SMPP
* receiver session. The parameter value is represented in UNIX regular
* expression format (see Appendix A). Set to NULL if not known.
*/
private String addressRange;
public BindTransmitter() {
super(CommandId.BIND_TRANSMITTER);
}
BindTransmitter(ByteBuffer bb) throws PduException {
super(bb);
try {
systemId = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("System id parsing failed.", e);
}
try {
password = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Password parsing failed.", e);
}
try {
systemType= bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("System type parsing failed.", e);
}
interfaceVersion = bb.removeByte();
addrTon = bb.removeByte();
addrNpi = bb.removeByte();
try {
addressRange = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Address range parsing failed.", e);
}
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendCString(systemId);
bb.appendCString(password);
bb.appendCString(systemType);
bb.appendByte(interfaceVersion);
bb.appendByte(addrTon);
bb.appendByte(addrNpi);
bb.appendCString(addressRange);
return bb;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSystemType() {
return systemType;
}
public void setSystemType(String systemType) {
this.systemType = systemType;
}
public int getInterfaceVersion() {
return interfaceVersion;
}
public void setInterfaceVersion(int interfaceVersion) {
this.interfaceVersion = interfaceVersion;
}
public int getAddrTon() {
return addrTon;
}
public void setAddrTon(int addrTon) {
this.addrTon = addrTon;
}
public int getAddrNpi() {
return addrNpi;
}
public void setAddrNpi(int addrNpi) {
this.addrNpi = addrNpi;
}
public String getAddressRange() {
return addressRange;
}
public void setAddressRange(String addressRange) {
this.addressRange = addressRange;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* This message is sent by the SMSC to the ESME, when the SMSC has detected that
* a particular mobile subscriber has become available and a delivery pending
* flag had been set for that subscriber from a previous data_sm operation.
*
* @author Bulat Nigmatullin
*/
public class AlertNotification extends AbstractPdu {
/**
* Type of number for the MS which has become available. If not known, set
* to NULL.
*/
private int sourceAddrTon;
/**
* Numbering Plan Indicator for the MS which has become available. If not
* known, set to NULL.
*/
private int sourceAddrNpi;
/**
* Address of MS which has become available.
*/
private String sourceAddr;
/**
* Type of number for destination address which requested an alert on a
* particular MS becoming available. If not known, set to NULL.
*/
private int esmeAddrTon;
/**
* Numbering Plan Indicator for ESME which requested an alert on a
* particular MS becoming available. If not known, set to NULL.
*/
private int esmeAddrNpi;
/**
* Address of ESME which requested an alert on a particular MS becoming
* available.
*/
private String esmeAddr;
public AlertNotification() {
super(CommandId.ALERT_NOTIFICATION);
}
AlertNotification(ByteBuffer bb) throws PduException {
super(bb);
sourceAddrTon = bb.removeByte();
sourceAddrNpi = bb.removeByte();
try {
sourceAddr = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Source address parsing failed", e);
}
esmeAddrTon = bb.removeByte();
esmeAddrNpi = bb.removeByte();
try {
esmeAddr = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Esme address parsing failed", e);
}
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendByte(sourceAddrTon);
bb.appendByte(sourceAddrNpi);
bb.appendCString(sourceAddr);
bb.appendByte(esmeAddrTon);
bb.appendByte(esmeAddrNpi);
bb.appendCString(esmeAddr);
return bb;
}
public int getSourceAddrTon() {
return sourceAddrTon;
}
public void setSourceAddrTon(int sourceAddrTon) {
this.sourceAddrTon = sourceAddrTon;
}
public int getSourceAddrNpi() {
return sourceAddrNpi;
}
public void setSourceAddrNpi(int sourceAddrNpi) {
this.sourceAddrNpi = sourceAddrNpi;
}
public String getSourceAddr() {
return sourceAddr;
}
public void setSourceAddr(String sourceAddr) {
this.sourceAddr = sourceAddr;
}
public int getEsmeAddrTon() {
return esmeAddrTon;
}
public void setEsmeAddrTon(int esmeAddrTon) {
this.esmeAddrTon = esmeAddrTon;
}
public int getEsmeAddrNpi() {
return esmeAddrNpi;
}
public void setEsmeAddrNpi(int esmeAddrNpi) {
this.esmeAddrNpi = esmeAddrNpi;
}
public String getEsmeAddr() {
return esmeAddr;
}
public void setEsmeAddr(String esmeAddr) {
this.esmeAddr = esmeAddr;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
/**
* This message can be sent by either the ESME or SMSC and is used to provide a
* confidencecheck of the communication path between an ESME and an SMSC. On
* receipt of this request the receiving party should respond with an
* enquire_link_resp, thus verifying that the application level connection
* between the SMSC and the ESME is functioning. The ESME may also respond by
* sending any valid SMPP primitive.
*
* @author Bulat Nigmatullin
*/
public class EnquireLink extends AbstractPdu {
public EnquireLink() {
super(CommandId.ENQUIRE_LINK);
}
protected EnquireLink(ByteBuffer bb) throws PduException {
super(bb);
}
@Override
protected ByteBuffer body() {
return null;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* The deliver_sm is issued by the SMSC to send a message to an ESME. Using this
* command,the SMSC may route a short message to the ESME for delivery.<br/>
* <p/>
* In addition the SMSC uses the deliver_sm operation to transfer the following
* types of short messages to the ESME:-<br/> • SMSC Delivery Receipt. A
* delivery receipt relating to a a message which had been previously submitted
* with the submit_sm operation and the ESME had requested a delivery receipt
* via the registered_delivery parameter. The delivery receipt data relating to
* the original short message will be included in the short_message field of the
* deliver_sm. (Reference Appendix B for an example Delivery Receipt format.)<br/> •
* SME Delivery Acknowledgement. The user data of the SME delivery
* acknowledgement is included in the short_message field of the deliver_sm<br/> •
* SME Manual/User Acknowledgement. The user data of the SME delivery
* acknowledgement is included in the short_message field of the deliver_sm<br/> •
* Intermediate Notification.
*
* @author Bulat Nigmatullin
*/
public class DeliverSm extends AbstractPdu {
/**
* The service_type parameter can be used to indicate the SMS Application
* service associated with the message.
*/
private String serviceType;
/**
* Type of Number for source address. If not known, set to NULL (Unknown).
*/
private int sourceAddrTon;
/**
* Numbering Plan Indicator for source. If not known, set to NULL (Unknown).
*/
private int sourceAddrNpi;
/**
* Address of SME which originated this message. If not known, set to NULL
* (Unknown).
*/
private String sourceAddr;
/**
* Type of number of destination SME.
*/
private int destAddrTon;
/**
* Numbering Plan Indicator of destination SME.
*/
private int destAddrNpi;
/**
* Destination address of destination SME.
*/
private String destinationAddr;
/**
* Indicates Message Type and enhanced network services.
*/
private int esmClass;
/**
* Protocol Identifier. Network Specific Field.
*/
private int protocolId;
/**
* Designates the priority level of the message.
*/
private int priorityFlag;
/**
* This field is unused for deliver_sm. It must be set to NULL.
*/
private String scheduleDeliveryTime;
/**
* This field is unused for deliver_sm It must be set to NULL.
*/
private String validityPeriod;
/**
* Indicates if an ESME acknowledgement is required.
*/
private int registeredDelivery;
/**
* Not used in deliver_sm. It must be set to NULL.
*/
private int replaceIfPresentFlag;
/**
* Indicates the encoding scheme of the short message.
*/
private int dataCoding;
/**
* Unused in deliver_sm. It must be set to NULL.
*/
private int smDefaultMsgId;
/**
* Up to 254 octets of short message user data.<br/>
* <p/>
* When sending messages longer than 254 octets the message_payload
* parameter should be used and the sm_length parameter should be set to
* zero.<br/>
* <p/>
* Note: The message data should be inserted in either the short_message or
* the message_payload parameters. Both parameters must not be used
* simultaneously.
*/
private byte[] shortMessage;
public DeliverSm() {
super(CommandId.DELIVER_SM);
}
DeliverSm(ByteBuffer bb) throws PduException {
super(bb);
try {
serviceType = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Service type parsing failed.", e);
}
sourceAddrTon = bb.removeByte();
sourceAddrNpi = bb.removeByte();
try {
sourceAddr = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Service type parsing failed.", e);
}
destAddrTon = bb.removeByte();
destAddrNpi = bb.removeByte();
try {
destinationAddr = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Service type parsing failed.", e);
}
esmClass = bb.removeByte();
protocolId = bb.removeByte();
priorityFlag = bb.removeByte();
try {
scheduleDeliveryTime = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Service type parsing failed.", e);
}
try {
validityPeriod = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Service type parsing failed.", e);
}
registeredDelivery = bb.removeByte();
replaceIfPresentFlag = bb.removeByte();
dataCoding = bb.removeByte();
smDefaultMsgId = bb.removeByte();
int shortMessageLength = bb.removeByte();
shortMessage = bb.removeBytes(shortMessageLength);
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendCString(serviceType);
bb.appendByte(sourceAddrTon);
bb.appendByte(sourceAddrNpi);
bb.appendCString(sourceAddr);
bb.appendByte(destAddrTon);
bb.appendByte(destAddrNpi);
bb.appendCString(destinationAddr);
bb.appendByte(esmClass);
bb.appendByte(protocolId);
bb.appendByte(priorityFlag);
bb.appendCString(scheduleDeliveryTime);
bb.appendCString(validityPeriod);
bb.appendByte(registeredDelivery);
bb.appendByte(replaceIfPresentFlag);
bb.appendByte(dataCoding);
bb.appendByte(smDefaultMsgId);
if (shortMessage != null) {
bb.appendByte(shortMessage.length);
bb.appendBytes(shortMessage);
} else {
bb.appendByte(0);
}
return bb;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public int getSourceAddrTon() {
return sourceAddrTon;
}
public void setSourceAddrTon(int sourceAddrTon) {
this.sourceAddrTon = sourceAddrTon;
}
public int getSourceAddrNpi() {
return sourceAddrNpi;
}
public void setSourceAddrNpi(int sourceAddrNpi) {
this.sourceAddrNpi = sourceAddrNpi;
}
public String getSourceAddr() {
return sourceAddr;
}
public void setSourceAddr(String sourceAddr) {
this.sourceAddr = sourceAddr;
}
public int getDestAddrTon() {
return destAddrTon;
}
public void setDestAddrTon(int destAddrTon) {
this.destAddrTon = destAddrTon;
}
public int getDestAddrNpi() {
return destAddrNpi;
}
public void setDestAddrNpi(int destAddrNpi) {
this.destAddrNpi = destAddrNpi;
}
public String getDestinationAddr() {
return destinationAddr;
}
public void setDestinationAddr(String destinationAddr) {
this.destinationAddr = destinationAddr;
}
public int getEsmClass() {
return esmClass;
}
public void setEsmClass(int esmClass) {
this.esmClass = esmClass;
}
public int getProtocolId() {
return protocolId;
}
public void setProtocolId(int protocolId) {
this.protocolId = protocolId;
}
public int getPriorityFlag() {
return priorityFlag;
}
public void setPriorityFlag(int priorityFlag) {
this.priorityFlag = priorityFlag;
}
public String getScheduleDeliveryTime() {
return scheduleDeliveryTime;
}
public void setScheduleDeliveryTime(String scheduleDeliveryTime) {
this.scheduleDeliveryTime = scheduleDeliveryTime;
}
public String getValidityPeriod() {
return validityPeriod;
}
public void setValidityPeriod(String validityPeriod) {
this.validityPeriod = validityPeriod;
}
public int getRegisteredDelivery() {
return registeredDelivery;
}
public void setRegisteredDelivery(int registeredDelivery) {
this.registeredDelivery = registeredDelivery;
}
public int getReplaceIfPresentFlag() {
return replaceIfPresentFlag;
}
public void setReplaceIfPresentFlag(int replaceIfPresentFlag) {
this.replaceIfPresentFlag = replaceIfPresentFlag;
}
public int getDataCoding() {
return dataCoding;
}
public void setDataCoding(int dataCoding) {
this.dataCoding = dataCoding;
}
public int getSmDefaultMsgId() {
return smDefaultMsgId;
}
public void setSmDefaultMsgId(int smDefaultMsgId) {
this.smDefaultMsgId = smDefaultMsgId;
}
public byte[] getShortMessage() {
return shortMessage;
}
public void setShortMessage(byte[] shortMessage) {
this.shortMessage = shortMessage;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
/**
* The purpose of the SMPP unbind operation is to deregister an instance of an
* ESME from the SMSC and inform the SMSC that the ESME no longer wishes to use
* this network connection for the submission or delivery of messages.<br/>
* <p/>
* Thus, the unbind operation may be viewed as a form of SMSC logoff request to
* close the current SMPP session.
*
* @author Bulat Nigmatullin
*/
public class Unbind extends AbstractPdu {
public Unbind() {
super(CommandId.UNBIND);
}
Unbind(ByteBuffer bb) throws PduException {
super(bb);
}
@Override
protected ByteBuffer body() {
return null;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
/**
* This is a generic negative acknowledgement to an SMPP PDU submitted with an
* invalid message header. A generic_nack response is returned in the following
* cases:<br/> • Invalid command_length<br/> If the receiving SMPP entity, on
* decoding an SMPP PDU, detects an invalid command_length (either too short or
* too long), it should assume that the data is corrupt. In such cases a
* generic_nack PDU must be returned to the message originator. • Unknown
* command_id<br/> If an unknown or invalid command_id is received, a
* generic_nack PDU must also be returned to the originator.
*
* @author Bulat Nigmatullin
*/
public class GenericNack extends AbstractPdu {
public GenericNack() {
super(CommandId.GENERIC_NACK);
}
GenericNack(ByteBuffer bb) throws PduException {
super(bb);
}
@Override
protected ByteBuffer body() {
return null;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* This command is issued by the ESME to query the status of a previously
* submitted short message.<br/>
* <p/>
* The matching mechanism is based on the SMSC assigned message_id and source
* address. Where the original submit_sm, data_sm or submit_multi ‘source
* address’ was defaulted to NULL, then the source address in the query_sm
* command should also be set to NULL.
*
* @author Bulat Nigmatullin
*/
public class QuerySm extends AbstractPdu {
/**
* Message ID of the message whose state is to be queried. This must be the
* SMSC assigned Message ID allocated to the original short message when
* submitted to the SMSC by the submit_sm, data_sm or submit_multi command,
* and returned in the response PDU by the SMSC.
*/
private String messageId;
/**
* Type of Number of message originator. This is used for verification
* purposes, and must match that supplied in the original request PDU (e.g.
* submit_sm). If not known, set to NULL.
*/
private int sourceAddrTon;
/**
* Numbering Plan Identity of message originator. This is used for
* verification purposes, and must match that supplied in the original
* request PDU (e.g. submit_sm). If not known, set to NULL.
*/
private int sourceAddrNpi;
/**
* Address of message originator. This is used for verification purposes,
* and must match that supplied in the original request PDU (e.g.
* submit_sm). If not known, set to NULL.
*/
private String sourceAddr;
public QuerySm() {
super(CommandId.QUERY_SM);
}
protected QuerySm(ByteBuffer bb) throws PduException {
super(bb);
try {
messageId = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Message id parsing failed.", e);
}
sourceAddrTon = bb.removeByte();
sourceAddrNpi = bb.removeByte();
try {
sourceAddr = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Source address parsing failed.", e);
}
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendCString(messageId);
bb.appendByte(sourceAddrTon);
bb.appendByte(sourceAddrNpi);
bb.appendCString(sourceAddr);
return bb;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public int getSourceAddrTon() {
return sourceAddrTon;
}
public void setSourceAddrTon(int sourceAddrTon) {
this.sourceAddrTon = sourceAddrTon;
}
public int getSourceAddrNpi() {
return sourceAddrNpi;
}
public void setSourceAddrNpi(int sourceAddrNpi) {
this.sourceAddrNpi = sourceAddrNpi;
}
public String getSourceAddr() {
return sourceAddr;
}
public void setSourceAddr(String sourceAddr) {
this.sourceAddr = sourceAddr;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.CommandStatus;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* SubmitSm response PDU.
*
* @author Bulat Nigmatullin
*/
public class SubmitSmResp extends AbstractPdu {
/**
* This field contains the SMSC message ID of the submitted message. It may
* be used at a later stage to query the status of a message, cancel or
* replace the message.
*/
private String messageId;
public SubmitSmResp() {
super(CommandId.SUBMIT_SM_RESP);
}
SubmitSmResp(ByteBuffer bb) throws PduException {
super(bb);
if (CommandStatus.ESME_ROK == getCommandStatus()) {
try {
messageId = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Message id parsing failed.", e);
}
} else if (bb.length() == 1) {
// Some SMSC ignore protocol and add null messageId value. This is the workaround for them.
bb.removeByte();
}
}
@Override
protected ByteBuffer body() {
if (CommandStatus.ESME_ROK != getCommandStatus())
return null;
ByteBuffer bb = new ByteBuffer();
bb.appendCString(messageId);
return bb;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* An ESME bound as a Receiver is authorised to receive short messages from the
* SMSC and to return the corresponding SMPP message responses to the SMSC.
*
* @author Bulat Nigmatullin
*/
public class BindReceiver extends AbstractPdu {
/**
* Identifies the ESME system requesting to bind as a receiver with the
* SMSC.
*/
private String systemId;
/**
* The password may be used by the SMSC for security reasons to authenticate
* the ESME requesting to bind.
*/
private String password;
/**
* Identifies the type of ESME system requesting to bind as a receiver with
* the SMSC.
*/
private String systemType;
/**
* Identifies the version of the SMPP protocol supported by the ESME.
*/
private int interfaceVersion;
/**
* Type of Number (TON) for ESME address(es) served via this SMPP receiver
* session. Set to NULL if not known.
*/
private int addrTon;
/**
* Numbering Plan Indicator (NPI) for ESME address(es) served via this SMPP
* receiver session. Set to NULL if not known.
*/
private int addrNpi;
/**
* A single ESME address or a range of ESME addresses served via this SMPP
* receiver session. The parameter value is represented in UNIX regular
* expression format (see Appendix A). Set to NULL if not known.
*/
private String addressRange;
public BindReceiver() {
super(CommandId.BIND_RECEIVER);
}
BindReceiver(ByteBuffer bb) throws PduException {
super(bb);
try {
systemId = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("System id parsing failed.", e);
}
try {
password = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Password parsing failed.", e);
}
try {
systemType= bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("System type parsing failed.", e);
}
interfaceVersion = bb.removeByte();
addrTon = bb.removeByte();
addrNpi = bb.removeByte();
try {
addressRange = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Address range parsing failed.", e);
}
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendCString(systemId);
bb.appendCString(password);
bb.appendCString(systemType);
bb.appendByte(interfaceVersion);
bb.appendByte(addrTon);
bb.appendByte(addrNpi);
bb.appendCString(addressRange);
return bb;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSystemType() {
return systemType;
}
public void setSystemType(String systemType) {
this.systemType = systemType;
}
public int getInterfaceVersion() {
return interfaceVersion;
}
public void setInterfaceVersion(int interfaceVersion) {
this.interfaceVersion = interfaceVersion;
}
public int getAddrTon() {
return addrTon;
}
public void setAddrTon(int addrTon) {
this.addrTon = addrTon;
}
public int getAddrNpi() {
return addrNpi;
}
public void setAddrNpi(int addrNpi) {
this.addrNpi = addrNpi;
}
public String getAddressRange() {
return addressRange;
}
public void setAddressRange(String addressRange) {
this.addressRange = addressRange;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* DeliverSm response PDU.
*
* @author Bulat Nigmatullin
*/
public class DeliverSmResp extends AbstractPdu {
public DeliverSmResp() {
super(CommandId.DELIVER_SM_RESP);
}
DeliverSmResp(ByteBuffer bb) throws PduException {
super(bb);
try {
bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Message id parsing failed.", e);
}
}
@Override
protected ByteBuffer body() {
return new ByteBuffer().appendByte(0);
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
/**
* Unbind Response PDU.
*
* @author Bulat Nigmatullin
*/
public class UnbindResp extends AbstractPdu {
public UnbindResp() {
super(CommandId.UNBIND_RESP);
}
UnbindResp(ByteBuffer bb) throws PduException {
super(bb);
}
@Override
protected ByteBuffer body() {
return null;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.Pdu;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.pdu.tlv.Tlv;
import org.bulatnig.smpp.pdu.tlv.TlvException;
import org.bulatnig.smpp.util.ByteBuffer;
import java.util.Map;
/**
* PDU header.
*
* @author Bulat Nigmatullin
*/
public abstract class AbstractPdu implements Pdu {
// lazy init tlv map
public Map<Integer, Tlv> tlvs;
private final long commandId;
private long commandStatus;
private long sequenceNumber;
/**
* Construct new PDU.
*
* @param commandId PDU command identificator
*/
protected AbstractPdu(long commandId) {
this.commandId = commandId;
this.commandStatus = 0;
this.sequenceNumber = 0;
}
/**
* Parse PDU from bytes.
*
* @param bb pdu bytes
*/
protected AbstractPdu(ByteBuffer bb) {
bb.removeInt(); // PDU length value not stored
commandId = bb.removeInt();
commandStatus = bb.removeInt();
sequenceNumber = bb.removeInt();
}
/**
* Calculate and return PDU body bytes.
*
* @return body bytes, can be null
*/
protected abstract ByteBuffer body();
/**
* Calculate and return PDU bytes.
*
* @return pdu bytes
* @throws PduException pdu contains wrong values
*/
@Override
public ByteBuffer buffer() throws PduException {
long length = HEADER_LENGTH;
ByteBuffer body = body();
if (body != null)
length += body.length();
ByteBuffer tlv = tlv();
if (tlv != null)
length += tlv.length();
ByteBuffer bb = new ByteBuffer();
bb.appendInt(length);
bb.appendInt(commandId);
bb.appendInt(commandStatus);
bb.appendInt(sequenceNumber);
if (body != null)
bb.appendBytes(body.array());
if (tlv != null)
bb.appendBytes(tlv.array());
return bb;
}
private ByteBuffer tlv() throws PduException {
if (tlvs != null) {
ByteBuffer result = new ByteBuffer();
for (Tlv tlv : tlvs.values()) {
try {
result.appendBytes(tlv.buffer().array());
} catch (TlvException e) {
throw new PduException("Tlv to bytes parsing error.", e);
}
}
return result;
} else
return null;
}
@Override
public long getCommandId() {
return commandId;
}
@Override
public long getCommandStatus() {
return commandStatus;
}
@Override
public long getSequenceNumber() {
return sequenceNumber;
}
@Override
public void setCommandStatus(long commandStatus) {
this.commandStatus = commandStatus;
}
@Override
public void setSequenceNumber(long sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* BindReceiver response PDU.
*
* @author Bulat Nigmatullin
*/
public class BindReceiverResp extends AbstractPdu {
/**
* SMSC identifier. Identifies the SMSC to the ESME.
*/
private String systemId;
public BindReceiverResp() {
super(CommandId.BIND_RECEIVER_RESP);
}
BindReceiverResp(ByteBuffer bb) throws PduException {
super(bb);
try {
systemId = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("System id parsing failed.", e);
}
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendCString(systemId);
return bb;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
} | Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* This operation is used by an ESME to submit a short message to the SMSC for
* onward transmission to a specified short message entity (SME). The submit_sm
* PDU does not support the transaction message mode.
*
* @author Bulat Nigmatullin
*/
public class SubmitSm extends AbstractPdu {
/**
* The service_type parameter can be used to indicate the SMS Application
* service associated with the message. Specifying the service_type allows
* the ESME to • avail of enhanced messaging services such as “replace by
* service” type • to control the teleservice used on the air interface. Set
* to NULL for default SMSC settings.
*/
private String serviceType;
/**
* Type of Number for source address. If not known, set to NULL (Unknown).
*/
private int sourceAddrTon;
/**
* Numbering Plan Indicator for source address. If not known, set to NULL
* (Unknown).
*/
private int sourceAddrNpi;
/**
* Address of SME which originated this message. If not known, set to NULL
* (Unknown).
*/
private String sourceAddr;
/**
* Type of Number for destination.
*/
private int destAddrTon;
/**
* Numbering Plan Indicator for destination.
*/
private int destAddrNpi;
/**
* Destination address of this short message. For mobile terminated
* messages, this is the directory number of the recipient MS.
*/
private String destinationAddr;
/**
* Indicates Message Mode & Message Type.
*/
private int esmClass;
/**
* Protocol Identifier. Network specific field.
*/
private int protocolId;
/**
* Designates the priority level of the message.
*/
private int priorityFlag;
/**
* The short message is to be scheduled by the SMSC for delivery. Set to
* NULL for immediate message delivery.
*/
private String scheduleDeliveryTime;
/**
* The validity period of this message. Set to NULL to request the SMSC
* default validity period.
*/
private String validityPeriod;
/**
* Indicator to signify if an SMSC delivery receipt or an SME
* acknowledgement is required.
*/
private int registeredDelivery;
/**
* Flag indicating if submitted message should replace an existing message.
*/
private int replaceIfPresentFlag;
/**
* Defines the encoding scheme of the short message user data.
*/
private int dataCoding;
/**
* Indicates the short message to send from a list of predefined (‘canned’)
* short messages stored on the SMSC. If not using an SMSC canned message,
* set to NULL.
*/
private int smDefaultMsgId;
/**
* Up to 254 octets of short message user data. The exact physical limit for
* short_message size may vary according to the underlying network.<br/>
* <p/>
* Applications which need to send messages longer than 254 octets should
* use the message_payload parameter. In this case the sm_length field
* should be set to zero.<br/>
* <p/>
* Note: The short message data should be inserted in either the
* short_message or message_payload fields. Both fields must not be used
* simultaneously.
*/
private byte[] shortMessage;
public SubmitSm() {
super(CommandId.SUBMIT_SM);
}
SubmitSm(ByteBuffer bb) throws PduException {
super(bb);
try {
serviceType = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Service type parsing failed.", e);
}
sourceAddrTon = bb.removeByte();
sourceAddrNpi = bb.removeByte();
try {
sourceAddr = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Service type parsing failed.", e);
}
destAddrTon = bb.removeByte();
destAddrNpi = bb.removeByte();
try {
destinationAddr = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Service type parsing failed.", e);
}
esmClass = bb.removeByte();
protocolId = bb.removeByte();
priorityFlag = bb.removeByte();
try {
scheduleDeliveryTime = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Service type parsing failed.", e);
}
try {
validityPeriod = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Service type parsing failed.", e);
}
registeredDelivery = bb.removeByte();
replaceIfPresentFlag = bb.removeByte();
dataCoding = bb.removeByte();
smDefaultMsgId = bb.removeByte();
int shortMessageLength = bb.removeByte();
shortMessage = bb.removeBytes(shortMessageLength);
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendCString(serviceType);
bb.appendByte(sourceAddrTon);
bb.appendByte(sourceAddrNpi);
bb.appendCString(sourceAddr);
bb.appendByte(destAddrTon);
bb.appendByte(destAddrNpi);
bb.appendCString(destinationAddr);
bb.appendByte(esmClass);
bb.appendByte(protocolId);
bb.appendByte(priorityFlag);
bb.appendCString(scheduleDeliveryTime);
bb.appendCString(validityPeriod);
bb.appendByte(registeredDelivery);
bb.appendByte(replaceIfPresentFlag);
bb.appendByte(dataCoding);
bb.appendByte(smDefaultMsgId);
if (shortMessage != null) {
bb.appendByte(shortMessage.length);
bb.appendBytes(shortMessage);
} else {
bb.appendByte(0);
}
return bb;
}
public String getServiceType() {
return serviceType;
}
public void setServiceType(String serviceType) {
this.serviceType = serviceType;
}
public int getSourceAddrTon() {
return sourceAddrTon;
}
public void setSourceAddrTon(int sourceAddrTon) {
this.sourceAddrTon = sourceAddrTon;
}
public int getSourceAddrNpi() {
return sourceAddrNpi;
}
public void setSourceAddrNpi(int sourceAddrNpi) {
this.sourceAddrNpi = sourceAddrNpi;
}
public String getSourceAddr() {
return sourceAddr;
}
public void setSourceAddr(String sourceAddr) {
this.sourceAddr = sourceAddr;
}
public int getDestAddrTon() {
return destAddrTon;
}
public void setDestAddrTon(int destAddrTon) {
this.destAddrTon = destAddrTon;
}
public int getDestAddrNpi() {
return destAddrNpi;
}
public void setDestAddrNpi(int destAddrNpi) {
this.destAddrNpi = destAddrNpi;
}
public String getDestinationAddr() {
return destinationAddr;
}
public void setDestinationAddr(String destinationAddr) {
this.destinationAddr = destinationAddr;
}
public int getEsmClass() {
return esmClass;
}
public void setEsmClass(int esmClass) {
this.esmClass = esmClass;
}
public int getProtocolId() {
return protocolId;
}
public void setProtocolId(int protocolId) {
this.protocolId = protocolId;
}
public int getPriorityFlag() {
return priorityFlag;
}
public void setPriorityFlag(int priorityFlag) {
this.priorityFlag = priorityFlag;
}
public String getScheduleDeliveryTime() {
return scheduleDeliveryTime;
}
public void setScheduleDeliveryTime(String scheduleDeliveryTime) {
this.scheduleDeliveryTime = scheduleDeliveryTime;
}
public String getValidityPeriod() {
return validityPeriod;
}
public void setValidityPeriod(String validityPeriod) {
this.validityPeriod = validityPeriod;
}
public int getRegisteredDelivery() {
return registeredDelivery;
}
public void setRegisteredDelivery(int registeredDelivery) {
this.registeredDelivery = registeredDelivery;
}
public int getReplaceIfPresentFlag() {
return replaceIfPresentFlag;
}
public void setReplaceIfPresentFlag(int replaceIfPresentFlag) {
this.replaceIfPresentFlag = replaceIfPresentFlag;
}
public int getDataCoding() {
return dataCoding;
}
public void setDataCoding(int dataCoding) {
this.dataCoding = dataCoding;
}
public int getSmDefaultMsgId() {
return smDefaultMsgId;
}
public void setSmDefaultMsgId(int smDefaultMsgId) {
this.smDefaultMsgId = smDefaultMsgId;
}
public byte[] getShortMessage() {
return shortMessage;
}
public void setShortMessage(byte[] shortMessage) {
this.shortMessage = shortMessage;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* BindTransmitter response PDU.
*
* @author Bulat Nigmatullin
*/
public class BindTransmitterResp extends AbstractPdu {
/**
* SMSC identifier. Identifies the SMSC to the ESME.
*/
private String systemId;
public BindTransmitterResp() {
super(CommandId.BIND_TRANSMITTER_RESP);
}
BindTransmitterResp(ByteBuffer bb) throws PduException {
super(bb);
try {
systemId = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("System id parsing failed.", e);
}
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendCString(systemId);
return bb;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
} | Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* QuerySM response PDU.
*
* @author Bulat Nigmatullin
*/
public class QuerySmResp extends AbstractPdu {
/**
* SMSC Message ID of the message whose state is being queried.
*/
private String messageId;
/**
* Date and time when the queried message reached a final state. For
* messages which have not yet reached a final state this field will contain
* a single NULL octet.
*/
private String finalDate;
/**
* Specifies the status of the queried short message.
*/
private int messageState;
/**
* Where appropriate this holds a network error code defining the reason for
* failure of message delivery.
*/
private int errorCode;
public QuerySmResp() {
super(CommandId.QUERY_SM_RESP);
}
protected QuerySmResp(ByteBuffer bb) throws PduException {
super(bb);
try {
messageId = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Message id parsing failed.", e);
}
try {
finalDate = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Final date parsing failed.", e);
}
messageState = bb.removeByte();
errorCode = bb.removeByte();
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendCString(messageId);
bb.appendCString(finalDate);
bb.appendByte(messageState);
bb.appendByte(errorCode);
return bb;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public String getFinalDate() {
return finalDate;
}
public void setFinalDate(String finalDate) {
this.finalDate = finalDate;
}
public int getMessageState() {
return messageState;
}
public void setMessageState(int messageState) {
this.messageState = messageState;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
}
| Java |
package org.bulatnig.smpp.pdu.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.util.ByteBuffer;
import org.bulatnig.smpp.util.TerminatingNullNotFoundException;
/**
* An ESME bound as a Transceiver is allowed to send messages to the SMSC and
* receive messages from the SMSC over a single SMPP session.
*
* @author Bulat Nigmatullin
*/
public class BindTransceiver extends AbstractPdu {
/**
* Identifies the ESME system requesting to bind as a receiver with the
* SMSC.
*/
private String systemId;
/**
* The password may be used by the SMSC for security reasons to authenticate
* the ESME requesting to bind.
*/
private String password;
/**
* Identifies the type of ESME system requesting to bind as a receiver with
* the SMSC.
*/
private String systemType;
/**
* Identifies the version of the SMPP protocol supported by the ESME.
*/
private int interfaceVersion;
/**
* Type of Number (TON) for ESME address(es) served via this SMPP receiver
* session. Set to NULL if not known.
*/
private int addrTon;
/**
* Numbering Plan Indicator (NPI) for ESME address(es) served via this SMPP
* receiver session. Set to NULL if not known.
*/
private int addrNpi;
/**
* A single ESME address or a range of ESME addresses served via this SMPP
* receiver session. The parameter value is represented in UNIX regular
* expression format (see Appendix A). Set to NULL if not known.
*/
private String addressRange;
public BindTransceiver() {
super(CommandId.BIND_TRANSCEIVER);
}
BindTransceiver(ByteBuffer bb) throws PduException {
super(bb);
try {
systemId = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("System id parsing failed.", e);
}
try {
password = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Password parsing failed.", e);
}
try {
systemType= bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("System type parsing failed.", e);
}
interfaceVersion = bb.removeByte();
addrTon = bb.removeByte();
addrNpi = bb.removeByte();
try {
addressRange = bb.removeCString();
} catch (TerminatingNullNotFoundException e) {
throw new PduException("Address range parsing failed.", e);
}
}
@Override
protected ByteBuffer body() {
ByteBuffer bb = new ByteBuffer();
bb.appendCString(systemId);
bb.appendCString(password);
bb.appendCString(systemType);
bb.appendByte(interfaceVersion);
bb.appendByte(addrTon);
bb.appendByte(addrNpi);
bb.appendCString(addressRange);
return bb;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSystemType() {
return systemType;
}
public void setSystemType(String systemType) {
this.systemType = systemType;
}
public int getInterfaceVersion() {
return interfaceVersion;
}
public void setInterfaceVersion(int interfaceVersion) {
this.interfaceVersion = interfaceVersion;
}
public int getAddrTon() {
return addrTon;
}
public void setAddrTon(int addrTon) {
this.addrTon = addrTon;
}
public int getAddrNpi() {
return addrNpi;
}
public void setAddrNpi(int addrNpi) {
this.addrNpi = addrNpi;
}
public String getAddressRange() {
return addressRange;
}
public void setAddressRange(String addressRange) {
this.addressRange = addressRange;
}
}
| Java |
package org.bulatnig.smpp.pdu;
/**
* Numbric Plan Indicator (NPI).
*
* @author Bulat Nigmatullin
*/
public enum Npi {
INSTANCE;
/**
* Unknown.
*/
public static final int UNKNOWN = 0;
/**
* ISDN (E163/E164).
*/
public static final int ISDN = 1;
/**
* Data (X.121).
*/
public static final int DATA = 3;
/**
* Telex (F.69).
*/
public static final int TELEX = 4;
/**
* Land Mobile (E.212).
*/
public static final int LAND_MOBILE = 6;
/**
* National.
*/
public static final int NATIONAL = 8;
/**
* Private.
*/
public static final int PRIVATE = 9;
/**
* ERMES
*/
public static final int ERMES = 10;
/**
* Internet (IP).
*/
public static final int INTERNET = 14;
/**
* WAP Client Id (to be defined by WAP Forum).
*/
public static final int WAP_CLIENT_ID = 18;
}
| Java |
package org.bulatnig.smpp.pdu.tlv;
/**
* Standard TLV's Parameter Tags.
*
* @author Bulat Nigmatullin
*/
public enum ParameterTag {
INSTANCE;
/**
* The dest_addr_subunit parameter is used to route messages when received
* by a mobile station, for example to a smart card in the mobile station or
* to an external device connected to the mobile station.
*/
public static final int DEST_ADDR_SUBUNIT = 0x0005;
/**
* The dest_network_type parameter is used to indicate a network type
* associated with the destination address of a message. In the case that
* the receiving system (e.g. SMSC) does not support the indicated network
* type, it may treat this a failure and return a response PDU reporting a
* failure.
*/
public static final int DEST_NETWORK_TYPE = 0x0006;
/**
* The dest_bearer_type parameter is used to request the desired bearer for
* delivery of the message to the destination address. In the case that the
* receiving system (e.g. SMSC) does not support the indicated bearer type,
* it may treat this a failure and return a response PDU reporting a
* failure.
*/
public static final int DEST_BEARER_TYPE = 0x0007;
/**
* This parameter defines the telematic interworking to be used by the
* delivering system for the destination address. This is only useful when a
* specific dest_bearer_type parameter has also been specified as the value
* is bearer dependent. In the case that the receiving system (e.g. SMSC)
* does not support the indicated telematic interworking, it may treat this
* a failure and return a response PDU reporting a failure.
*/
public static final int DEST_TELEMATICS_ID = 0x0008;
/**
* The source_addr_subunit parameter is used to indicate where a message
* originated in the mobile station, for example a smart card in the mobile
* station or an external device connected to the mobile station.
*/
public static final int SOURCE_ADDR_SUBUNIT = 0x000D;
/**
* The source_network_type parameter is used to indicate the network type
* associated with the device that originated the message.
*/
public static final int SOURCE_NETWORK_TYPE = 0x000E;
/**
* The source_bearer_type parameter indicates the wireless bearer over which
* the message originated.
*/
public static final int SOURCE_BEARER_TYPE = 0x000F;
/**
* The source_telematics_id parameter indicates the type of telematics
* interface over which the message originated.
*/
public static final int SOURCE_TELEMATICS_ID = 0x0010;
/**
* This parameter defines the number of seconds which the sender requests
* the SMSC to keep the message if undelivered before it is deemed expired
* and not worth delivering. If the parameter is not present, the SMSC may
* apply a default value.
*/
public static final int QOS_TIME_TO_LIVE = 0x0017;
/**
* The payload_type parameter defines the higher layer PDU type contained in
* the message payload.
*/
public static final int PAYLOAD_TYPE = 0x0019;
/**
* The payload_type parameter defines the higher layer PDU type contained in
* the message payload.
*/
public static final int ADDITIONAL_STATUS_INFO_TEXT = 0x001D;
/**
* The receipted_message_id parameter indicates the ID of the message being
* receipted in an SMSC Delivery Receipt. This is the opaque SMSC message
* identifier that was returned in the message_id parameter of the SMPP
* response PDU that acknowledged the submission of the original message.
*/
public static final int RECEIPTED_MESSAGE_ID = 0x001E;
/**
* The ms_msg_wait_facilities parameter allows an indication to be provided
* to an MS that there are messages waiting for the subscriber on systems on
* the PLMN. The indication can be an icon on the MS screen or other MMI
* indication.<br/>
*
* The ms_msg_wait_facilities can also specify the type of message
* associated with the message waiting indication.
*/
public static final int MS_MSG_WAIT_FACILITIES = 0x0030;
/**
* The privacy_indicator indicates the privacy level of the message.
*/
public static final int PRIVACY_INDICATOR = 0x0201;
/**
* The source_subaddress parameter specifies a subaddress associated with
* the originator of the message.
*/
public static final int SOURCE_SUBADDRESS = 0x0202;
/**
* The dest_subaddress parameter specifies a subaddress associated with the
* destination of the message.
*/
public static final int DEST_SUBADDRESS = 0x0203;
/**
* A reference assigned by the originating SME to the short message.
*/
public static final int USER_MESSAGE_REFERENCE = 0x0204;
/**
* A response code set by the user in a User Acknowledgement/Reply message.
* The response codes are application specific.
*/
public static final int USER_RESPONSE_CODE = 0x0205;
/**
* The source_port parameter is used to indicate the application port number
* associated with the source address of the message.
*/
public static final int SOURCE_PORT = 0x020A;
/**
* The destination_port parameter is used to indicate the application port
* number associated with the destination address of the message.
*/
public static final int DESTINATION_PORT = 0x020B;
/**
* The sar_msg_ref_num parameter is used to indicate the reference number
* for a particular concatenated short message.
*/
public static final int SAR_MSG_REF_NUM = 0x020C;
/**
* The language_indicator parameter is used to indicate the language of the
* short message.
*/
public static final int LANGUAGE_INDICATOR = 0x020D;
/**
* The sar_total_segments parameter is used to indicate the total number of
* short messages within the concatenated short message.
*/
public static final int SAR_TOTAL_SEGMENTS = 0x020E;
/**
* The sar_segment_seqnum parameter is used to indicate the sequence number
* of a particular short message within the concatenated short message.
*/
public static final int SAR_SEGMENT_SEQNUM = 0x020F;
/**
* The sc_interface_version parameter is used to indicate the SMPP version
* supported by the SMSC. It is returned in the bind response PDUs.
*/
public static final int SC_INTERFACE_VERSION = 0x0210;
/**
* callback_num_pres_ind.
*/
public static final int CALLBACK_NUM_PRES_IND = 0x0302;
/**
* The callback_num_atag parameter associates an alphanumeric display with
* the call back number.
*/
public static final int CALLBACK_NUM_ATAG = 0x0303;
/**
* The number_of_messages parameter is used to indicate the number of
* messages stored in a mailbox.
*/
public static final int NUMBER_OF_MESSAGES = 0x0304;
/**
* The callback_num parameter associates a call back number with the
* message. In TDMA networks, it is possible to send and receive multiple
* callback numbers to/from TDMA mobile stations.
*/
public static final int CALLBACK_NUM = 0x0381;
/**
* The dpf_result parameter is used in the data_sm_resp PDU to indicate if
* delivery pending flag (DPF) was set for a delivery failure of the short
* message..<br/>
*
* If the dpf_result parameter is not included in the data_sm_resp PDU, the
* ESME should assume that DPF is not set.<br/>
*
* Currently this parameter is only applicable for the Transaction message
* mode.
*/
public static final int DPF_RESULT = 0x0420;
/**
* An ESME may use the set_dpf parameter to request the setting of a
* delivery pending flag (DPF) for certain delivery failure scenarios, such
* as<br/> - MS is unavailable for message delivery (as indicated by the
* HLR)<br/>
*
* The SMSC should respond to such a request with an alert_notification PDU
* when it detects that the destination MS has become available.<br/>
*
* The delivery failure scenarios under which DPF is set is SMSC
* implementation and network implementation specific. If a delivery pending
* flag is set by the SMSC or network (e.g. HLR), then the SMSC should
* indicate this to the ESME in the data_sm_resp message via the dpf_result
* parameter.
*/
public static final int SET_DPF = 0x0421;
/**
* The ms_availability_status parameter is used in the alert_notification
* operation to indicate the availability state of the MS to the ESME.<br/>
*
* If the SMSC does not include the parameter in the alert_notification
* operation, the ESME should assume that the MS is in an “available” state.
*/
public static final int MS_AVAILABILITY_STATUS = 0x0422;
/**
* The network_error_code parameter is used to indicate the actual network
* error code for a delivery failure. The network error code is technology
* specific.
*/
public static final int NETWORK_ERROR_CODE = 0x0423;
/**
* The message_payload parameter contains the user data.
*/
public static final int MESSAGE_PAYLOAD = 0x0424;
/**
* The delivery_failure_reason parameter is used in the data_sm_resp
* operation to indicate the outcome of the message delivery attempt (only
* applicable for transaction message mode). If a delivery failure due to a
* network error is indicated, the ESME may check the network_error_code
* parameter (if present) for the actual network error code.<br/>
*
* The delivery_failure_reason parameter is not included if the delivery
* attempt was successful.
*/
public static final int DELIVERY_FAILURE_REASON = 0x0425;
/**
* The more_messages_to_send parameter is used by the ESME in the submit_sm
* and data_sm operations to indicate to the SMSC that there are further
* messages for the same destination SME. The SMSC may use this setting for
* network resource optimization.
*/
public static final int MORE_MESSAGES_TO_SEND = 0x0426;
/**
* The message_state optional parameter is used by the SMSC in the
* deliver_sm and data_sm PDUs to indicate to the ESME the final message
* state for an SMSC Delivery Receipt.
*/
public static final int MESSAGE_STATE = 0x0427;
/**
* The ussd_service_op parameter is required to define the USSD service
* operation when SMPP is being used as an interface to a (GSM) USSD system.
*/
public static final int USSD_SERVICE_OP = 0x0501;
/**
* The display_time parameter is used to associate a display time of the
* short message on the MS.
*/
public static final int DISPLAY_TIME = 0x1201;
/**
* The sms_signal parameter is used to provide a TDMA MS with alert tone
* information associated with the received short message.
*/
public static final int SMS_SIGNAL = 0x1203;
/**
* The ms_validity parameter is used to provide an MS with validity
* information associated with the received short message.
*/
public static final int MS_VALIDITY = 0x1204;
/**
* The alert_on_message_delivery parameter is set to instruct a MS to alert
* the user (in a MS implementation specific manner) when the short message
* arrives at the MS.
*/
public static final int ALERT_ON_MESSAGE_DELIVERY = 0x130C;
/**
* The its_reply_type parameter is a required parameter for the CDMA
* Interactive Teleservice as defined by the Korean PCS carriers [KORITS].
* It indicates and controls the MS user’s reply method to an SMS delivery
* message received from the ESME.
*/
public static final int ITS_REPLY_TYPE = 0x1380;
/**
* The its_session_info parameter is a required parameter for the CDMA
* Interactive Teleservice as defined by the Korean PCS carriers [KORITS].
* It contains control information for the interactive session between an MS
* and an ESME.
*/
public static final int ITS_SESSION_INFO = 0x1383;
}
| Java |
package org.bulatnig.smpp.pdu.tlv;
import org.bulatnig.smpp.util.ByteBuffer;
/**
* Optional Parameters are fields, which may be present in a message. Optional
* Parameters provide a mechanism for the future introduction of new parameters,
* as and when defined in future versions of the SMPP protocol.<br/>
* <p/>
* Optional Parameters must always appear at the end of a PDU , in the "Optional
* Parameters" section of the SMPP PDU. However, they may be included in any
* convenient order within the "Optional Parameters" section of the SMPP PDU and
* need not be encoded in the order presented in this document.<br/>
* <p/>
* For a particular SMPP PDU, the ESME or SMSC may include some, all or none of
* the defined optional parameters as required for the particular application
* context. For example a paging system may only need to include the “callback
* number” related optional parameters in a submit_sm operation.
*
* @author Bulat Nigmatullin
*/
public interface Tlv {
/**
* Header length in bytes.
*/
public static final int HEADER_LENGTH = 4;
/**
* Calculate and return TLV bytes.
*
* @return tlv bytes
* @throws TlvException TLV contains wrong values
*/
public ByteBuffer buffer() throws TlvException;
/**
* The Tag field is used to uniquely identify the particular optional
* parameter in question.<br>
* <p/>
* The optional parameter Tag field is always 2 octets in length.
*
* @return tag id
*/
public int getTag();
/**
* Return TLV value bytes.
*
* @return value bytes
*/
public byte[] getValue();
/**
* Set TLV value in bytes.
*
* @param valueBytes value bytes
*/
public void setValue(byte[] valueBytes);
}
| Java |
package org.bulatnig.smpp.pdu.tlv;
import org.bulatnig.smpp.util.ByteBuffer;
import java.util.Map;
/**
* TLV parser.
*
* @author Bulat Nigmatullin
*/
public interface TlvParser {
/**
* Parse TLV's from bytes.
*
* @param bb byte buffer
* @return map parameter tag to tlv, may be null
* @throws TlvException tlv parsing error
*/
Map<Integer, Tlv> parse(ByteBuffer bb) throws TlvException;
}
| Java |
package org.bulatnig.smpp.pdu.tlv.impl;
import org.bulatnig.smpp.pdu.tlv.Tlv;
import org.bulatnig.smpp.pdu.tlv.TlvException;
import org.bulatnig.smpp.util.ByteBuffer;
/**
* General TLV implementation.
*
* @author Bulat Nigmatullin
*/
public class TlvImpl implements Tlv {
private final int tag;
private byte[] value;
public TlvImpl(int tag) {
this.tag = tag;
}
@Override
public ByteBuffer buffer() throws TlvException {
ByteBuffer bb = new ByteBuffer();
bb.appendShort(tag);
int length = value != null ? value.length : 0;
bb.appendShort(length);
if (length > 0)
bb.appendBytes(value);
return bb;
}
@Override
public int getTag() {
return tag;
}
@Override
public byte[] getValue() {
return value;
}
@Override
public void setValue(byte[] valueBytes) {
this.value = valueBytes;
}
}
| Java |
package org.bulatnig.smpp.pdu.tlv.impl;
import org.bulatnig.smpp.pdu.tlv.Tlv;
import org.bulatnig.smpp.pdu.tlv.TlvException;
import org.bulatnig.smpp.pdu.tlv.TlvParser;
import org.bulatnig.smpp.pdu.tlv.impl.TlvImpl;
import org.bulatnig.smpp.util.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
/**
* Default TLV parser implementation.
*
* @author Bulat Nigmatullin
*/
public class DefaultTlvParser implements TlvParser {
@Override
public Map<Integer, Tlv> parse(ByteBuffer bb) throws TlvException {
final byte[] original = bb.array();
Map<Integer, Tlv> tlvs = null;
if (bb.length() >= 4)
tlvs = new HashMap<Integer, Tlv>();
try {
while (bb.length() > 0) {
int tag = bb.removeShort();
int length = bb.removeShort();
byte[] value = bb.removeBytes(length);
Tlv tlv = new TlvImpl(tag);
tlv.setValue(value);
tlvs.put(tag, tlv);
}
} catch (IndexOutOfBoundsException e) {
throw new TlvException("Malformed TLV part: " + new ByteBuffer(original).hexDump() + ".", e);
}
return tlvs;
}
}
| Java |
package org.bulatnig.smpp.pdu.tlv;
import org.bulatnig.smpp.SmppException;
/**
* TLV parsing failed.
*
* @author Bulat Nigmatullin
*/
public class TlvException extends SmppException {
public TlvException() {
super();
}
public TlvException(String message) {
super(message);
}
public TlvException(String message, Throwable cause) {
super(message, cause);
}
public TlvException(Throwable cause) {
super(cause);
}
}
| Java |
package org.bulatnig.smpp.util;
import org.bulatnig.smpp.SmppException;
/**
* C-Octet Sring terminating null character not found.
*
* @author Bulat Nigmatullin
*/
public class TerminatingNullNotFoundException extends SmppException {
public TerminatingNullNotFoundException() {
super("C-Octet String terminating zero not found.");
}
}
| Java |
package org.bulatnig.smpp.util;
import java.io.UnsupportedEncodingException;
/**
* Converts java types to byte array according to SMPP protocol.
* You should remember, that all SMPP simple numeric types are unsigned,
* but Java types are always signed.
* <p/>
* Not thread safe.
*
* @author Bulat Nigmatullin
*/
public class ByteBuffer {
/**
* Empty byte array.
*/
private static final byte[] EMPTY = new byte[0];
/**
* SMPP NULL character to append at the end of C-Octet String.
*/
private static final byte[] ZERO = new byte[]{0};
/**
* Byte buffer.
*/
private byte[] buffer;
/**
* Create empty buffer.
*/
public ByteBuffer() {
buffer = EMPTY;
}
/**
* Create buffer based on provided array.
*
* @param b byte array
*/
public ByteBuffer(byte[] b) {
buffer = b;
}
/**
* Возвращает массив байтов.
*
* @return массив байтов
*/
public byte[] array() {
return buffer;
}
/**
* Возвращает длину массива.
*
* @return длина массива
*/
public int length() {
return buffer.length;
}
/**
* Добавляет байты в массив.
*
* @param bytes byte array
* @return this buffer
*/
public ByteBuffer appendBytes(byte[] bytes) {
return appendBytes(bytes, bytes.length);
}
/**
* Добавляет байты в массив.
*
* @param bytes byte array
* @param length bytes length to add
* @return this buffer
*/
public ByteBuffer appendBytes(byte[] bytes, int length) {
byte[] newBuffer = new byte[buffer.length + length];
System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
System.arraycopy(bytes, 0, newBuffer, buffer.length, length);
buffer = newBuffer;
return this;
}
/**
* Добавляет переменную типа byte в массив.
* Значение переменной должно быть в диапазоне от 0 до 255 включительно.
*
* @param value byte value to be appended
* @return this buffer
* @throws IllegalArgumentException задан неверный параметр
*/
public ByteBuffer appendByte(int value) throws IllegalArgumentException {
if (value >= 0 && value < 256)
appendBytes(new byte[]{(byte) value});
else
throw new IllegalArgumentException("Byte value should be between 0 and 255.");
return this;
}
/**
* Добавляет переменную типа short в массив.
* Значение переменной должно быть в диапазоне от 0 до 65535 включительно.
*
* @param value short value to be appended
* @return this buffer
* @throws IllegalArgumentException задан неверный параметр
*/
public ByteBuffer appendShort(int value) throws IllegalArgumentException {
if (value >= 0 && value < 65536)
appendBytes(new byte[]{(byte) (value >>> 8), (byte) value});
else
throw new IllegalArgumentException("Short value should be between 0 and 65535.");
return this;
}
/**
* Добавляет переменную типа int в массив.
* Значение переменной должно быть в диапазоне от 0 до 4294967295 включительно.
*
* @param value short-переменная
* @return this buffer
* @throws IllegalArgumentException задан неверный параметр
*/
public ByteBuffer appendInt(long value) throws IllegalArgumentException {
if (value >= 0 && value < 4294967296L)
appendBytes(new byte[]{(byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value});
else
throw new IllegalArgumentException("Short value should be between 0 and 4294967295.");
return this;
}
/**
* Добавляет строку C-Octet String в массив.
*
* @param cstring строка типа C-Octet (по протоколу SMPP), may be null
* @return this buffer
*/
public ByteBuffer appendCString(String cstring) {
if (cstring != null && cstring.length() > 0) {
try {
byte[] stringBuf = cstring.getBytes("US-ASCII");
appendBytes(stringBuf);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("US-ASCII charset is not supported. Consult developer.", e);
}
}
appendBytes(ZERO); // always append terminating ZERO
return this;
}
/**
* Append string using ASCII charset.
*
* @param string string value, may be null
* @return this buffer
*/
public ByteBuffer appendString(String string) {
return appendString(string, "US-ASCII");
}
/**
* Append string using charset name.
* Note: UTF-16(UCS2) uses Byte Order Mark at the head of string and
* it may be unsupported by your Operator. So you should consider using
* UTF-16BE or UTF-16LE instead of UTF-16.
*
* @param string encoded string, null allowed
* @param charsetName encoding character set name
* @return this buffer
* @throws IllegalArgumentException wrong charset name
*/
public ByteBuffer appendString(String string, String charsetName) {
if (string != null && string.length() > 0) {
try {
byte[] stringBuf = string.getBytes(charsetName);
appendBytes(stringBuf);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Wrong charset name provided.", e);
}
}
return this;
}
/**
* Read one byte from byte buffer
*
* @return byte was read
* @throws IndexOutOfBoundsException out of buffer
*/
public int readByte() {
return buffer[0] & 0xFF;
}
/**
* Read short value from buffer
*
* @return short value
* @throws IndexOutOfBoundsException out of buffer
*/
public int readShort() {
int result = 0;
result |= buffer[0] & 0xFF;
result <<= 8;
result |= buffer[1] & 0xFF;
return result;
}
/**
* Read int value from buffer
*
* @return int value
* @throws IndexOutOfBoundsException out of buffer
*/
public long readInt() {
return readInt(0);
}
/**
* Read int value from buffer
*
* @param offset start reading from offset byte
* @return int value
* @throws IndexOutOfBoundsException out of buffer
*/
public long readInt(int offset) {
long result = 0;
result |= buffer[offset] & 0xFF;
result <<= 8;
result |= buffer[offset + 1] & 0xFF;
result <<= 8;
result |= buffer[offset + 2] & 0xFF;
result <<= 8;
result |= buffer[offset + 3] & 0xFF;
return result;
}
/**
* Удаляет один byte из массива и возвращает его.
*
* @return удаленный byte
* @throws IndexOutOfBoundsException out of buffer
*/
public int removeByte() {
int result = readByte();
removeBytes0(1);
return result;
}
/**
* Удаляет один short из массива и возвращает его.
*
* @return удаленный short
* @throws IndexOutOfBoundsException out of buffer
*/
public int removeShort() {
int result = readShort();
removeBytes0(2);
return result;
}
/**
* Удаляет один int из массива и возвращает его.
*
* @return удаленные int
* @throws IndexOutOfBoundsException out of buffer
*/
public long removeInt() {
long result = readInt();
removeBytes0(4);
return result;
}
/**
* Удаляет строку C-Octet String из массива и возращает строку.
*
* @return C-Octet String, may be null
* @throws TerminatingNullNotFoundException
* null character not found in the buffer
*/
public String removeCString() throws TerminatingNullNotFoundException {
int zeroPos = -1;
for (int i = 0; i < buffer.length; i++) {
if (buffer[i] == 0) {
zeroPos = i;
break;
}
}
if (zeroPos == -1)
throw new TerminatingNullNotFoundException();
String result = null;
if (zeroPos > 0) {
try {
result = new String(buffer, 0, zeroPos, "US-ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("US-ASCII charset is not supported. Consult developer.", e);
}
}
removeBytes0(zeroPos + 1);
return result;
}
/**
* Remove Octet String from buffer and return it in ASCII encoding..
*
* @param length string length
* @return removed string
* @throws IndexOutOfBoundsException out of buffer
*/
public String removeString(int length) {
return removeString(length, "US-ASCII");
}
/**
* Remove Octet string from buffer and return it in charsetName encoding.
* <p/>
* Note: Even if string length is 0, zero-length String object created and returned.
* This behavior is differ from C-Octet String cause user know Octet String length
* and may not call this method if String length is 0 and he need null.
*
* @param length string length
* @param charsetName string charset name
* @return removed string
* @throws IndexOutOfBoundsException out of buffer
*/
public String removeString(int length, String charsetName) {
String result;
try {
result = new String(buffer, 0, length, charsetName);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Unsupported charset name: " + charsetName, e);
}
removeBytes0(length);
return result;
}
/**
* Remove bytes from buffer and return them.
*
* @param count count of bytes to remove
* @return removed bytes
* @throws IndexOutOfBoundsException out of buffer
*/
public byte[] removeBytes(int count) {
byte[] result = readBytes(count);
removeBytes0(count);
return result;
}
/**
* Возвращает строку отображающую содержимое массива.
*
* @return содержимое массива
*/
public String hexDump() {
StringBuilder builder = new StringBuilder();
for (byte b : buffer) {
builder.append(Character.forDigit((b >> 4) & 0x0f, 16));
builder.append(Character.forDigit(b & 0x0f, 16));
}
return builder.toString();
}
/**
* Just removes bytes from the buffer and doesnt return anything.
*
* @param count removed bytes
*/
private void removeBytes0(int count) {
int lefts = buffer.length - count;
if (lefts > 0) {
byte[] newBuf = new byte[lefts];
System.arraycopy(buffer, count, newBuf, 0, lefts);
buffer = newBuf;
} else {
buffer = EMPTY;
}
}
/**
* Read bytes.
*
* @param count count of bytes to read
* @return readed bytes
*/
private byte[] readBytes(int count) {
byte[] resBuf = new byte[count];
System.arraycopy(buffer, 0, resBuf, 0, count);
return resBuf;
}
}
| Java |
package org.bulatnig.smpp.session;
/**
* Session state.
*
* @author Bulat Nigmatullin
*/
public enum State {
CONNECTED,
DISCONNECTED,
RECONNECTING
}
| Java |
package org.bulatnig.smpp.session;
import org.bulatnig.smpp.pdu.Pdu;
import org.bulatnig.smpp.pdu.PduException;
import java.io.IOException;
/**
* Asynchronous session with SMSC.
* Supports connection by sending EnquireLink requests, session reuse (reconnect operations),
* automatically reconnects on IO failure after successful connect.
*
* @author Bulat Nigmatullin
*/
public interface Session {
/**
* Wait 30 seconds for response by default.
*/
static final int DEFAULT_SMSC_RESPONSE_TIMEOUT = 30000;
/**
* Send ENQUIRE_LINK requests every 30 seconds to check SMSC alive.
*/
static final int DEFAULT_ENQUIRE_LINK_TIMEOUT = 30000;
/**
* Try to reconnect every N ms.
*/
static final int DEFAULT_RECONNECT_TIMEOUT = 1000;
/**
* Set incoming messages from SMSC listener.
*
* @param messageListener incoming message listener
*/
void setMessageListener(MessageListener messageListener);
/**
* Set session state listener
*
* @param stateListener state listener
*/
void setStateListener(StateListener stateListener);
/**
* Set time in ms in which SMSC should response.
*
* @param timeout time in milliseconds
*/
void setSmscResponseTimeout(int timeout);
/**
* Session inactivity time in milliseconds after that ENQUIRE_LINK should be sent,
* to check SMSC availability.
*
* @param timeout time in milliseconds
*/
void setEnquireLinkTimeout(int timeout);
/**
* On IO failure try to reconnect to SMSC every timeout milliseconds.
*
* @param timeout time in milliseconds
*/
void setReconnectTimeout(int timeout);
/**
* Open session. Establish TCP connection and send provided bind PDU.
* Sequence number assigned automatically.
*
* @param pdu bind request
* @return bind response
* @throws PduException PDU parsing failed
* @throws IOException input-output exception
*/
Pdu open(Pdu pdu) throws PduException, IOException;
/**
* Unique PDU sequence number, used to track SMSC response.
* Application should first call this method, then set returned sequence number to PDU and
* send it.
*
* @return relatively unique PDU sequence number
*/
long nextSequenceNumber();
/**
* Send PDU to SMSC.
*
* @param pdu pdu to send
* @return send successful
* @throws PduException PDU parsing failed
*/
boolean send(Pdu pdu) throws PduException;
/**
* Send Unbind request, wait for UnbindResp, then close TCP connection and free all resources.
* Session may be reopened.
*/
void close();
}
| Java |
package org.bulatnig.smpp.session;
/**
* Track session connects and disconnects.
*
* @author Bulat Nigmatullin
*/
public interface StateListener {
/**
* Session state changed to new state.
*
* @param state new state
* @param e failure reason, may be null
*/
void changed(State state, Exception e);
}
| Java |
package org.bulatnig.smpp.session.impl;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.Pdu;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.session.Session;
import org.bulatnig.smpp.session.MessageListener;
import org.bulatnig.smpp.session.StateListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Session, limiting the number of outgoing requests per second.
*
* @author Bulat Nigmatullin
*/
public class LimitingSession implements Session {
private static final Logger logger = LoggerFactory.getLogger(LimitingSession.class);
/**
* Limit message count per this amount of time.
*/
private static final int TIMEOUT = 1010;
private final Session session;
/**
* Holds the times when the last messages was sent.
*/
private final BlockingQueue<Long> sentTimes;
public LimitingSession(Session session, int maxMessagesPerSecond) {
this.session = session;
sentTimes = new LinkedBlockingQueue<Long>(maxMessagesPerSecond);
for (int i = 0; i < maxMessagesPerSecond; i++)
sentTimes.add(0L);
}
@Override
public void setMessageListener(MessageListener messageListener) {
session.setMessageListener(messageListener);
}
@Override
public void setStateListener(StateListener stateListener) {
session.setStateListener(stateListener);
}
@Override
public void setSmscResponseTimeout(int timeout) {
session.setSmscResponseTimeout(timeout);
}
@Override
public void setEnquireLinkTimeout(int timeout) {
session.setEnquireLinkTimeout(timeout);
}
@Override
public void setReconnectTimeout(int timeout) {
session.setReconnectTimeout(timeout);
}
@Override
public Pdu open(Pdu pdu) throws PduException, IOException {
return session.open(pdu);
}
@Override
public long nextSequenceNumber() {
return session.nextSequenceNumber();
}
@Override
public boolean send(Pdu pdu) throws PduException {
if (CommandId.SUBMIT_SM != pdu.getCommandId()) {
return session.send(pdu);
} else {
try {
long timeToSleep = sentTimes.poll() + TIMEOUT - System.currentTimeMillis();
logger.trace("Wait before send: {} ms.", timeToSleep);
if (timeToSleep > 0) {
logger.trace("Going to sleep {} ms.", timeToSleep);
Thread.sleep(timeToSleep);
}
return session.send(pdu);
} catch (InterruptedException e) {
logger.warn("Send interrupted.", e);
return false;
} finally {
sentTimes.add(System.currentTimeMillis());
}
}
}
@Override
public void close() {
session.close();
}
}
| Java |
package org.bulatnig.smpp.session.impl;
import org.bulatnig.smpp.session.State;
import org.bulatnig.smpp.session.StateListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Session default state listener implementation. Just print new session state.
*
* @author Bulat Nigmatullin
*/
public class DefaultStateListener implements StateListener {
private static final Logger logger = LoggerFactory.getLogger(DefaultStateListener.class);
@Override
public void changed(State state, Exception e) {
logger.debug("Session state changed to {}.", state, e);
}
}
| Java |
package org.bulatnig.smpp.session.impl;
import org.bulatnig.smpp.pdu.Pdu;
import org.bulatnig.smpp.session.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Session default message listener implementation, just print received PDU's class names.
*
* @author Bulat Nigmatullin
*/
public class DefaultMessageListener implements MessageListener {
private static final Logger logger = LoggerFactory.getLogger(DefaultMessageListener.class);
@Override
public void received(Pdu pdu) {
logger.debug("{} received, but no session listener set.", pdu.getClass().getName());
}
}
| Java |
package org.bulatnig.smpp.session.impl;
import org.bulatnig.smpp.net.Connection;
import org.bulatnig.smpp.pdu.CommandId;
import org.bulatnig.smpp.pdu.CommandStatus;
import org.bulatnig.smpp.pdu.Pdu;
import org.bulatnig.smpp.pdu.PduException;
import org.bulatnig.smpp.pdu.impl.EnquireLink;
import org.bulatnig.smpp.pdu.impl.EnquireLinkResp;
import org.bulatnig.smpp.pdu.impl.Unbind;
import org.bulatnig.smpp.session.MessageListener;
import org.bulatnig.smpp.session.Session;
import org.bulatnig.smpp.session.State;
import org.bulatnig.smpp.session.StateListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Asynchronous session implementation.
*
* @author Bulat Nigmatullin
*/
public class BasicSession implements Session {
private static final Logger logger = LoggerFactory.getLogger(BasicSession.class);
private final Connection conn;
private int smscResponseTimeout = DEFAULT_SMSC_RESPONSE_TIMEOUT;
private int pingTimeout = DEFAULT_ENQUIRE_LINK_TIMEOUT;
private int reconnectTimeout = DEFAULT_RECONNECT_TIMEOUT;
private MessageListener messageListener = new DefaultMessageListener();
private StateListener stateListener = new DefaultStateListener();
private PingThread pingThread;
private ReadThread readThread;
private Pdu bindPdu;
private volatile long sequenceNumber = 0;
private volatile long lastActivity;
private volatile State state = State.DISCONNECTED;
public BasicSession(Connection conn) {
this.conn = conn;
}
@Override
public void setMessageListener(MessageListener messageListener) {
this.messageListener = messageListener;
}
@Override
public void setStateListener(StateListener stateListener) {
this.stateListener = stateListener;
}
@Override
public void setSmscResponseTimeout(int timeout) {
this.smscResponseTimeout = timeout;
}
@Override
public void setEnquireLinkTimeout(int timeout) {
this.pingTimeout = timeout;
}
@Override
public void setReconnectTimeout(int timeout) {
this.reconnectTimeout = timeout;
}
@Override
public synchronized Pdu open(Pdu pdu) throws PduException, IOException {
bindPdu = pdu;
return open();
}
@Override
public synchronized long nextSequenceNumber() {
if (sequenceNumber == 2147483647L)
sequenceNumber = 1;
else
sequenceNumber++;
return sequenceNumber;
}
@Override
public synchronized boolean send(Pdu pdu) throws PduException {
if (State.CONNECTED != state)
return false;
try {
conn.write(pdu);
return true;
} catch (IOException e) {
logger.debug("Send failed.", e);
reconnect(e);
return false;
}
}
@Override
public synchronized void close() {
if (State.RECONNECTING == state || closeInternal(null))
updateState(State.DISCONNECTED);
}
private synchronized Pdu open() throws PduException, IOException {
logger.trace("Opening new session...");
conn.open();
logger.trace("TCP connection established. Sending bind request.");
bindPdu.setSequenceNumber(nextSequenceNumber());
conn.write(bindPdu);
ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
es.schedule(new Runnable() {
@Override
public void run() {
logger.warn("Bind response timed out.");
conn.close();
}
}, smscResponseTimeout, TimeUnit.MILLISECONDS);
logger.trace("Bind request sent. Waiting for bind response.");
try {
Pdu bindResp = conn.read();
es.shutdownNow();
logger.trace("Bind response command status: {}.", bindResp.getCommandStatus());
if (CommandStatus.ESME_ROK == bindResp.getCommandStatus()) {
updateLastActivity();
pingThread = new PingThread();
pingThread.setName("Ping");
pingThread.start();
readThread = new ReadThread();
Thread t2 = new Thread(readThread);
t2.setName("Read");
t2.start();
updateState(State.CONNECTED);
logger.trace("Session successfully opened.");
}
return bindResp;
} finally {
if (!es.isShutdown())
es.shutdownNow();
}
}
/**
* Actually close session.
*
* @param reason exception, caused session close, or null
* @return session closed
*/
private synchronized boolean closeInternal(Exception reason) {
if (State.DISCONNECTED != state) {
logger.trace("Closing session...");
pingThread.stopAndInterrupt();
pingThread = null;
if (!(reason instanceof IOException) && readThread.run) {
try {
synchronized (conn) {
Pdu unbind = new Unbind();
unbind.setSequenceNumber(nextSequenceNumber());
send(unbind);
conn.wait(smscResponseTimeout);
}
} catch (Exception e) {
logger.debug("Unbind request send failed.", e);
}
}
readThread.stop();
readThread = null;
conn.close();
logger.trace("Session closed.");
return true;
} else {
logger.trace("Session already closed.");
return false;
}
}
private void reconnect(Exception reason) {
// only one thread should do reconnect
boolean doReconnect = false;
synchronized (state) {
if (State.RECONNECTING != state) {
doReconnect = true;
state = State.RECONNECTING;
}
}
if (doReconnect) {
closeInternal(reason);
new Thread(new ReconnectThread(reason)).start();
}
}
private void updateLastActivity() {
lastActivity = System.currentTimeMillis();
}
private void updateState(State newState) {
updateState(newState, null);
}
private void updateState(State newState, Exception e) {
this.state = newState;
stateListener.changed(newState, e);
}
private class PingThread extends Thread {
private volatile boolean run = true;
@Override
public void run() {
logger.trace("Ping thread started.");
try {
while (run) {
logger.trace("Checking last activity.");
try {
Thread.sleep(pingTimeout);
if (pingTimeout < (System.currentTimeMillis() - lastActivity)) {
long prevLastActivity = lastActivity;
Pdu enquireLink = new EnquireLink();
enquireLink.setSequenceNumber(nextSequenceNumber());
send(enquireLink);
synchronized (conn) {
conn.wait(smscResponseTimeout);
}
if (run && lastActivity == prevLastActivity) {
reconnect(new IOException("Enquire link response not received. Session closed."));
}
}
} catch (InterruptedException e) {
logger.trace("Ping thread interrupted.");
}
}
} catch (PduException e) {
if (run) {
logger.warn("EnquireLink request failed.", e);
run = false;
reconnect(e);
}
} finally {
logger.trace("Ping thread stopped.");
}
}
void stopAndInterrupt() {
run = false;
interrupt();
}
}
private class ReadThread implements Runnable {
private volatile boolean run = true;
@Override
public void run() {
logger.trace("Read thread started.");
try {
while (run) {
Pdu request = conn.read();
updateLastActivity();
Pdu response;
if (CommandId.ENQUIRE_LINK == request.getCommandId()) {
response = new EnquireLinkResp();
response.setSequenceNumber(request.getSequenceNumber());
send(response);
} else if (CommandId.ENQUIRE_LINK_RESP == request.getCommandId()) {
synchronized (conn) {
conn.notifyAll();
}
} else if (CommandId.UNBIND_RESP == request.getCommandId()) {
synchronized (conn) {
conn.notifyAll();
}
stop();
} else {
messageListener.received(request);
}
}
} catch (PduException e) {
if (run) {
logger.warn("Incoming message parsing failed.", e);
run = false;
reconnect(e);
}
} catch (IOException e) {
if (run) {
logger.warn("Reading IO failure.", e);
run = false;
reconnect(e);
}
} finally {
logger.trace("Read thread stopped.");
}
}
void stop() {
run = false;
}
}
private class ReconnectThread implements Runnable {
private final Exception reason;
private ReconnectThread(Exception reason) {
this.reason = reason;
}
@Override
public void run() {
logger.debug("Reconnect started.");
stateListener.changed(state, reason);
boolean reconnectSuccessful = false;
while (!reconnectSuccessful && state == State.RECONNECTING) {
logger.debug("Reconnecting...");
try {
Pdu bindResponse = open();
if (CommandStatus.ESME_ROK == bindResponse.getCommandStatus()) {
reconnectSuccessful = true;
} else {
logger.warn("Reconnect failed. Bind response error code: {}.",
bindResponse.getCommandStatus());
}
} catch (Exception e) {
logger.warn("Reconnect failed.", e);
try {
Thread.sleep(reconnectTimeout);
} catch (InterruptedException e1) {
logger.trace("Reconnect sleep interrupted.", e1);
}
}
}
if (reconnectSuccessful)
state = State.CONNECTED;
logger.debug("Reconnect done.");
}
}
}
| Java |
package org.bulatnig.smpp.session;
import org.bulatnig.smpp.pdu.Pdu;
/**
* Session incoming messages listener.
*
* @author Bulat Nigmatullin
*/
public interface MessageListener {
/**
* Process incoming PDU.
*
* @param pdu incoming PDU from SMSC
*/
void received(Pdu pdu);
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.