repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
popo1379/popomusic | app/src/main/java/com/popomusic/adapter/PicAdapter.java | // Path: app/src/main/java/com/popomusic/picBean/Contentlist.java
// public class Contentlist {
//
// @SerializedName("itemId")
// @Expose
// private String itemId;
// @SerializedName("list")
// @Expose
// private java.util.List<Picbean> list = null;
// @SerializedName("title")
// @Expose
// private String title;
// @SerializedName("type")
// @Expose
// private Integer type;
// @SerializedName("typeName")
// @Expose
// private String typeName;
//
//
// public String getItemId() {
// return itemId;
// }
//
// public void setItemId(String itemId) {
// this.itemId = itemId;
// }
//
// public java.util.List<Picbean> getList() {
// return list;
// }
//
// public void setList(java.util.List<Picbean> list) {
// this.list = list;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public Integer getType() {
// return type;
// }
//
// public void setType(Integer type) {
// this.type = type;
// }
//
// public String getTypeName() {
// return typeName;
// }
//
// public void setTypeName(String typeName) {
// this.typeName = typeName;
// }
//
// }
//
// Path: app/src/main/java/com/popomusic/util/UIcollector.java
// @SuppressWarnings("ALL")
// public class UIcollector {
//
//
// public static Context getContext() {
// return BaseActivity.getContext();
// }
//
// public static Activity getActivity() {
// return BaseActivity.getActivity();
// }
//
//
// public static Drawable getDrawable(int id) {
// return getContext().getResources().getDrawable(id);
// }
//
// public static int getColor(int id) {
// return getContext().getResources().getColor(id);
// }
//
// public static String getString(int id) {
// return getContext().getResources().getString(id);
// }
//
//
// public static String[] getStringArray(int id) {
// return getContext().getResources().getStringArray(id);
// }
// }
//
// Path: app/src/main/java/com/popomusic/videoModel/ItemList.java
// public class ItemList implements Parcelable {
//
// public String type;
// public Data data;
//
// protected ItemList(Parcel in) {
// type = in.readString();
// data = in.readParcelable(Data.class.getClassLoader());
// }
//
// public static final Creator<ItemList> CREATOR = new Creator<ItemList>() {
// @Override
// public ItemList createFromParcel(Parcel in) {
// return new ItemList(in);
// }
//
// @Override
// public ItemList[] newArray(int size) {
// return new ItemList[size];
// }
// };
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(type);
// dest.writeParcelable(data, flags);
// }
//
// }
| import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.popo.popomusic.R;
import com.popomusic.picBean.Contentlist;
import com.popomusic.util.UIcollector;
import com.popomusic.videoModel.ItemList;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard; |
}
//动态加载数据至配适器中
public void addAll(List<Contentlist> lists) {
list.addAll(lists);
}
public void removeAll() {
if (list.size() != 0) {
list.clear();
}
this.notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_pic, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Contentlist contentlist= list.get(position);
// 随机高度, 模拟瀑布效果.
if (mHeights.size() <= position) {
mHeights.add((int) (100 + Math.random() * 300));
}
ViewGroup.LayoutParams lp = ((ViewHolder) holder).imageView.getLayoutParams();
lp.height = mHeights.get(position);
((ViewHolder) holder).imageView.setLayoutParams(lp); | // Path: app/src/main/java/com/popomusic/picBean/Contentlist.java
// public class Contentlist {
//
// @SerializedName("itemId")
// @Expose
// private String itemId;
// @SerializedName("list")
// @Expose
// private java.util.List<Picbean> list = null;
// @SerializedName("title")
// @Expose
// private String title;
// @SerializedName("type")
// @Expose
// private Integer type;
// @SerializedName("typeName")
// @Expose
// private String typeName;
//
//
// public String getItemId() {
// return itemId;
// }
//
// public void setItemId(String itemId) {
// this.itemId = itemId;
// }
//
// public java.util.List<Picbean> getList() {
// return list;
// }
//
// public void setList(java.util.List<Picbean> list) {
// this.list = list;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public Integer getType() {
// return type;
// }
//
// public void setType(Integer type) {
// this.type = type;
// }
//
// public String getTypeName() {
// return typeName;
// }
//
// public void setTypeName(String typeName) {
// this.typeName = typeName;
// }
//
// }
//
// Path: app/src/main/java/com/popomusic/util/UIcollector.java
// @SuppressWarnings("ALL")
// public class UIcollector {
//
//
// public static Context getContext() {
// return BaseActivity.getContext();
// }
//
// public static Activity getActivity() {
// return BaseActivity.getActivity();
// }
//
//
// public static Drawable getDrawable(int id) {
// return getContext().getResources().getDrawable(id);
// }
//
// public static int getColor(int id) {
// return getContext().getResources().getColor(id);
// }
//
// public static String getString(int id) {
// return getContext().getResources().getString(id);
// }
//
//
// public static String[] getStringArray(int id) {
// return getContext().getResources().getStringArray(id);
// }
// }
//
// Path: app/src/main/java/com/popomusic/videoModel/ItemList.java
// public class ItemList implements Parcelable {
//
// public String type;
// public Data data;
//
// protected ItemList(Parcel in) {
// type = in.readString();
// data = in.readParcelable(Data.class.getClassLoader());
// }
//
// public static final Creator<ItemList> CREATOR = new Creator<ItemList>() {
// @Override
// public ItemList createFromParcel(Parcel in) {
// return new ItemList(in);
// }
//
// @Override
// public ItemList[] newArray(int size) {
// return new ItemList[size];
// }
// };
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(type);
// dest.writeParcelable(data, flags);
// }
//
// }
// Path: app/src/main/java/com/popomusic/adapter/PicAdapter.java
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.popo.popomusic.R;
import com.popomusic.picBean.Contentlist;
import com.popomusic.util.UIcollector;
import com.popomusic.videoModel.ItemList;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
}
//动态加载数据至配适器中
public void addAll(List<Contentlist> lists) {
list.addAll(lists);
}
public void removeAll() {
if (list.size() != 0) {
list.clear();
}
this.notifyDataSetChanged();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_pic, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Contentlist contentlist= list.get(position);
// 随机高度, 模拟瀑布效果.
if (mHeights.size() <= position) {
mHeights.add((int) (100 + Math.random() * 300));
}
ViewGroup.LayoutParams lp = ((ViewHolder) holder).imageView.getLayoutParams();
lp.height = mHeights.get(position);
((ViewHolder) holder).imageView.setLayoutParams(lp); | Glide.with(UIcollector.getContext()) |
popo1379/popomusic | app/src/main/java/com/popomusic/fragment/BaseFragment.java | // Path: app/src/main/java/com/popomusic/util/UIcollector.java
// @SuppressWarnings("ALL")
// public class UIcollector {
//
//
// public static Context getContext() {
// return BaseActivity.getContext();
// }
//
// public static Activity getActivity() {
// return BaseActivity.getActivity();
// }
//
//
// public static Drawable getDrawable(int id) {
// return getContext().getResources().getDrawable(id);
// }
//
// public static int getColor(int id) {
// return getContext().getResources().getColor(id);
// }
//
// public static String getString(int id) {
// return getContext().getResources().getString(id);
// }
//
//
// public static String[] getStringArray(int id) {
// return getContext().getResources().getStringArray(id);
// }
// }
| import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.popomusic.util.UIcollector;
import butterknife.ButterKnife; |
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = initView();
Log.i("BaseFragment", getClass().getSimpleName());
ButterKnife.bind(this,view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initData();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getUserVisibleHint()) {
isVisible = true;
onVisible();
} else {
isVisible = false;
onInvisible();
}
}
void Toast(String content) { | // Path: app/src/main/java/com/popomusic/util/UIcollector.java
// @SuppressWarnings("ALL")
// public class UIcollector {
//
//
// public static Context getContext() {
// return BaseActivity.getContext();
// }
//
// public static Activity getActivity() {
// return BaseActivity.getActivity();
// }
//
//
// public static Drawable getDrawable(int id) {
// return getContext().getResources().getDrawable(id);
// }
//
// public static int getColor(int id) {
// return getContext().getResources().getColor(id);
// }
//
// public static String getString(int id) {
// return getContext().getResources().getString(id);
// }
//
//
// public static String[] getStringArray(int id) {
// return getContext().getResources().getStringArray(id);
// }
// }
// Path: app/src/main/java/com/popomusic/fragment/BaseFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.popomusic.util.UIcollector;
import butterknife.ButterKnife;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = initView();
Log.i("BaseFragment", getClass().getSimpleName());
ButterKnife.bind(this,view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initData();
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getUserVisibleHint()) {
isVisible = true;
onVisible();
} else {
isVisible = false;
onInvisible();
}
}
void Toast(String content) { | Toast.makeText(UIcollector.getContext(), content, Toast.LENGTH_LONG).show(); |
popo1379/popomusic | app/src/main/java/com/popomusic/data/PicData.java | // Path: app/src/main/java/com/popomusic/picBean/Contentlist.java
// public class Contentlist {
//
// @SerializedName("itemId")
// @Expose
// private String itemId;
// @SerializedName("list")
// @Expose
// private java.util.List<Picbean> list = null;
// @SerializedName("title")
// @Expose
// private String title;
// @SerializedName("type")
// @Expose
// private Integer type;
// @SerializedName("typeName")
// @Expose
// private String typeName;
//
//
// public String getItemId() {
// return itemId;
// }
//
// public void setItemId(String itemId) {
// this.itemId = itemId;
// }
//
// public java.util.List<Picbean> getList() {
// return list;
// }
//
// public void setList(java.util.List<Picbean> list) {
// this.list = list;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public Integer getType() {
// return type;
// }
//
// public void setType(Integer type) {
// this.type = type;
// }
//
// public String getTypeName() {
// return typeName;
// }
//
// public void setTypeName(String typeName) {
// this.typeName = typeName;
// }
//
// }
//
// Path: app/src/main/java/com/popomusic/picBean/picbean.java
// public class Picbean {
//
// @SerializedName("big")
// @Expose
// private String big;
// @SerializedName("middle")
// @Expose
// private String middle;
// @SerializedName("small")
// @Expose
// private String small;
//
// public String getBig() {
// return big;
// }
//
// public void setBig(String big) {
// this.big = big;
// }
//
// public String getMiddle() {
// return middle;
// }
//
// public void setMiddle(String middle) {
// this.middle = middle;
// }
//
// public String getSmall() {
// return small;
// }
//
// public void setSmall(String small) {
// this.small = small;
// }
//
// }
//
// Path: app/src/main/java/com/popomusic/videoModel/ItemList.java
// public class ItemList implements Parcelable {
//
// public String type;
// public Data data;
//
// protected ItemList(Parcel in) {
// type = in.readString();
// data = in.readParcelable(Data.class.getClassLoader());
// }
//
// public static final Creator<ItemList> CREATOR = new Creator<ItemList>() {
// @Override
// public ItemList createFromParcel(Parcel in) {
// return new ItemList(in);
// }
//
// @Override
// public ItemList[] newArray(int size) {
// return new ItemList[size];
// }
// };
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(type);
// dest.writeParcelable(data, flags);
// }
//
// }
//
// Path: app/src/main/java/com/popomusic/view/BaseView.java
// public interface BaseView {
// }
| import com.popomusic.picBean.Contentlist;
import com.popomusic.picBean.Picbean;
import com.popomusic.videoModel.ItemList;
import com.popomusic.view.BaseView;
import java.util.List; | package com.popomusic.data;
/**
* Created by Administrator on 2017/5/31 0031.
*/
public interface PicData {
interface View extends BaseView { | // Path: app/src/main/java/com/popomusic/picBean/Contentlist.java
// public class Contentlist {
//
// @SerializedName("itemId")
// @Expose
// private String itemId;
// @SerializedName("list")
// @Expose
// private java.util.List<Picbean> list = null;
// @SerializedName("title")
// @Expose
// private String title;
// @SerializedName("type")
// @Expose
// private Integer type;
// @SerializedName("typeName")
// @Expose
// private String typeName;
//
//
// public String getItemId() {
// return itemId;
// }
//
// public void setItemId(String itemId) {
// this.itemId = itemId;
// }
//
// public java.util.List<Picbean> getList() {
// return list;
// }
//
// public void setList(java.util.List<Picbean> list) {
// this.list = list;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void setTitle(String title) {
// this.title = title;
// }
//
// public Integer getType() {
// return type;
// }
//
// public void setType(Integer type) {
// this.type = type;
// }
//
// public String getTypeName() {
// return typeName;
// }
//
// public void setTypeName(String typeName) {
// this.typeName = typeName;
// }
//
// }
//
// Path: app/src/main/java/com/popomusic/picBean/picbean.java
// public class Picbean {
//
// @SerializedName("big")
// @Expose
// private String big;
// @SerializedName("middle")
// @Expose
// private String middle;
// @SerializedName("small")
// @Expose
// private String small;
//
// public String getBig() {
// return big;
// }
//
// public void setBig(String big) {
// this.big = big;
// }
//
// public String getMiddle() {
// return middle;
// }
//
// public void setMiddle(String middle) {
// this.middle = middle;
// }
//
// public String getSmall() {
// return small;
// }
//
// public void setSmall(String small) {
// this.small = small;
// }
//
// }
//
// Path: app/src/main/java/com/popomusic/videoModel/ItemList.java
// public class ItemList implements Parcelable {
//
// public String type;
// public Data data;
//
// protected ItemList(Parcel in) {
// type = in.readString();
// data = in.readParcelable(Data.class.getClassLoader());
// }
//
// public static final Creator<ItemList> CREATOR = new Creator<ItemList>() {
// @Override
// public ItemList createFromParcel(Parcel in) {
// return new ItemList(in);
// }
//
// @Override
// public ItemList[] newArray(int size) {
// return new ItemList[size];
// }
// };
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeString(type);
// dest.writeParcelable(data, flags);
// }
//
// }
//
// Path: app/src/main/java/com/popomusic/view/BaseView.java
// public interface BaseView {
// }
// Path: app/src/main/java/com/popomusic/data/PicData.java
import com.popomusic.picBean.Contentlist;
import com.popomusic.picBean.Picbean;
import com.popomusic.videoModel.ItemList;
import com.popomusic.view.BaseView;
import java.util.List;
package com.popomusic.data;
/**
* Created by Administrator on 2017/5/31 0031.
*/
public interface PicData {
interface View extends BaseView { | void setData(List<Contentlist> list); |
popo1379/popomusic | app/src/main/java/com/popomusic/util/UIcollector.java | // Path: app/src/main/java/com/popomusic/activity/BaseActivity.java
// public abstract class BaseActivity extends AppCompatActivity {
//
// private static Context context;
// private static Activity activity;
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// init(savedInstanceState);//初始化view之前,进行的操作
// super.onCreate(savedInstanceState);
// setContentView(setLayoutResourceID());
// context = getApplicationContext();
// activity = this;
// ButterKnife.bind(this);
// initView();
// initListener();
// initData();
// }
// public void init(Bundle savedInstanceState){}
// public abstract int setLayoutResourceID();
// public abstract void initView();
// public void initListener(){}
// public abstract void initData();
//
// public static Context getContext() {
// return context;
// }
//
// public static Activity getActivity() {
// return activity;
// }
//
// void Toast(String content) {
// Toast.makeText(UIcollector.getContext(), content, Toast.LENGTH_LONG).show();
//
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.popomusic.activity.BaseActivity; | package com.popomusic.util;
/**
* by popo on 2016/4/28.
*/
@SuppressWarnings("ALL")
public class UIcollector {
public static Context getContext() { | // Path: app/src/main/java/com/popomusic/activity/BaseActivity.java
// public abstract class BaseActivity extends AppCompatActivity {
//
// private static Context context;
// private static Activity activity;
//
// @Override
// protected void onCreate(@Nullable Bundle savedInstanceState) {
// init(savedInstanceState);//初始化view之前,进行的操作
// super.onCreate(savedInstanceState);
// setContentView(setLayoutResourceID());
// context = getApplicationContext();
// activity = this;
// ButterKnife.bind(this);
// initView();
// initListener();
// initData();
// }
// public void init(Bundle savedInstanceState){}
// public abstract int setLayoutResourceID();
// public abstract void initView();
// public void initListener(){}
// public abstract void initData();
//
// public static Context getContext() {
// return context;
// }
//
// public static Activity getActivity() {
// return activity;
// }
//
// void Toast(String content) {
// Toast.makeText(UIcollector.getContext(), content, Toast.LENGTH_LONG).show();
//
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// }
// }
// Path: app/src/main/java/com/popomusic/util/UIcollector.java
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.popomusic.activity.BaseActivity;
package com.popomusic.util;
/**
* by popo on 2016/4/28.
*/
@SuppressWarnings("ALL")
public class UIcollector {
public static Context getContext() { | return BaseActivity.getContext(); |
popo1379/popomusic | app/src/main/java/com/popomusic/videoModel/VideoBeanDao.java | // Path: app/src/main/java/com/popomusic/bean/DaoSession.java
// public class DaoSession extends AbstractDaoSession {
//
// private final DaoConfig musicBeanDaoConfig;
// private final DaoConfig searchNameBeanDaoConfig;
// private final DaoConfig videoBeanDaoConfig;
//
// private final MusicBeanDao musicBeanDao;
// private final SearchNameBeanDao searchNameBeanDao;
// private final VideoBeanDao videoBeanDao;
//
// public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
// daoConfigMap) {
// super(db);
//
// musicBeanDaoConfig = daoConfigMap.get(MusicBeanDao.class).clone();
// musicBeanDaoConfig.initIdentityScope(type);
//
// searchNameBeanDaoConfig = daoConfigMap.get(SearchNameBeanDao.class).clone();
// searchNameBeanDaoConfig.initIdentityScope(type);
//
// videoBeanDaoConfig = daoConfigMap.get(VideoBeanDao.class).clone();
// videoBeanDaoConfig.initIdentityScope(type);
//
// musicBeanDao = new MusicBeanDao(musicBeanDaoConfig, this);
// searchNameBeanDao = new SearchNameBeanDao(searchNameBeanDaoConfig, this);
// videoBeanDao = new VideoBeanDao(videoBeanDaoConfig, this);
//
// registerDao(MusicBean.class, musicBeanDao);
// registerDao(SearchNameBean.class, searchNameBeanDao);
// registerDao(VideoBean.class, videoBeanDao);
// }
//
// public void clear() {
// musicBeanDaoConfig.clearIdentityScope();
// searchNameBeanDaoConfig.clearIdentityScope();
// videoBeanDaoConfig.clearIdentityScope();
// }
//
// public MusicBeanDao getMusicBeanDao() {
// return musicBeanDao;
// }
//
// public SearchNameBeanDao getSearchNameBeanDao() {
// return searchNameBeanDao;
// }
//
// public VideoBeanDao getVideoBeanDao() {
// return videoBeanDao;
// }
//
// }
| import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import com.popomusic.bean.DaoSession; | package com.popomusic.videoModel;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "VIDEO_BEAN".
*/
public class VideoBeanDao extends AbstractDao<VideoBean, Long> {
public static final String TABLENAME = "VIDEO_BEAN";
/**
* Properties of entity VideoBean.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property DataType = new Property(1, String.class, "dataType", false, "DATA_TYPE");
public final static Property Title = new Property(2, String.class, "title", false, "TITLE");
public final static Property Text = new Property(3, String.class, "text", false, "TEXT");
public final static Property Description = new Property(4, String.class, "description", false, "DESCRIPTION");
public final static Property Image = new Property(5, String.class, "image", false, "IMAGE");
public final static Property ActionUrl = new Property(6, String.class, "actionUrl", false, "ACTION_URL");
public final static Property Shade = new Property(7, boolean.class, "shade", false, "SHADE");
public final static Property PlayUrl = new Property(8, String.class, "playUrl", false, "PLAY_URL");
public final static Property Category = new Property(9, String.class, "category", false, "CATEGORY");
public final static Property Duration = new Property(10, long.class, "duration", false, "DURATION");
public final static Property Icon = new Property(11, String.class, "icon", false, "ICON");
}
public VideoBeanDao(DaoConfig config) {
super(config);
}
| // Path: app/src/main/java/com/popomusic/bean/DaoSession.java
// public class DaoSession extends AbstractDaoSession {
//
// private final DaoConfig musicBeanDaoConfig;
// private final DaoConfig searchNameBeanDaoConfig;
// private final DaoConfig videoBeanDaoConfig;
//
// private final MusicBeanDao musicBeanDao;
// private final SearchNameBeanDao searchNameBeanDao;
// private final VideoBeanDao videoBeanDao;
//
// public DaoSession(Database db, IdentityScopeType type, Map<Class<? extends AbstractDao<?, ?>>, DaoConfig>
// daoConfigMap) {
// super(db);
//
// musicBeanDaoConfig = daoConfigMap.get(MusicBeanDao.class).clone();
// musicBeanDaoConfig.initIdentityScope(type);
//
// searchNameBeanDaoConfig = daoConfigMap.get(SearchNameBeanDao.class).clone();
// searchNameBeanDaoConfig.initIdentityScope(type);
//
// videoBeanDaoConfig = daoConfigMap.get(VideoBeanDao.class).clone();
// videoBeanDaoConfig.initIdentityScope(type);
//
// musicBeanDao = new MusicBeanDao(musicBeanDaoConfig, this);
// searchNameBeanDao = new SearchNameBeanDao(searchNameBeanDaoConfig, this);
// videoBeanDao = new VideoBeanDao(videoBeanDaoConfig, this);
//
// registerDao(MusicBean.class, musicBeanDao);
// registerDao(SearchNameBean.class, searchNameBeanDao);
// registerDao(VideoBean.class, videoBeanDao);
// }
//
// public void clear() {
// musicBeanDaoConfig.clearIdentityScope();
// searchNameBeanDaoConfig.clearIdentityScope();
// videoBeanDaoConfig.clearIdentityScope();
// }
//
// public MusicBeanDao getMusicBeanDao() {
// return musicBeanDao;
// }
//
// public SearchNameBeanDao getSearchNameBeanDao() {
// return searchNameBeanDao;
// }
//
// public VideoBeanDao getVideoBeanDao() {
// return videoBeanDao;
// }
//
// }
// Path: app/src/main/java/com/popomusic/videoModel/VideoBeanDao.java
import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;
import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import com.popomusic.bean.DaoSession;
package com.popomusic.videoModel;
// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
* DAO for table "VIDEO_BEAN".
*/
public class VideoBeanDao extends AbstractDao<VideoBean, Long> {
public static final String TABLENAME = "VIDEO_BEAN";
/**
* Properties of entity VideoBean.<br/>
* Can be used for QueryBuilder and for referencing column names.
*/
public static class Properties {
public final static Property Id = new Property(0, Long.class, "id", true, "_id");
public final static Property DataType = new Property(1, String.class, "dataType", false, "DATA_TYPE");
public final static Property Title = new Property(2, String.class, "title", false, "TITLE");
public final static Property Text = new Property(3, String.class, "text", false, "TEXT");
public final static Property Description = new Property(4, String.class, "description", false, "DESCRIPTION");
public final static Property Image = new Property(5, String.class, "image", false, "IMAGE");
public final static Property ActionUrl = new Property(6, String.class, "actionUrl", false, "ACTION_URL");
public final static Property Shade = new Property(7, boolean.class, "shade", false, "SHADE");
public final static Property PlayUrl = new Property(8, String.class, "playUrl", false, "PLAY_URL");
public final static Property Category = new Property(9, String.class, "category", false, "CATEGORY");
public final static Property Duration = new Property(10, long.class, "duration", false, "DURATION");
public final static Property Icon = new Property(11, String.class, "icon", false, "ICON");
}
public VideoBeanDao(DaoConfig config) {
super(config);
}
| public VideoBeanDao(DaoConfig config, DaoSession daoSession) { |
amplify-education/honeydew | server/src/main/java/com/amplify/honeydew_server/actions/AbstractChildCountAction.java | // Path: server/src/main/java/com/amplify/honeydew_server/Action.java
// public abstract class Action {
// protected final UiDevice uiDevice;
//
// protected final String TAG = getClass().getSimpleName();
//
// public Action(UiDevice uiDevice) {
// this.uiDevice = uiDevice;
// }
//
// public abstract Result execute(Map<String, Object> arguments) throws UiObjectNotFoundException;
//
// public String name() {
// return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, getClass().getSimpleName());
// }
//
// protected UiDevice getUiDevice() {
// return uiDevice;
// }
//
// private long getTimeoutInMs(Map<String, Object> arguments){
// return Integer.parseInt((String) arguments.get("timeout")) * 1000;
// }
//
// protected boolean isUiObjectAvailable(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitForExists(getTimeoutInMs(arguments));
// }
//
// protected boolean isUiObjectGone(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitUntilGone(getTimeoutInMs(arguments));
// }
//
// protected UiObject getUiObject(Map<String, Object> arguments) {
// ViewSelector viewSelector = getViewSelector(arguments);
// return viewSelector.find();
// }
//
// protected ViewSelector getViewSelector(Map<String, Object> arguments) {
// ViewSelector viewSelector = new ViewSelector();
//
// Log.d(TAG, arguments.toString());
// if (arguments.containsKey("type")) {
// Log.d(TAG, String.format("Type %s", (String) arguments.get("type")));
// viewSelector.withType((String) arguments.get("type"));
// }
// if (arguments.containsKey("text")) {
// Log.d(TAG, String.format("Text %s", (String) arguments.get("text")));
// viewSelector.withText((String) arguments.get("text"));
// }
// if (arguments.containsKey("description")) {
// Log.d(TAG, String.format("Description %s", (String) arguments.get("description")));
// viewSelector.withDescription((String) arguments.get("description"));
// }
// if (arguments.containsKey("regex")) {
// Log.d(TAG, String.format("Regular Expression %s", (String) arguments.get("regex")));
// viewSelector.withRegexMatch((String) arguments.get("regex"));
// }
// return viewSelector;
// }
//
// public static class ViewSelector {
// private UiSelector uiSelector = new UiSelector();
//
// public ViewSelector withType(String type) {
// uiSelector = uiSelector.className("android.widget." + type);
// return this;
// }
//
// public ViewSelector withText(String text) {
// uiSelector = uiSelector.textContains(text);
// return this;
// }
//
// public ViewSelector withDescription(String description) {
// uiSelector = uiSelector.description(description);
// return this;
// }
//
// public ViewSelector withRegexMatch(String regexString) {
// uiSelector = uiSelector.textMatches(regexString);
// return this;
// }
//
// public UiObject find() {
// return new UiObject(uiSelector);
// }
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
| import android.util.Log;
import com.amplify.honeydew_server.Action;
import com.amplify.honeydew_server.Result;
import com.android.uiautomator.core.UiCollection;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiSelector;
import java.util.Map; | package com.amplify.honeydew_server.actions;
public abstract class AbstractChildCountAction extends Action {
public AbstractChildCountAction(UiDevice uiDevice) {
super(uiDevice);
}
protected abstract boolean isTrue(int childCount, int count);
@Override | // Path: server/src/main/java/com/amplify/honeydew_server/Action.java
// public abstract class Action {
// protected final UiDevice uiDevice;
//
// protected final String TAG = getClass().getSimpleName();
//
// public Action(UiDevice uiDevice) {
// this.uiDevice = uiDevice;
// }
//
// public abstract Result execute(Map<String, Object> arguments) throws UiObjectNotFoundException;
//
// public String name() {
// return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, getClass().getSimpleName());
// }
//
// protected UiDevice getUiDevice() {
// return uiDevice;
// }
//
// private long getTimeoutInMs(Map<String, Object> arguments){
// return Integer.parseInt((String) arguments.get("timeout")) * 1000;
// }
//
// protected boolean isUiObjectAvailable(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitForExists(getTimeoutInMs(arguments));
// }
//
// protected boolean isUiObjectGone(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitUntilGone(getTimeoutInMs(arguments));
// }
//
// protected UiObject getUiObject(Map<String, Object> arguments) {
// ViewSelector viewSelector = getViewSelector(arguments);
// return viewSelector.find();
// }
//
// protected ViewSelector getViewSelector(Map<String, Object> arguments) {
// ViewSelector viewSelector = new ViewSelector();
//
// Log.d(TAG, arguments.toString());
// if (arguments.containsKey("type")) {
// Log.d(TAG, String.format("Type %s", (String) arguments.get("type")));
// viewSelector.withType((String) arguments.get("type"));
// }
// if (arguments.containsKey("text")) {
// Log.d(TAG, String.format("Text %s", (String) arguments.get("text")));
// viewSelector.withText((String) arguments.get("text"));
// }
// if (arguments.containsKey("description")) {
// Log.d(TAG, String.format("Description %s", (String) arguments.get("description")));
// viewSelector.withDescription((String) arguments.get("description"));
// }
// if (arguments.containsKey("regex")) {
// Log.d(TAG, String.format("Regular Expression %s", (String) arguments.get("regex")));
// viewSelector.withRegexMatch((String) arguments.get("regex"));
// }
// return viewSelector;
// }
//
// public static class ViewSelector {
// private UiSelector uiSelector = new UiSelector();
//
// public ViewSelector withType(String type) {
// uiSelector = uiSelector.className("android.widget." + type);
// return this;
// }
//
// public ViewSelector withText(String text) {
// uiSelector = uiSelector.textContains(text);
// return this;
// }
//
// public ViewSelector withDescription(String description) {
// uiSelector = uiSelector.description(description);
// return this;
// }
//
// public ViewSelector withRegexMatch(String regexString) {
// uiSelector = uiSelector.textMatches(regexString);
// return this;
// }
//
// public UiObject find() {
// return new UiObject(uiSelector);
// }
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
// Path: server/src/main/java/com/amplify/honeydew_server/actions/AbstractChildCountAction.java
import android.util.Log;
import com.amplify.honeydew_server.Action;
import com.amplify.honeydew_server.Result;
import com.android.uiautomator.core.UiCollection;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiSelector;
import java.util.Map;
package com.amplify.honeydew_server.actions;
public abstract class AbstractChildCountAction extends Action {
public AbstractChildCountAction(UiDevice uiDevice) {
super(uiDevice);
}
protected abstract boolean isTrue(int childCount, int count);
@Override | public final Result execute(Map<String, Object> arguments) throws UiObjectNotFoundException { |
amplify-education/honeydew | server/src/main/java/com/amplify/honeydew_server/actions/IsRegexMatchPresent.java | // Path: server/src/main/java/com/amplify/honeydew_server/Action.java
// public abstract class Action {
// protected final UiDevice uiDevice;
//
// protected final String TAG = getClass().getSimpleName();
//
// public Action(UiDevice uiDevice) {
// this.uiDevice = uiDevice;
// }
//
// public abstract Result execute(Map<String, Object> arguments) throws UiObjectNotFoundException;
//
// public String name() {
// return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, getClass().getSimpleName());
// }
//
// protected UiDevice getUiDevice() {
// return uiDevice;
// }
//
// private long getTimeoutInMs(Map<String, Object> arguments){
// return Integer.parseInt((String) arguments.get("timeout")) * 1000;
// }
//
// protected boolean isUiObjectAvailable(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitForExists(getTimeoutInMs(arguments));
// }
//
// protected boolean isUiObjectGone(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitUntilGone(getTimeoutInMs(arguments));
// }
//
// protected UiObject getUiObject(Map<String, Object> arguments) {
// ViewSelector viewSelector = getViewSelector(arguments);
// return viewSelector.find();
// }
//
// protected ViewSelector getViewSelector(Map<String, Object> arguments) {
// ViewSelector viewSelector = new ViewSelector();
//
// Log.d(TAG, arguments.toString());
// if (arguments.containsKey("type")) {
// Log.d(TAG, String.format("Type %s", (String) arguments.get("type")));
// viewSelector.withType((String) arguments.get("type"));
// }
// if (arguments.containsKey("text")) {
// Log.d(TAG, String.format("Text %s", (String) arguments.get("text")));
// viewSelector.withText((String) arguments.get("text"));
// }
// if (arguments.containsKey("description")) {
// Log.d(TAG, String.format("Description %s", (String) arguments.get("description")));
// viewSelector.withDescription((String) arguments.get("description"));
// }
// if (arguments.containsKey("regex")) {
// Log.d(TAG, String.format("Regular Expression %s", (String) arguments.get("regex")));
// viewSelector.withRegexMatch((String) arguments.get("regex"));
// }
// return viewSelector;
// }
//
// public static class ViewSelector {
// private UiSelector uiSelector = new UiSelector();
//
// public ViewSelector withType(String type) {
// uiSelector = uiSelector.className("android.widget." + type);
// return this;
// }
//
// public ViewSelector withText(String text) {
// uiSelector = uiSelector.textContains(text);
// return this;
// }
//
// public ViewSelector withDescription(String description) {
// uiSelector = uiSelector.description(description);
// return this;
// }
//
// public ViewSelector withRegexMatch(String regexString) {
// uiSelector = uiSelector.textMatches(regexString);
// return this;
// }
//
// public UiObject find() {
// return new UiObject(uiSelector);
// }
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
| import com.amplify.honeydew_server.Action;
import com.amplify.honeydew_server.Result;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObjectNotFoundException;
import java.util.Map; | package com.amplify.honeydew_server.actions;
public class IsRegexMatchPresent extends Action {
public IsRegexMatchPresent(UiDevice uiDevice){
super(uiDevice);
}
@Override | // Path: server/src/main/java/com/amplify/honeydew_server/Action.java
// public abstract class Action {
// protected final UiDevice uiDevice;
//
// protected final String TAG = getClass().getSimpleName();
//
// public Action(UiDevice uiDevice) {
// this.uiDevice = uiDevice;
// }
//
// public abstract Result execute(Map<String, Object> arguments) throws UiObjectNotFoundException;
//
// public String name() {
// return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, getClass().getSimpleName());
// }
//
// protected UiDevice getUiDevice() {
// return uiDevice;
// }
//
// private long getTimeoutInMs(Map<String, Object> arguments){
// return Integer.parseInt((String) arguments.get("timeout")) * 1000;
// }
//
// protected boolean isUiObjectAvailable(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitForExists(getTimeoutInMs(arguments));
// }
//
// protected boolean isUiObjectGone(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitUntilGone(getTimeoutInMs(arguments));
// }
//
// protected UiObject getUiObject(Map<String, Object> arguments) {
// ViewSelector viewSelector = getViewSelector(arguments);
// return viewSelector.find();
// }
//
// protected ViewSelector getViewSelector(Map<String, Object> arguments) {
// ViewSelector viewSelector = new ViewSelector();
//
// Log.d(TAG, arguments.toString());
// if (arguments.containsKey("type")) {
// Log.d(TAG, String.format("Type %s", (String) arguments.get("type")));
// viewSelector.withType((String) arguments.get("type"));
// }
// if (arguments.containsKey("text")) {
// Log.d(TAG, String.format("Text %s", (String) arguments.get("text")));
// viewSelector.withText((String) arguments.get("text"));
// }
// if (arguments.containsKey("description")) {
// Log.d(TAG, String.format("Description %s", (String) arguments.get("description")));
// viewSelector.withDescription((String) arguments.get("description"));
// }
// if (arguments.containsKey("regex")) {
// Log.d(TAG, String.format("Regular Expression %s", (String) arguments.get("regex")));
// viewSelector.withRegexMatch((String) arguments.get("regex"));
// }
// return viewSelector;
// }
//
// public static class ViewSelector {
// private UiSelector uiSelector = new UiSelector();
//
// public ViewSelector withType(String type) {
// uiSelector = uiSelector.className("android.widget." + type);
// return this;
// }
//
// public ViewSelector withText(String text) {
// uiSelector = uiSelector.textContains(text);
// return this;
// }
//
// public ViewSelector withDescription(String description) {
// uiSelector = uiSelector.description(description);
// return this;
// }
//
// public ViewSelector withRegexMatch(String regexString) {
// uiSelector = uiSelector.textMatches(regexString);
// return this;
// }
//
// public UiObject find() {
// return new UiObject(uiSelector);
// }
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
// Path: server/src/main/java/com/amplify/honeydew_server/actions/IsRegexMatchPresent.java
import com.amplify.honeydew_server.Action;
import com.amplify.honeydew_server.Result;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObjectNotFoundException;
import java.util.Map;
package com.amplify.honeydew_server.actions;
public class IsRegexMatchPresent extends Action {
public IsRegexMatchPresent(UiDevice uiDevice){
super(uiDevice);
}
@Override | public Result execute(Map<String, Object> arguments) throws UiObjectNotFoundException { |
amplify-education/honeydew | server/src/main/java/com/amplify/honeydew_server/TestRunner.java | // Path: server/src/main/java/com/amplify/honeydew_server/httpd/RemoteCommandReceiver.java
// public class RemoteCommandReceiver extends NanoHTTPD {
//
// private static final String PLAIN_TEXT = "plain/text";
// public static final Type ARGUMENTS_COLLECTION_TYPE = new TypeToken<Map<String, Object>>() {
// }.getType();
// private final ActionsExecutor actionsExecutor;
//
// private static final Response OK = new Response("honeydew-server is awaiting commands");
// private static final Response TERMINATED = new Response("honeydew-server is stopping");
// private final Response BAD_REQUEST = new Response(Response.Status.BAD_REQUEST, PLAIN_TEXT, "Unsupported command");
//
// private static final String TAG = RemoteCommandReceiver.class.getSimpleName();
// private final Gson jsonParser = new Gson();
//
// public RemoteCommandReceiver(ActionsExecutor actionsExecutor) throws IOException, InterruptedException {
// super(7120);
// this.actionsExecutor = actionsExecutor;
// }
//
// @Override
// public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> params, Map<String, String> files) {
// if (method == Method.POST && uri.equalsIgnoreCase("/terminate")) {
// return terminate();
// }
// if (method == Method.POST && uri.equalsIgnoreCase("/command")) {
// return performCommand(params);
// }
// if (method == Method.GET && uri.equalsIgnoreCase("/status")) {
// return status();
// }
//
// return BAD_REQUEST;
// }
//
// private Response status() {
// Log.d(TAG, "Got status request, responding OK");
// return OK;
// }
//
// private Response terminate() {
// Log.d(TAG, "Got terminate request, finishing up...");
// stop();
// return TERMINATED;
// }
//
// private Response performCommand(Map<String, String> params) {
// String action = params.get("action");
// String argumentJson = params.get("arguments");
// Map<String, Object> arguments = jsonParser.fromJson(argumentJson, ARGUMENTS_COLLECTION_TYPE);
//
// Log.i(TAG, format("Performing action %s: %s for %s", action, argumentJson, params.toString()));
// try {
// Result result = actionsExecutor.execute(new Command(action, arguments));
// if (result.success) {
// return new Response(result.description);
// }
// return new Response(Response.Status.NO_CONTENT, null, (String) null);
// } catch (Exception exception) {
// Log.e(TAG, format("Server error while processing command %s: %s", action, exception.toString()));
// return new Response(Response.Status.INTERNAL_ERROR, PLAIN_TEXT, exception.getMessage());
// }
// }
// }
| import android.util.Log;
import android.view.KeyEvent;
import com.amplify.honeydew_server.httpd.RemoteCommandReceiver;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.testrunner.UiAutomatorTestCase; | package com.amplify.honeydew_server;
public class TestRunner extends UiAutomatorTestCase {
private static final String TAG = TestRunner.class.getSimpleName();
public void testRemoteLoop() throws Exception {
Log.d(TAG, "Starting honeydew-server...");
UiDevice uiDevice = getUiDevice();
uiDevice.wakeUp();
unlockEmulator();
| // Path: server/src/main/java/com/amplify/honeydew_server/httpd/RemoteCommandReceiver.java
// public class RemoteCommandReceiver extends NanoHTTPD {
//
// private static final String PLAIN_TEXT = "plain/text";
// public static final Type ARGUMENTS_COLLECTION_TYPE = new TypeToken<Map<String, Object>>() {
// }.getType();
// private final ActionsExecutor actionsExecutor;
//
// private static final Response OK = new Response("honeydew-server is awaiting commands");
// private static final Response TERMINATED = new Response("honeydew-server is stopping");
// private final Response BAD_REQUEST = new Response(Response.Status.BAD_REQUEST, PLAIN_TEXT, "Unsupported command");
//
// private static final String TAG = RemoteCommandReceiver.class.getSimpleName();
// private final Gson jsonParser = new Gson();
//
// public RemoteCommandReceiver(ActionsExecutor actionsExecutor) throws IOException, InterruptedException {
// super(7120);
// this.actionsExecutor = actionsExecutor;
// }
//
// @Override
// public Response serve(String uri, Method method, Map<String, String> headers, Map<String, String> params, Map<String, String> files) {
// if (method == Method.POST && uri.equalsIgnoreCase("/terminate")) {
// return terminate();
// }
// if (method == Method.POST && uri.equalsIgnoreCase("/command")) {
// return performCommand(params);
// }
// if (method == Method.GET && uri.equalsIgnoreCase("/status")) {
// return status();
// }
//
// return BAD_REQUEST;
// }
//
// private Response status() {
// Log.d(TAG, "Got status request, responding OK");
// return OK;
// }
//
// private Response terminate() {
// Log.d(TAG, "Got terminate request, finishing up...");
// stop();
// return TERMINATED;
// }
//
// private Response performCommand(Map<String, String> params) {
// String action = params.get("action");
// String argumentJson = params.get("arguments");
// Map<String, Object> arguments = jsonParser.fromJson(argumentJson, ARGUMENTS_COLLECTION_TYPE);
//
// Log.i(TAG, format("Performing action %s: %s for %s", action, argumentJson, params.toString()));
// try {
// Result result = actionsExecutor.execute(new Command(action, arguments));
// if (result.success) {
// return new Response(result.description);
// }
// return new Response(Response.Status.NO_CONTENT, null, (String) null);
// } catch (Exception exception) {
// Log.e(TAG, format("Server error while processing command %s: %s", action, exception.toString()));
// return new Response(Response.Status.INTERNAL_ERROR, PLAIN_TEXT, exception.getMessage());
// }
// }
// }
// Path: server/src/main/java/com/amplify/honeydew_server/TestRunner.java
import android.util.Log;
import android.view.KeyEvent;
import com.amplify.honeydew_server.httpd.RemoteCommandReceiver;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
package com.amplify.honeydew_server;
public class TestRunner extends UiAutomatorTestCase {
private static final String TAG = TestRunner.class.getSimpleName();
public void testRemoteLoop() throws Exception {
Log.d(TAG, "Starting honeydew-server...");
UiDevice uiDevice = getUiDevice();
uiDevice.wakeUp();
unlockEmulator();
| RemoteCommandReceiver remoteCommandReceiver = new RemoteCommandReceiver(new ActionsExecutor(uiDevice)); |
amplify-education/honeydew | server/src/main/java/com/amplify/honeydew_server/actions/InspectOptionInSettingsMenu.java | // Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
| import android.widget.TextView;
import com.amplify.honeydew_server.Result;
import com.android.uiautomator.core.*;
import java.util.*; | package com.amplify.honeydew_server.actions;
public abstract class InspectOptionInSettingsMenu extends SelectMenuInSettings {
private Boolean enabled;
public InspectOptionInSettingsMenu(UiDevice uiDevice, boolean enabled) {
super(uiDevice);
this.enabled = enabled;
}
@Override | // Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
// Path: server/src/main/java/com/amplify/honeydew_server/actions/InspectOptionInSettingsMenu.java
import android.widget.TextView;
import com.amplify.honeydew_server.Result;
import com.android.uiautomator.core.*;
import java.util.*;
package com.amplify.honeydew_server.actions;
public abstract class InspectOptionInSettingsMenu extends SelectMenuInSettings {
private Boolean enabled;
public InspectOptionInSettingsMenu(UiDevice uiDevice, boolean enabled) {
super(uiDevice);
this.enabled = enabled;
}
@Override | public Result execute(Map<String, Object> arguments) throws UiObjectNotFoundException { |
amplify-education/honeydew | server/src/main/java/com/amplify/honeydew_server/actions/IsTextGone.java | // Path: server/src/main/java/com/amplify/honeydew_server/Action.java
// public abstract class Action {
// protected final UiDevice uiDevice;
//
// protected final String TAG = getClass().getSimpleName();
//
// public Action(UiDevice uiDevice) {
// this.uiDevice = uiDevice;
// }
//
// public abstract Result execute(Map<String, Object> arguments) throws UiObjectNotFoundException;
//
// public String name() {
// return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, getClass().getSimpleName());
// }
//
// protected UiDevice getUiDevice() {
// return uiDevice;
// }
//
// private long getTimeoutInMs(Map<String, Object> arguments){
// return Integer.parseInt((String) arguments.get("timeout")) * 1000;
// }
//
// protected boolean isUiObjectAvailable(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitForExists(getTimeoutInMs(arguments));
// }
//
// protected boolean isUiObjectGone(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitUntilGone(getTimeoutInMs(arguments));
// }
//
// protected UiObject getUiObject(Map<String, Object> arguments) {
// ViewSelector viewSelector = getViewSelector(arguments);
// return viewSelector.find();
// }
//
// protected ViewSelector getViewSelector(Map<String, Object> arguments) {
// ViewSelector viewSelector = new ViewSelector();
//
// Log.d(TAG, arguments.toString());
// if (arguments.containsKey("type")) {
// Log.d(TAG, String.format("Type %s", (String) arguments.get("type")));
// viewSelector.withType((String) arguments.get("type"));
// }
// if (arguments.containsKey("text")) {
// Log.d(TAG, String.format("Text %s", (String) arguments.get("text")));
// viewSelector.withText((String) arguments.get("text"));
// }
// if (arguments.containsKey("description")) {
// Log.d(TAG, String.format("Description %s", (String) arguments.get("description")));
// viewSelector.withDescription((String) arguments.get("description"));
// }
// if (arguments.containsKey("regex")) {
// Log.d(TAG, String.format("Regular Expression %s", (String) arguments.get("regex")));
// viewSelector.withRegexMatch((String) arguments.get("regex"));
// }
// return viewSelector;
// }
//
// public static class ViewSelector {
// private UiSelector uiSelector = new UiSelector();
//
// public ViewSelector withType(String type) {
// uiSelector = uiSelector.className("android.widget." + type);
// return this;
// }
//
// public ViewSelector withText(String text) {
// uiSelector = uiSelector.textContains(text);
// return this;
// }
//
// public ViewSelector withDescription(String description) {
// uiSelector = uiSelector.description(description);
// return this;
// }
//
// public ViewSelector withRegexMatch(String regexString) {
// uiSelector = uiSelector.textMatches(regexString);
// return this;
// }
//
// public UiObject find() {
// return new UiObject(uiSelector);
// }
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
| import com.amplify.honeydew_server.Action;
import com.amplify.honeydew_server.Result;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObjectNotFoundException;
import java.util.Map; | package com.amplify.honeydew_server.actions;
public class IsTextGone extends Action {
public IsTextGone(UiDevice uiDevice) {
super(uiDevice);
}
@Override | // Path: server/src/main/java/com/amplify/honeydew_server/Action.java
// public abstract class Action {
// protected final UiDevice uiDevice;
//
// protected final String TAG = getClass().getSimpleName();
//
// public Action(UiDevice uiDevice) {
// this.uiDevice = uiDevice;
// }
//
// public abstract Result execute(Map<String, Object> arguments) throws UiObjectNotFoundException;
//
// public String name() {
// return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, getClass().getSimpleName());
// }
//
// protected UiDevice getUiDevice() {
// return uiDevice;
// }
//
// private long getTimeoutInMs(Map<String, Object> arguments){
// return Integer.parseInt((String) arguments.get("timeout")) * 1000;
// }
//
// protected boolean isUiObjectAvailable(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitForExists(getTimeoutInMs(arguments));
// }
//
// protected boolean isUiObjectGone(UiObject uiObject, Map<String, Object> arguments){
// return uiObject.waitUntilGone(getTimeoutInMs(arguments));
// }
//
// protected UiObject getUiObject(Map<String, Object> arguments) {
// ViewSelector viewSelector = getViewSelector(arguments);
// return viewSelector.find();
// }
//
// protected ViewSelector getViewSelector(Map<String, Object> arguments) {
// ViewSelector viewSelector = new ViewSelector();
//
// Log.d(TAG, arguments.toString());
// if (arguments.containsKey("type")) {
// Log.d(TAG, String.format("Type %s", (String) arguments.get("type")));
// viewSelector.withType((String) arguments.get("type"));
// }
// if (arguments.containsKey("text")) {
// Log.d(TAG, String.format("Text %s", (String) arguments.get("text")));
// viewSelector.withText((String) arguments.get("text"));
// }
// if (arguments.containsKey("description")) {
// Log.d(TAG, String.format("Description %s", (String) arguments.get("description")));
// viewSelector.withDescription((String) arguments.get("description"));
// }
// if (arguments.containsKey("regex")) {
// Log.d(TAG, String.format("Regular Expression %s", (String) arguments.get("regex")));
// viewSelector.withRegexMatch((String) arguments.get("regex"));
// }
// return viewSelector;
// }
//
// public static class ViewSelector {
// private UiSelector uiSelector = new UiSelector();
//
// public ViewSelector withType(String type) {
// uiSelector = uiSelector.className("android.widget." + type);
// return this;
// }
//
// public ViewSelector withText(String text) {
// uiSelector = uiSelector.textContains(text);
// return this;
// }
//
// public ViewSelector withDescription(String description) {
// uiSelector = uiSelector.description(description);
// return this;
// }
//
// public ViewSelector withRegexMatch(String regexString) {
// uiSelector = uiSelector.textMatches(regexString);
// return this;
// }
//
// public UiObject find() {
// return new UiObject(uiSelector);
// }
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
// Path: server/src/main/java/com/amplify/honeydew_server/actions/IsTextGone.java
import com.amplify.honeydew_server.Action;
import com.amplify.honeydew_server.Result;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObjectNotFoundException;
import java.util.Map;
package com.amplify.honeydew_server.actions;
public class IsTextGone extends Action {
public IsTextGone(UiDevice uiDevice) {
super(uiDevice);
}
@Override | public Result execute(Map<String, Object> arguments) throws UiObjectNotFoundException { |
amplify-education/honeydew | server/src/main/java/com/amplify/honeydew_server/httpd/RemoteCommandReceiver.java | // Path: server/src/main/java/com/amplify/honeydew_server/ActionsExecutor.java
// public class ActionsExecutor {
//
// protected final UiDevice uiDevice;
// private final Map<String, Action> actions;
// private static final String TAG = ActionsExecutor.class.getName();
//
// public ActionsExecutor(UiDevice uiDevice) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
// this.uiDevice = uiDevice;
// actions = newHashMap();
// for (Class<? extends Action> actionClass : allActionClasses()) {
// Constructor<? extends Action> constructor = actionClass.getConstructor(UiDevice.class);
// Action action = constructor.newInstance(this.uiDevice);
// Log.d(TAG, String.format("Registering action: %s", action.name()));
// actions.put(action.name(), action);
// }
// }
//
// public Result execute(Command command) {
// String actionName = command.getAction();
// try {
// Action action = actions.get(actionName);
// if (action == null) {
// return new Result("Action: " + actionName + " does not exist");
// }
// return executeWithStopwatch(command, action);
// } catch (Exception e) {
// return new Result("Exception, on calling " + actionName, e);
// }
// }
//
// private Result executeWithStopwatch(Command command, Action action) throws UiObjectNotFoundException {
// Stopwatch timer = new Stopwatch().start();
//
// Result result = action.execute(command.getArguments());
//
// timer.stop();
// Log.i(TAG, String.format("action '%s' took %d ms to execute on the tablet",
// command.getAction(), timer.elapsed(MILLISECONDS)));
// return result;
// }
//
// private static Set<Class<? extends Action>> allActionClasses() {
// Set<Class<? extends Action>> actionClasses = newHashSet();
// actionClasses.add(LaunchApp.class);
// actionClasses.add(LaunchHome.class);
// actionClasses.add(PressBack.class);
// actionClasses.add(PressEnter.class);
// actionClasses.add(WakeUp.class);
// actionClasses.add(Sleep.class);
// actionClasses.add(IsTextPresent.class);
// actionClasses.add(IsTextGone.class);
// actionClasses.add(IsRegexMatchPresent.class);
// actionClasses.add(IsButtonPresent.class);
// actionClasses.add(IsElementWithNestedTextPresent.class);
// actionClasses.add(IsChildCountEqualTo.class);
// actionClasses.add(IsChildCountGreaterThan.class);
// actionClasses.add(Click.class);
// actionClasses.add(ClickAndWaitForNewWindow.class);
// actionClasses.add(LongClick.class);
// actionClasses.add(SetText.class);
// actionClasses.add(SetTextByLabel.class);
// actionClasses.add(SetTextByIndex.class);
// actionClasses.add(DumpWindowHierarchy.class);
// actionClasses.add(SelectMenuInSettings.class);
// actionClasses.add(IsOptionInSettingsMenuEnabled.class);
// actionClasses.add(IsOptionInSettingsMenuDisabled.class);
// actionClasses.add(HasSettingsMenuItem.class);
// actionClasses.add(SelectFromAppsList.class);
// actionClasses.add(Unlock.class);
// actionClasses.add(ScrollToTextByIndex.class);
// return actionClasses;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Command.java
// public class Command {
// private String action;
// private Map<String, Object> arguments;
//
// public Command(String action, Map<String, Object> arguments) {
// this.action = action;
// this.arguments = arguments;
// }
//
// public String getAction() {
// return action;
// }
//
// public Map<String, Object> getArguments() {
// return arguments;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
| import android.util.Log;
import com.amplify.honeydew_server.ActionsExecutor;
import com.amplify.honeydew_server.Command;
import com.amplify.honeydew_server.Result;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import fi.iki.elonen.NanoHTTPD;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
import static java.lang.String.format; | package com.amplify.honeydew_server.httpd;
public class RemoteCommandReceiver extends NanoHTTPD {
private static final String PLAIN_TEXT = "plain/text";
public static final Type ARGUMENTS_COLLECTION_TYPE = new TypeToken<Map<String, Object>>() {
}.getType(); | // Path: server/src/main/java/com/amplify/honeydew_server/ActionsExecutor.java
// public class ActionsExecutor {
//
// protected final UiDevice uiDevice;
// private final Map<String, Action> actions;
// private static final String TAG = ActionsExecutor.class.getName();
//
// public ActionsExecutor(UiDevice uiDevice) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
// this.uiDevice = uiDevice;
// actions = newHashMap();
// for (Class<? extends Action> actionClass : allActionClasses()) {
// Constructor<? extends Action> constructor = actionClass.getConstructor(UiDevice.class);
// Action action = constructor.newInstance(this.uiDevice);
// Log.d(TAG, String.format("Registering action: %s", action.name()));
// actions.put(action.name(), action);
// }
// }
//
// public Result execute(Command command) {
// String actionName = command.getAction();
// try {
// Action action = actions.get(actionName);
// if (action == null) {
// return new Result("Action: " + actionName + " does not exist");
// }
// return executeWithStopwatch(command, action);
// } catch (Exception e) {
// return new Result("Exception, on calling " + actionName, e);
// }
// }
//
// private Result executeWithStopwatch(Command command, Action action) throws UiObjectNotFoundException {
// Stopwatch timer = new Stopwatch().start();
//
// Result result = action.execute(command.getArguments());
//
// timer.stop();
// Log.i(TAG, String.format("action '%s' took %d ms to execute on the tablet",
// command.getAction(), timer.elapsed(MILLISECONDS)));
// return result;
// }
//
// private static Set<Class<? extends Action>> allActionClasses() {
// Set<Class<? extends Action>> actionClasses = newHashSet();
// actionClasses.add(LaunchApp.class);
// actionClasses.add(LaunchHome.class);
// actionClasses.add(PressBack.class);
// actionClasses.add(PressEnter.class);
// actionClasses.add(WakeUp.class);
// actionClasses.add(Sleep.class);
// actionClasses.add(IsTextPresent.class);
// actionClasses.add(IsTextGone.class);
// actionClasses.add(IsRegexMatchPresent.class);
// actionClasses.add(IsButtonPresent.class);
// actionClasses.add(IsElementWithNestedTextPresent.class);
// actionClasses.add(IsChildCountEqualTo.class);
// actionClasses.add(IsChildCountGreaterThan.class);
// actionClasses.add(Click.class);
// actionClasses.add(ClickAndWaitForNewWindow.class);
// actionClasses.add(LongClick.class);
// actionClasses.add(SetText.class);
// actionClasses.add(SetTextByLabel.class);
// actionClasses.add(SetTextByIndex.class);
// actionClasses.add(DumpWindowHierarchy.class);
// actionClasses.add(SelectMenuInSettings.class);
// actionClasses.add(IsOptionInSettingsMenuEnabled.class);
// actionClasses.add(IsOptionInSettingsMenuDisabled.class);
// actionClasses.add(HasSettingsMenuItem.class);
// actionClasses.add(SelectFromAppsList.class);
// actionClasses.add(Unlock.class);
// actionClasses.add(ScrollToTextByIndex.class);
// return actionClasses;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Command.java
// public class Command {
// private String action;
// private Map<String, Object> arguments;
//
// public Command(String action, Map<String, Object> arguments) {
// this.action = action;
// this.arguments = arguments;
// }
//
// public String getAction() {
// return action;
// }
//
// public Map<String, Object> getArguments() {
// return arguments;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
// Path: server/src/main/java/com/amplify/honeydew_server/httpd/RemoteCommandReceiver.java
import android.util.Log;
import com.amplify.honeydew_server.ActionsExecutor;
import com.amplify.honeydew_server.Command;
import com.amplify.honeydew_server.Result;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import fi.iki.elonen.NanoHTTPD;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
import static java.lang.String.format;
package com.amplify.honeydew_server.httpd;
public class RemoteCommandReceiver extends NanoHTTPD {
private static final String PLAIN_TEXT = "plain/text";
public static final Type ARGUMENTS_COLLECTION_TYPE = new TypeToken<Map<String, Object>>() {
}.getType(); | private final ActionsExecutor actionsExecutor; |
amplify-education/honeydew | server/src/main/java/com/amplify/honeydew_server/httpd/RemoteCommandReceiver.java | // Path: server/src/main/java/com/amplify/honeydew_server/ActionsExecutor.java
// public class ActionsExecutor {
//
// protected final UiDevice uiDevice;
// private final Map<String, Action> actions;
// private static final String TAG = ActionsExecutor.class.getName();
//
// public ActionsExecutor(UiDevice uiDevice) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
// this.uiDevice = uiDevice;
// actions = newHashMap();
// for (Class<? extends Action> actionClass : allActionClasses()) {
// Constructor<? extends Action> constructor = actionClass.getConstructor(UiDevice.class);
// Action action = constructor.newInstance(this.uiDevice);
// Log.d(TAG, String.format("Registering action: %s", action.name()));
// actions.put(action.name(), action);
// }
// }
//
// public Result execute(Command command) {
// String actionName = command.getAction();
// try {
// Action action = actions.get(actionName);
// if (action == null) {
// return new Result("Action: " + actionName + " does not exist");
// }
// return executeWithStopwatch(command, action);
// } catch (Exception e) {
// return new Result("Exception, on calling " + actionName, e);
// }
// }
//
// private Result executeWithStopwatch(Command command, Action action) throws UiObjectNotFoundException {
// Stopwatch timer = new Stopwatch().start();
//
// Result result = action.execute(command.getArguments());
//
// timer.stop();
// Log.i(TAG, String.format("action '%s' took %d ms to execute on the tablet",
// command.getAction(), timer.elapsed(MILLISECONDS)));
// return result;
// }
//
// private static Set<Class<? extends Action>> allActionClasses() {
// Set<Class<? extends Action>> actionClasses = newHashSet();
// actionClasses.add(LaunchApp.class);
// actionClasses.add(LaunchHome.class);
// actionClasses.add(PressBack.class);
// actionClasses.add(PressEnter.class);
// actionClasses.add(WakeUp.class);
// actionClasses.add(Sleep.class);
// actionClasses.add(IsTextPresent.class);
// actionClasses.add(IsTextGone.class);
// actionClasses.add(IsRegexMatchPresent.class);
// actionClasses.add(IsButtonPresent.class);
// actionClasses.add(IsElementWithNestedTextPresent.class);
// actionClasses.add(IsChildCountEqualTo.class);
// actionClasses.add(IsChildCountGreaterThan.class);
// actionClasses.add(Click.class);
// actionClasses.add(ClickAndWaitForNewWindow.class);
// actionClasses.add(LongClick.class);
// actionClasses.add(SetText.class);
// actionClasses.add(SetTextByLabel.class);
// actionClasses.add(SetTextByIndex.class);
// actionClasses.add(DumpWindowHierarchy.class);
// actionClasses.add(SelectMenuInSettings.class);
// actionClasses.add(IsOptionInSettingsMenuEnabled.class);
// actionClasses.add(IsOptionInSettingsMenuDisabled.class);
// actionClasses.add(HasSettingsMenuItem.class);
// actionClasses.add(SelectFromAppsList.class);
// actionClasses.add(Unlock.class);
// actionClasses.add(ScrollToTextByIndex.class);
// return actionClasses;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Command.java
// public class Command {
// private String action;
// private Map<String, Object> arguments;
//
// public Command(String action, Map<String, Object> arguments) {
// this.action = action;
// this.arguments = arguments;
// }
//
// public String getAction() {
// return action;
// }
//
// public Map<String, Object> getArguments() {
// return arguments;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
| import android.util.Log;
import com.amplify.honeydew_server.ActionsExecutor;
import com.amplify.honeydew_server.Command;
import com.amplify.honeydew_server.Result;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import fi.iki.elonen.NanoHTTPD;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
import static java.lang.String.format; | return terminate();
}
if (method == Method.POST && uri.equalsIgnoreCase("/command")) {
return performCommand(params);
}
if (method == Method.GET && uri.equalsIgnoreCase("/status")) {
return status();
}
return BAD_REQUEST;
}
private Response status() {
Log.d(TAG, "Got status request, responding OK");
return OK;
}
private Response terminate() {
Log.d(TAG, "Got terminate request, finishing up...");
stop();
return TERMINATED;
}
private Response performCommand(Map<String, String> params) {
String action = params.get("action");
String argumentJson = params.get("arguments");
Map<String, Object> arguments = jsonParser.fromJson(argumentJson, ARGUMENTS_COLLECTION_TYPE);
Log.i(TAG, format("Performing action %s: %s for %s", action, argumentJson, params.toString()));
try { | // Path: server/src/main/java/com/amplify/honeydew_server/ActionsExecutor.java
// public class ActionsExecutor {
//
// protected final UiDevice uiDevice;
// private final Map<String, Action> actions;
// private static final String TAG = ActionsExecutor.class.getName();
//
// public ActionsExecutor(UiDevice uiDevice) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
// this.uiDevice = uiDevice;
// actions = newHashMap();
// for (Class<? extends Action> actionClass : allActionClasses()) {
// Constructor<? extends Action> constructor = actionClass.getConstructor(UiDevice.class);
// Action action = constructor.newInstance(this.uiDevice);
// Log.d(TAG, String.format("Registering action: %s", action.name()));
// actions.put(action.name(), action);
// }
// }
//
// public Result execute(Command command) {
// String actionName = command.getAction();
// try {
// Action action = actions.get(actionName);
// if (action == null) {
// return new Result("Action: " + actionName + " does not exist");
// }
// return executeWithStopwatch(command, action);
// } catch (Exception e) {
// return new Result("Exception, on calling " + actionName, e);
// }
// }
//
// private Result executeWithStopwatch(Command command, Action action) throws UiObjectNotFoundException {
// Stopwatch timer = new Stopwatch().start();
//
// Result result = action.execute(command.getArguments());
//
// timer.stop();
// Log.i(TAG, String.format("action '%s' took %d ms to execute on the tablet",
// command.getAction(), timer.elapsed(MILLISECONDS)));
// return result;
// }
//
// private static Set<Class<? extends Action>> allActionClasses() {
// Set<Class<? extends Action>> actionClasses = newHashSet();
// actionClasses.add(LaunchApp.class);
// actionClasses.add(LaunchHome.class);
// actionClasses.add(PressBack.class);
// actionClasses.add(PressEnter.class);
// actionClasses.add(WakeUp.class);
// actionClasses.add(Sleep.class);
// actionClasses.add(IsTextPresent.class);
// actionClasses.add(IsTextGone.class);
// actionClasses.add(IsRegexMatchPresent.class);
// actionClasses.add(IsButtonPresent.class);
// actionClasses.add(IsElementWithNestedTextPresent.class);
// actionClasses.add(IsChildCountEqualTo.class);
// actionClasses.add(IsChildCountGreaterThan.class);
// actionClasses.add(Click.class);
// actionClasses.add(ClickAndWaitForNewWindow.class);
// actionClasses.add(LongClick.class);
// actionClasses.add(SetText.class);
// actionClasses.add(SetTextByLabel.class);
// actionClasses.add(SetTextByIndex.class);
// actionClasses.add(DumpWindowHierarchy.class);
// actionClasses.add(SelectMenuInSettings.class);
// actionClasses.add(IsOptionInSettingsMenuEnabled.class);
// actionClasses.add(IsOptionInSettingsMenuDisabled.class);
// actionClasses.add(HasSettingsMenuItem.class);
// actionClasses.add(SelectFromAppsList.class);
// actionClasses.add(Unlock.class);
// actionClasses.add(ScrollToTextByIndex.class);
// return actionClasses;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Command.java
// public class Command {
// private String action;
// private Map<String, Object> arguments;
//
// public Command(String action, Map<String, Object> arguments) {
// this.action = action;
// this.arguments = arguments;
// }
//
// public String getAction() {
// return action;
// }
//
// public Map<String, Object> getArguments() {
// return arguments;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
// Path: server/src/main/java/com/amplify/honeydew_server/httpd/RemoteCommandReceiver.java
import android.util.Log;
import com.amplify.honeydew_server.ActionsExecutor;
import com.amplify.honeydew_server.Command;
import com.amplify.honeydew_server.Result;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import fi.iki.elonen.NanoHTTPD;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
import static java.lang.String.format;
return terminate();
}
if (method == Method.POST && uri.equalsIgnoreCase("/command")) {
return performCommand(params);
}
if (method == Method.GET && uri.equalsIgnoreCase("/status")) {
return status();
}
return BAD_REQUEST;
}
private Response status() {
Log.d(TAG, "Got status request, responding OK");
return OK;
}
private Response terminate() {
Log.d(TAG, "Got terminate request, finishing up...");
stop();
return TERMINATED;
}
private Response performCommand(Map<String, String> params) {
String action = params.get("action");
String argumentJson = params.get("arguments");
Map<String, Object> arguments = jsonParser.fromJson(argumentJson, ARGUMENTS_COLLECTION_TYPE);
Log.i(TAG, format("Performing action %s: %s for %s", action, argumentJson, params.toString()));
try { | Result result = actionsExecutor.execute(new Command(action, arguments)); |
amplify-education/honeydew | server/src/main/java/com/amplify/honeydew_server/httpd/RemoteCommandReceiver.java | // Path: server/src/main/java/com/amplify/honeydew_server/ActionsExecutor.java
// public class ActionsExecutor {
//
// protected final UiDevice uiDevice;
// private final Map<String, Action> actions;
// private static final String TAG = ActionsExecutor.class.getName();
//
// public ActionsExecutor(UiDevice uiDevice) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
// this.uiDevice = uiDevice;
// actions = newHashMap();
// for (Class<? extends Action> actionClass : allActionClasses()) {
// Constructor<? extends Action> constructor = actionClass.getConstructor(UiDevice.class);
// Action action = constructor.newInstance(this.uiDevice);
// Log.d(TAG, String.format("Registering action: %s", action.name()));
// actions.put(action.name(), action);
// }
// }
//
// public Result execute(Command command) {
// String actionName = command.getAction();
// try {
// Action action = actions.get(actionName);
// if (action == null) {
// return new Result("Action: " + actionName + " does not exist");
// }
// return executeWithStopwatch(command, action);
// } catch (Exception e) {
// return new Result("Exception, on calling " + actionName, e);
// }
// }
//
// private Result executeWithStopwatch(Command command, Action action) throws UiObjectNotFoundException {
// Stopwatch timer = new Stopwatch().start();
//
// Result result = action.execute(command.getArguments());
//
// timer.stop();
// Log.i(TAG, String.format("action '%s' took %d ms to execute on the tablet",
// command.getAction(), timer.elapsed(MILLISECONDS)));
// return result;
// }
//
// private static Set<Class<? extends Action>> allActionClasses() {
// Set<Class<? extends Action>> actionClasses = newHashSet();
// actionClasses.add(LaunchApp.class);
// actionClasses.add(LaunchHome.class);
// actionClasses.add(PressBack.class);
// actionClasses.add(PressEnter.class);
// actionClasses.add(WakeUp.class);
// actionClasses.add(Sleep.class);
// actionClasses.add(IsTextPresent.class);
// actionClasses.add(IsTextGone.class);
// actionClasses.add(IsRegexMatchPresent.class);
// actionClasses.add(IsButtonPresent.class);
// actionClasses.add(IsElementWithNestedTextPresent.class);
// actionClasses.add(IsChildCountEqualTo.class);
// actionClasses.add(IsChildCountGreaterThan.class);
// actionClasses.add(Click.class);
// actionClasses.add(ClickAndWaitForNewWindow.class);
// actionClasses.add(LongClick.class);
// actionClasses.add(SetText.class);
// actionClasses.add(SetTextByLabel.class);
// actionClasses.add(SetTextByIndex.class);
// actionClasses.add(DumpWindowHierarchy.class);
// actionClasses.add(SelectMenuInSettings.class);
// actionClasses.add(IsOptionInSettingsMenuEnabled.class);
// actionClasses.add(IsOptionInSettingsMenuDisabled.class);
// actionClasses.add(HasSettingsMenuItem.class);
// actionClasses.add(SelectFromAppsList.class);
// actionClasses.add(Unlock.class);
// actionClasses.add(ScrollToTextByIndex.class);
// return actionClasses;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Command.java
// public class Command {
// private String action;
// private Map<String, Object> arguments;
//
// public Command(String action, Map<String, Object> arguments) {
// this.action = action;
// this.arguments = arguments;
// }
//
// public String getAction() {
// return action;
// }
//
// public Map<String, Object> getArguments() {
// return arguments;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
| import android.util.Log;
import com.amplify.honeydew_server.ActionsExecutor;
import com.amplify.honeydew_server.Command;
import com.amplify.honeydew_server.Result;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import fi.iki.elonen.NanoHTTPD;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
import static java.lang.String.format; | return terminate();
}
if (method == Method.POST && uri.equalsIgnoreCase("/command")) {
return performCommand(params);
}
if (method == Method.GET && uri.equalsIgnoreCase("/status")) {
return status();
}
return BAD_REQUEST;
}
private Response status() {
Log.d(TAG, "Got status request, responding OK");
return OK;
}
private Response terminate() {
Log.d(TAG, "Got terminate request, finishing up...");
stop();
return TERMINATED;
}
private Response performCommand(Map<String, String> params) {
String action = params.get("action");
String argumentJson = params.get("arguments");
Map<String, Object> arguments = jsonParser.fromJson(argumentJson, ARGUMENTS_COLLECTION_TYPE);
Log.i(TAG, format("Performing action %s: %s for %s", action, argumentJson, params.toString()));
try { | // Path: server/src/main/java/com/amplify/honeydew_server/ActionsExecutor.java
// public class ActionsExecutor {
//
// protected final UiDevice uiDevice;
// private final Map<String, Action> actions;
// private static final String TAG = ActionsExecutor.class.getName();
//
// public ActionsExecutor(UiDevice uiDevice) throws IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException {
// this.uiDevice = uiDevice;
// actions = newHashMap();
// for (Class<? extends Action> actionClass : allActionClasses()) {
// Constructor<? extends Action> constructor = actionClass.getConstructor(UiDevice.class);
// Action action = constructor.newInstance(this.uiDevice);
// Log.d(TAG, String.format("Registering action: %s", action.name()));
// actions.put(action.name(), action);
// }
// }
//
// public Result execute(Command command) {
// String actionName = command.getAction();
// try {
// Action action = actions.get(actionName);
// if (action == null) {
// return new Result("Action: " + actionName + " does not exist");
// }
// return executeWithStopwatch(command, action);
// } catch (Exception e) {
// return new Result("Exception, on calling " + actionName, e);
// }
// }
//
// private Result executeWithStopwatch(Command command, Action action) throws UiObjectNotFoundException {
// Stopwatch timer = new Stopwatch().start();
//
// Result result = action.execute(command.getArguments());
//
// timer.stop();
// Log.i(TAG, String.format("action '%s' took %d ms to execute on the tablet",
// command.getAction(), timer.elapsed(MILLISECONDS)));
// return result;
// }
//
// private static Set<Class<? extends Action>> allActionClasses() {
// Set<Class<? extends Action>> actionClasses = newHashSet();
// actionClasses.add(LaunchApp.class);
// actionClasses.add(LaunchHome.class);
// actionClasses.add(PressBack.class);
// actionClasses.add(PressEnter.class);
// actionClasses.add(WakeUp.class);
// actionClasses.add(Sleep.class);
// actionClasses.add(IsTextPresent.class);
// actionClasses.add(IsTextGone.class);
// actionClasses.add(IsRegexMatchPresent.class);
// actionClasses.add(IsButtonPresent.class);
// actionClasses.add(IsElementWithNestedTextPresent.class);
// actionClasses.add(IsChildCountEqualTo.class);
// actionClasses.add(IsChildCountGreaterThan.class);
// actionClasses.add(Click.class);
// actionClasses.add(ClickAndWaitForNewWindow.class);
// actionClasses.add(LongClick.class);
// actionClasses.add(SetText.class);
// actionClasses.add(SetTextByLabel.class);
// actionClasses.add(SetTextByIndex.class);
// actionClasses.add(DumpWindowHierarchy.class);
// actionClasses.add(SelectMenuInSettings.class);
// actionClasses.add(IsOptionInSettingsMenuEnabled.class);
// actionClasses.add(IsOptionInSettingsMenuDisabled.class);
// actionClasses.add(HasSettingsMenuItem.class);
// actionClasses.add(SelectFromAppsList.class);
// actionClasses.add(Unlock.class);
// actionClasses.add(ScrollToTextByIndex.class);
// return actionClasses;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Command.java
// public class Command {
// private String action;
// private Map<String, Object> arguments;
//
// public Command(String action, Map<String, Object> arguments) {
// this.action = action;
// this.arguments = arguments;
// }
//
// public String getAction() {
// return action;
// }
//
// public Map<String, Object> getArguments() {
// return arguments;
// }
// }
//
// Path: server/src/main/java/com/amplify/honeydew_server/Result.java
// public class Result {
// public final boolean success;
// public String description;
// public String errorMessage;
// public String stackTrace;
//
// public static Result OK = new Result();
// public static Result FAILURE = new Result(false);
//
// public Result() {
// this(true);
// }
//
// public Result(boolean success) {
// this(success, success ? "Success!" : "Failure.");
// }
//
// public Result(boolean success, String description) {
// this.success = success;
// this.description = description;
// }
//
// public Result(String errorMessage, Throwable exception) {
// this(errorMessage);
// this.stackTrace = ExceptionUtils.getFullStackTrace(exception);
// }
//
// public Result(String errorMessage) {
// this.success = false;
// this.errorMessage = errorMessage;
// }
// }
// Path: server/src/main/java/com/amplify/honeydew_server/httpd/RemoteCommandReceiver.java
import android.util.Log;
import com.amplify.honeydew_server.ActionsExecutor;
import com.amplify.honeydew_server.Command;
import com.amplify.honeydew_server.Result;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import fi.iki.elonen.NanoHTTPD;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;
import static java.lang.String.format;
return terminate();
}
if (method == Method.POST && uri.equalsIgnoreCase("/command")) {
return performCommand(params);
}
if (method == Method.GET && uri.equalsIgnoreCase("/status")) {
return status();
}
return BAD_REQUEST;
}
private Response status() {
Log.d(TAG, "Got status request, responding OK");
return OK;
}
private Response terminate() {
Log.d(TAG, "Got terminate request, finishing up...");
stop();
return TERMINATED;
}
private Response performCommand(Map<String, String> params) {
String action = params.get("action");
String argumentJson = params.get("arguments");
Map<String, Object> arguments = jsonParser.fromJson(argumentJson, ARGUMENTS_COLLECTION_TYPE);
Log.i(TAG, format("Performing action %s: %s for %s", action, argumentJson, params.toString()));
try { | Result result = actionsExecutor.execute(new Command(action, arguments)); |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/SecurityConfig.java | // Path: lolibox-server/src/main/java/io/loli/box/dao/JpaReMemberMeRepository.java
// public interface JpaReMemberMeRepository extends JpaRepository<PersistentLogins, String>, PersistentTokenRepository {
//
// @Modifying
// @Transactional
// default void createNewToken(PersistentRememberMeToken token) {
// PersistentLogins logins = new PersistentLogins();
// logins.setLastUsed(token.getDate());
// logins.setSeries(token.getSeries());
// logins.setToken(token.getTokenValue());
// logins.setUsername(token.getUsername());
// this.save(logins);
// }
//
// @Modifying
// @Transactional
// default void updateToken(String series, String tokenValue, Date lastUsed) {
// updateTokenAndLastUsedBySeries(tokenValue, lastUsed, series);
// }
//
// @Query("update PersistentLogins set token=?, lastUsed=? where series=?")
// @Modifying
// public int updateTokenAndLastUsedBySeries(String token, Date lastUsed, String series);
//
// public List<PersistentLogins> findBySeries(String series);
//
// default PersistentRememberMeToken getTokenForSeries(String seriesId) {
// List<PersistentLogins> logins = this.findBySeries(seriesId);
// if (logins.isEmpty()) {
// return null;
// }
// PersistentLogins login = logins.get(0);
// return new PersistentRememberMeToken(login.getUsername(), login.getSeries(), login.getToken(), login.getLastUsed());
// }
//
// @Modifying
// public int deleteByUsername(String username);
//
// @Transactional
// default void removeUserTokens(String username){
// this.deleteByUsername(username);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java
// @Component
// public class RepositoryUserDetailsService implements UserDetailsService {
//
// private UserRepository repository;
//
// @Autowired
// public RepositoryUserDetailsService(UserRepository repository) {
// this.repository = repository;
// }
//
// @Autowired
// private AdminProperties adminProperties;
//
// @Override
// public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
// User user = repository.findByEmail(email);
// if (user == null) {
// user = repository.findByUserName(email);
// }
//
// if (user == null) {
// throw new UsernameNotFoundException("No user found with username: " + email);
// }
//
// SocialUserDetails.Builder builder = SocialUserDetails.getBuilder()
// .id(user.getId())
// .password(user.getPassword())
// .role(user.getRole());
// if (adminProperties.getEmail() != null && adminProperties.getEmail().equals(user.getEmail())) {
// builder = builder.role(Role.ADMIN);
// }
//
//
// SocialUserDetails principal = builder.socialSignInProvider(user.getSignInProvider())
// .username(user.getUserName())
// .email(user.getEmail())
// .build();
//
// return principal;
// }
// }
| import io.loli.box.dao.JpaReMemberMeRepository;
import io.loli.box.entity.Role;
import io.loli.box.social.RepositoryUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; | package io.loli.box;
/**
* @author choco
*/
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(6)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests(); | // Path: lolibox-server/src/main/java/io/loli/box/dao/JpaReMemberMeRepository.java
// public interface JpaReMemberMeRepository extends JpaRepository<PersistentLogins, String>, PersistentTokenRepository {
//
// @Modifying
// @Transactional
// default void createNewToken(PersistentRememberMeToken token) {
// PersistentLogins logins = new PersistentLogins();
// logins.setLastUsed(token.getDate());
// logins.setSeries(token.getSeries());
// logins.setToken(token.getTokenValue());
// logins.setUsername(token.getUsername());
// this.save(logins);
// }
//
// @Modifying
// @Transactional
// default void updateToken(String series, String tokenValue, Date lastUsed) {
// updateTokenAndLastUsedBySeries(tokenValue, lastUsed, series);
// }
//
// @Query("update PersistentLogins set token=?, lastUsed=? where series=?")
// @Modifying
// public int updateTokenAndLastUsedBySeries(String token, Date lastUsed, String series);
//
// public List<PersistentLogins> findBySeries(String series);
//
// default PersistentRememberMeToken getTokenForSeries(String seriesId) {
// List<PersistentLogins> logins = this.findBySeries(seriesId);
// if (logins.isEmpty()) {
// return null;
// }
// PersistentLogins login = logins.get(0);
// return new PersistentRememberMeToken(login.getUsername(), login.getSeries(), login.getToken(), login.getLastUsed());
// }
//
// @Modifying
// public int deleteByUsername(String username);
//
// @Transactional
// default void removeUserTokens(String username){
// this.deleteByUsername(username);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java
// @Component
// public class RepositoryUserDetailsService implements UserDetailsService {
//
// private UserRepository repository;
//
// @Autowired
// public RepositoryUserDetailsService(UserRepository repository) {
// this.repository = repository;
// }
//
// @Autowired
// private AdminProperties adminProperties;
//
// @Override
// public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
// User user = repository.findByEmail(email);
// if (user == null) {
// user = repository.findByUserName(email);
// }
//
// if (user == null) {
// throw new UsernameNotFoundException("No user found with username: " + email);
// }
//
// SocialUserDetails.Builder builder = SocialUserDetails.getBuilder()
// .id(user.getId())
// .password(user.getPassword())
// .role(user.getRole());
// if (adminProperties.getEmail() != null && adminProperties.getEmail().equals(user.getEmail())) {
// builder = builder.role(Role.ADMIN);
// }
//
//
// SocialUserDetails principal = builder.socialSignInProvider(user.getSignInProvider())
// .username(user.getUserName())
// .email(user.getEmail())
// .build();
//
// return principal;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/SecurityConfig.java
import io.loli.box.dao.JpaReMemberMeRepository;
import io.loli.box.entity.Role;
import io.loli.box.social.RepositoryUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
package io.loli.box;
/**
* @author choco
*/
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(6)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests(); | registry.antMatchers("/admin/**").hasAuthority(Role.ADMIN.toString()) |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/SecurityConfig.java | // Path: lolibox-server/src/main/java/io/loli/box/dao/JpaReMemberMeRepository.java
// public interface JpaReMemberMeRepository extends JpaRepository<PersistentLogins, String>, PersistentTokenRepository {
//
// @Modifying
// @Transactional
// default void createNewToken(PersistentRememberMeToken token) {
// PersistentLogins logins = new PersistentLogins();
// logins.setLastUsed(token.getDate());
// logins.setSeries(token.getSeries());
// logins.setToken(token.getTokenValue());
// logins.setUsername(token.getUsername());
// this.save(logins);
// }
//
// @Modifying
// @Transactional
// default void updateToken(String series, String tokenValue, Date lastUsed) {
// updateTokenAndLastUsedBySeries(tokenValue, lastUsed, series);
// }
//
// @Query("update PersistentLogins set token=?, lastUsed=? where series=?")
// @Modifying
// public int updateTokenAndLastUsedBySeries(String token, Date lastUsed, String series);
//
// public List<PersistentLogins> findBySeries(String series);
//
// default PersistentRememberMeToken getTokenForSeries(String seriesId) {
// List<PersistentLogins> logins = this.findBySeries(seriesId);
// if (logins.isEmpty()) {
// return null;
// }
// PersistentLogins login = logins.get(0);
// return new PersistentRememberMeToken(login.getUsername(), login.getSeries(), login.getToken(), login.getLastUsed());
// }
//
// @Modifying
// public int deleteByUsername(String username);
//
// @Transactional
// default void removeUserTokens(String username){
// this.deleteByUsername(username);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java
// @Component
// public class RepositoryUserDetailsService implements UserDetailsService {
//
// private UserRepository repository;
//
// @Autowired
// public RepositoryUserDetailsService(UserRepository repository) {
// this.repository = repository;
// }
//
// @Autowired
// private AdminProperties adminProperties;
//
// @Override
// public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
// User user = repository.findByEmail(email);
// if (user == null) {
// user = repository.findByUserName(email);
// }
//
// if (user == null) {
// throw new UsernameNotFoundException("No user found with username: " + email);
// }
//
// SocialUserDetails.Builder builder = SocialUserDetails.getBuilder()
// .id(user.getId())
// .password(user.getPassword())
// .role(user.getRole());
// if (adminProperties.getEmail() != null && adminProperties.getEmail().equals(user.getEmail())) {
// builder = builder.role(Role.ADMIN);
// }
//
//
// SocialUserDetails principal = builder.socialSignInProvider(user.getSignInProvider())
// .username(user.getUserName())
// .email(user.getEmail())
// .build();
//
// return principal;
// }
// }
| import io.loli.box.dao.JpaReMemberMeRepository;
import io.loli.box.entity.Role;
import io.loli.box.social.RepositoryUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; | package io.loli.box;
/**
* @author choco
*/
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(6)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
registry.antMatchers("/admin/**").hasAuthority(Role.ADMIN.toString())
.antMatchers("/image/**").permitAll()
// .antMatchers("/webjars/**").permitAll()
// .antMatchers("/js/**").permitAll()
// .antMatchers("/css/**").permitAll()
// .antMatchers("/img/**").permitAll()
.and().formLogin().loginPage("/signin").defaultSuccessUrl("/").permitAll()
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
.and().csrf().ignoringAntMatchers("/admin/**"/*,"/oauth*//**"*/);
http.headers().frameOptions().disable().and()
.rememberMe().tokenRepository(reMemberMeRepository);
}
@Autowired | // Path: lolibox-server/src/main/java/io/loli/box/dao/JpaReMemberMeRepository.java
// public interface JpaReMemberMeRepository extends JpaRepository<PersistentLogins, String>, PersistentTokenRepository {
//
// @Modifying
// @Transactional
// default void createNewToken(PersistentRememberMeToken token) {
// PersistentLogins logins = new PersistentLogins();
// logins.setLastUsed(token.getDate());
// logins.setSeries(token.getSeries());
// logins.setToken(token.getTokenValue());
// logins.setUsername(token.getUsername());
// this.save(logins);
// }
//
// @Modifying
// @Transactional
// default void updateToken(String series, String tokenValue, Date lastUsed) {
// updateTokenAndLastUsedBySeries(tokenValue, lastUsed, series);
// }
//
// @Query("update PersistentLogins set token=?, lastUsed=? where series=?")
// @Modifying
// public int updateTokenAndLastUsedBySeries(String token, Date lastUsed, String series);
//
// public List<PersistentLogins> findBySeries(String series);
//
// default PersistentRememberMeToken getTokenForSeries(String seriesId) {
// List<PersistentLogins> logins = this.findBySeries(seriesId);
// if (logins.isEmpty()) {
// return null;
// }
// PersistentLogins login = logins.get(0);
// return new PersistentRememberMeToken(login.getUsername(), login.getSeries(), login.getToken(), login.getLastUsed());
// }
//
// @Modifying
// public int deleteByUsername(String username);
//
// @Transactional
// default void removeUserTokens(String username){
// this.deleteByUsername(username);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java
// @Component
// public class RepositoryUserDetailsService implements UserDetailsService {
//
// private UserRepository repository;
//
// @Autowired
// public RepositoryUserDetailsService(UserRepository repository) {
// this.repository = repository;
// }
//
// @Autowired
// private AdminProperties adminProperties;
//
// @Override
// public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
// User user = repository.findByEmail(email);
// if (user == null) {
// user = repository.findByUserName(email);
// }
//
// if (user == null) {
// throw new UsernameNotFoundException("No user found with username: " + email);
// }
//
// SocialUserDetails.Builder builder = SocialUserDetails.getBuilder()
// .id(user.getId())
// .password(user.getPassword())
// .role(user.getRole());
// if (adminProperties.getEmail() != null && adminProperties.getEmail().equals(user.getEmail())) {
// builder = builder.role(Role.ADMIN);
// }
//
//
// SocialUserDetails principal = builder.socialSignInProvider(user.getSignInProvider())
// .username(user.getUserName())
// .email(user.getEmail())
// .build();
//
// return principal;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/SecurityConfig.java
import io.loli.box.dao.JpaReMemberMeRepository;
import io.loli.box.entity.Role;
import io.loli.box.social.RepositoryUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
package io.loli.box;
/**
* @author choco
*/
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(6)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
registry.antMatchers("/admin/**").hasAuthority(Role.ADMIN.toString())
.antMatchers("/image/**").permitAll()
// .antMatchers("/webjars/**").permitAll()
// .antMatchers("/js/**").permitAll()
// .antMatchers("/css/**").permitAll()
// .antMatchers("/img/**").permitAll()
.and().formLogin().loginPage("/signin").defaultSuccessUrl("/").permitAll()
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
.and().csrf().ignoringAntMatchers("/admin/**"/*,"/oauth*//**"*/);
http.headers().frameOptions().disable().and()
.rememberMe().tokenRepository(reMemberMeRepository);
}
@Autowired | private JpaReMemberMeRepository reMemberMeRepository; |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/SecurityConfig.java | // Path: lolibox-server/src/main/java/io/loli/box/dao/JpaReMemberMeRepository.java
// public interface JpaReMemberMeRepository extends JpaRepository<PersistentLogins, String>, PersistentTokenRepository {
//
// @Modifying
// @Transactional
// default void createNewToken(PersistentRememberMeToken token) {
// PersistentLogins logins = new PersistentLogins();
// logins.setLastUsed(token.getDate());
// logins.setSeries(token.getSeries());
// logins.setToken(token.getTokenValue());
// logins.setUsername(token.getUsername());
// this.save(logins);
// }
//
// @Modifying
// @Transactional
// default void updateToken(String series, String tokenValue, Date lastUsed) {
// updateTokenAndLastUsedBySeries(tokenValue, lastUsed, series);
// }
//
// @Query("update PersistentLogins set token=?, lastUsed=? where series=?")
// @Modifying
// public int updateTokenAndLastUsedBySeries(String token, Date lastUsed, String series);
//
// public List<PersistentLogins> findBySeries(String series);
//
// default PersistentRememberMeToken getTokenForSeries(String seriesId) {
// List<PersistentLogins> logins = this.findBySeries(seriesId);
// if (logins.isEmpty()) {
// return null;
// }
// PersistentLogins login = logins.get(0);
// return new PersistentRememberMeToken(login.getUsername(), login.getSeries(), login.getToken(), login.getLastUsed());
// }
//
// @Modifying
// public int deleteByUsername(String username);
//
// @Transactional
// default void removeUserTokens(String username){
// this.deleteByUsername(username);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java
// @Component
// public class RepositoryUserDetailsService implements UserDetailsService {
//
// private UserRepository repository;
//
// @Autowired
// public RepositoryUserDetailsService(UserRepository repository) {
// this.repository = repository;
// }
//
// @Autowired
// private AdminProperties adminProperties;
//
// @Override
// public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
// User user = repository.findByEmail(email);
// if (user == null) {
// user = repository.findByUserName(email);
// }
//
// if (user == null) {
// throw new UsernameNotFoundException("No user found with username: " + email);
// }
//
// SocialUserDetails.Builder builder = SocialUserDetails.getBuilder()
// .id(user.getId())
// .password(user.getPassword())
// .role(user.getRole());
// if (adminProperties.getEmail() != null && adminProperties.getEmail().equals(user.getEmail())) {
// builder = builder.role(Role.ADMIN);
// }
//
//
// SocialUserDetails principal = builder.socialSignInProvider(user.getSignInProvider())
// .username(user.getUserName())
// .email(user.getEmail())
// .build();
//
// return principal;
// }
// }
| import io.loli.box.dao.JpaReMemberMeRepository;
import io.loli.box.entity.Role;
import io.loli.box.social.RepositoryUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; | .and().formLogin().loginPage("/signin").defaultSuccessUrl("/").permitAll()
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
.and().csrf().ignoringAntMatchers("/admin/**"/*,"/oauth*//**"*/);
http.headers().frameOptions().disable().and()
.rememberMe().tokenRepository(reMemberMeRepository);
}
@Autowired
private JpaReMemberMeRepository reMemberMeRepository;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authProvider());
}
@Autowired | // Path: lolibox-server/src/main/java/io/loli/box/dao/JpaReMemberMeRepository.java
// public interface JpaReMemberMeRepository extends JpaRepository<PersistentLogins, String>, PersistentTokenRepository {
//
// @Modifying
// @Transactional
// default void createNewToken(PersistentRememberMeToken token) {
// PersistentLogins logins = new PersistentLogins();
// logins.setLastUsed(token.getDate());
// logins.setSeries(token.getSeries());
// logins.setToken(token.getTokenValue());
// logins.setUsername(token.getUsername());
// this.save(logins);
// }
//
// @Modifying
// @Transactional
// default void updateToken(String series, String tokenValue, Date lastUsed) {
// updateTokenAndLastUsedBySeries(tokenValue, lastUsed, series);
// }
//
// @Query("update PersistentLogins set token=?, lastUsed=? where series=?")
// @Modifying
// public int updateTokenAndLastUsedBySeries(String token, Date lastUsed, String series);
//
// public List<PersistentLogins> findBySeries(String series);
//
// default PersistentRememberMeToken getTokenForSeries(String seriesId) {
// List<PersistentLogins> logins = this.findBySeries(seriesId);
// if (logins.isEmpty()) {
// return null;
// }
// PersistentLogins login = logins.get(0);
// return new PersistentRememberMeToken(login.getUsername(), login.getSeries(), login.getToken(), login.getLastUsed());
// }
//
// @Modifying
// public int deleteByUsername(String username);
//
// @Transactional
// default void removeUserTokens(String username){
// this.deleteByUsername(username);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java
// @Component
// public class RepositoryUserDetailsService implements UserDetailsService {
//
// private UserRepository repository;
//
// @Autowired
// public RepositoryUserDetailsService(UserRepository repository) {
// this.repository = repository;
// }
//
// @Autowired
// private AdminProperties adminProperties;
//
// @Override
// public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
// User user = repository.findByEmail(email);
// if (user == null) {
// user = repository.findByUserName(email);
// }
//
// if (user == null) {
// throw new UsernameNotFoundException("No user found with username: " + email);
// }
//
// SocialUserDetails.Builder builder = SocialUserDetails.getBuilder()
// .id(user.getId())
// .password(user.getPassword())
// .role(user.getRole());
// if (adminProperties.getEmail() != null && adminProperties.getEmail().equals(user.getEmail())) {
// builder = builder.role(Role.ADMIN);
// }
//
//
// SocialUserDetails principal = builder.socialSignInProvider(user.getSignInProvider())
// .username(user.getUserName())
// .email(user.getEmail())
// .build();
//
// return principal;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/SecurityConfig.java
import io.loli.box.dao.JpaReMemberMeRepository;
import io.loli.box.entity.Role;
import io.loli.box.social.RepositoryUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
.and().formLogin().loginPage("/signin").defaultSuccessUrl("/").permitAll()
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll()
.and().csrf().ignoringAntMatchers("/admin/**"/*,"/oauth*//**"*/);
http.headers().frameOptions().disable().and()
.rememberMe().tokenRepository(reMemberMeRepository);
}
@Autowired
private JpaReMemberMeRepository reMemberMeRepository;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
auth.authenticationProvider(authProvider());
}
@Autowired | private RepositoryUserDetailsService userDetailsService; |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/service/impl/BaiduStorageService.java | // Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
| import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.ObjectMetadata;
import com.baidubce.services.bos.model.PutObjectResponse;
import io.loli.box.service.AbstractStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream; | package io.loli.box.service.impl;
/**
* @author choco
*/
@Component
@ConditionalOnProperty(name = "storage.type", havingValue = "baidu")
@ConfigurationProperties(prefix = "storage.baidu") | // Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/service/impl/BaiduStorageService.java
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.ObjectMetadata;
import com.baidubce.services.bos.model.PutObjectResponse;
import io.loli.box.service.AbstractStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
package io.loli.box.service.impl;
/**
* @author choco
*/
@Component
@ConditionalOnProperty(name = "storage.type", havingValue = "baidu")
@ConfigurationProperties(prefix = "storage.baidu") | public class BaiduStorageService extends AbstractStorageService { |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/service/impl/UserService.java | // Path: lolibox-server/src/main/java/io/loli/box/exception/UserExistsException.java
// public class UserExistsException extends Exception {
// public UserExistsException() {
// super();
// }
//
// public UserExistsException(String reason) {
// super(reason);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
| import io.loli.box.exception.UserExistsException;
import io.loli.box.entity.User;
import io.loli.box.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional; | package io.loli.box.service.impl;
/**
* @author choco
*/
@Service
public class UserService {
@Autowired | // Path: lolibox-server/src/main/java/io/loli/box/exception/UserExistsException.java
// public class UserExistsException extends Exception {
// public UserExistsException() {
// super();
// }
//
// public UserExistsException(String reason) {
// super(reason);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
// Path: lolibox-server/src/main/java/io/loli/box/service/impl/UserService.java
import io.loli.box.exception.UserExistsException;
import io.loli.box.entity.User;
import io.loli.box.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
package io.loli.box.service.impl;
/**
* @author choco
*/
@Service
public class UserService {
@Autowired | private UserRepository userRepository; |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/service/impl/UserService.java | // Path: lolibox-server/src/main/java/io/loli/box/exception/UserExistsException.java
// public class UserExistsException extends Exception {
// public UserExistsException() {
// super();
// }
//
// public UserExistsException(String reason) {
// super(reason);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
| import io.loli.box.exception.UserExistsException;
import io.loli.box.entity.User;
import io.loli.box.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional; | package io.loli.box.service.impl;
/**
* @author choco
*/
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional | // Path: lolibox-server/src/main/java/io/loli/box/exception/UserExistsException.java
// public class UserExistsException extends Exception {
// public UserExistsException() {
// super();
// }
//
// public UserExistsException(String reason) {
// super(reason);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
// Path: lolibox-server/src/main/java/io/loli/box/service/impl/UserService.java
import io.loli.box.exception.UserExistsException;
import io.loli.box.entity.User;
import io.loli.box.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
package io.loli.box.service.impl;
/**
* @author choco
*/
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional | public User registerNewUser(User user) throws UserExistsException { |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/service/impl/UserService.java | // Path: lolibox-server/src/main/java/io/loli/box/exception/UserExistsException.java
// public class UserExistsException extends Exception {
// public UserExistsException() {
// super();
// }
//
// public UserExistsException(String reason) {
// super(reason);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
| import io.loli.box.exception.UserExistsException;
import io.loli.box.entity.User;
import io.loli.box.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional; | package io.loli.box.service.impl;
/**
* @author choco
*/
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional | // Path: lolibox-server/src/main/java/io/loli/box/exception/UserExistsException.java
// public class UserExistsException extends Exception {
// public UserExistsException() {
// super();
// }
//
// public UserExistsException(String reason) {
// super(reason);
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
// Path: lolibox-server/src/main/java/io/loli/box/service/impl/UserService.java
import io.loli.box.exception.UserExistsException;
import io.loli.box.entity.User;
import io.loli.box.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
package io.loli.box.service.impl;
/**
* @author choco
*/
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional | public User registerNewUser(User user) throws UserExistsException { |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/oauth2/AuthorizationServerConfiguration.java | // Path: lolibox-server/src/main/java/io/loli/box/util/FinalValueHolder.java
// public class FinalValueHolder<T> {
// private T value;
//
// public FinalValueHolder(T t) {
// this.value = t;
// }
//
// public T getValue() {
// return value;
// }
//
// public void setValue(T value) {
// this.value = value;
// }
// }
| import io.loli.box.util.FinalValueHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.builders.ClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.builders.JdbcClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import javax.sql.DataSource;
import java.util.List; | package io.loli.box.oauth2;
/**
* @author choco
*/
@Configuration
@EnableAuthorizationServer
@Order(3)
@EntityScan("io.loli.box.oauth2")
@ConfigurationProperties(prefix = "oauth2")
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
private static final Log logger = LogFactory
.getLog(AuthorizationServerConfiguration.class);
private List<OauthClient> clients;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired(required = false)
private TokenStore tokenStore;
@Autowired
private DataSource ds;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// TODO Add JPA Builder
JdbcClientDetailsServiceBuilder builder = clients
.jdbc(ds);
if (this.clients != null) { | // Path: lolibox-server/src/main/java/io/loli/box/util/FinalValueHolder.java
// public class FinalValueHolder<T> {
// private T value;
//
// public FinalValueHolder(T t) {
// this.value = t;
// }
//
// public T getValue() {
// return value;
// }
//
// public void setValue(T value) {
// this.value = value;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/oauth2/AuthorizationServerConfiguration.java
import io.loli.box.util.FinalValueHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.builders.ClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.builders.JdbcClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import javax.sql.DataSource;
import java.util.List;
package io.loli.box.oauth2;
/**
* @author choco
*/
@Configuration
@EnableAuthorizationServer
@Order(3)
@EntityScan("io.loli.box.oauth2")
@ConfigurationProperties(prefix = "oauth2")
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
private static final Log logger = LogFactory
.getLog(AuthorizationServerConfiguration.class);
private List<OauthClient> clients;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired(required = false)
private TokenStore tokenStore;
@Autowired
private DataSource ds;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// TODO Add JPA Builder
JdbcClientDetailsServiceBuilder builder = clients
.jdbc(ds);
if (this.clients != null) { | FinalValueHolder<ClientDetailsServiceBuilder> detailHolder = new FinalValueHolder<>(builder); |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/green/AliGreenConfiguration.java | // Path: lolibox-server/src/main/java/io/loli/box/dao/ImgFileRepository.java
// public interface ImgFileRepository extends JpaRepository<ImgFile, Long> {
// public ImgFile save(ImgFile file);
//
// int deleteByShortName(String name);
//
// ImgFile findByShortName(String name);
//
// @Transactional
// @Modifying
// @Query("update ImgFile u set u.delete=?2 where u.shortName=?1")
// void updateDeleteByShortName(String name, boolean i);
//
// Page<ImgFile> findByUserIdOrderByCreateDateDesc(Long userId, Pageable pageable);
//
// @Query(value = "select f.* " +
// "from img_file f " +
// "left join user_accounts u " +
// "on f.user_id = u.id " +
// "where u.id = ?1 and f.deleted = ?2 " +
// "order by f.create_date desc /*#pageable*/",
// countQuery = "select count(f.*) " +
// "from img_file f " +
// "left join user_accounts u " +
// "on f.user_id = u.id " +
// "where u.id = ?1 and f.deleted = ?2 ", nativeQuery = true)
// Page<ImgFile> findByUserIdAndDeleteOrderByCreateDate(Long userId, Boolean delete, Pageable pageable);
//
// List<ImgFile> findByGreenStatus(Integer greenStatus, Date from, Date end);
//
//
// @Transactional
// @Modifying
// @Query("update ImgFile u set u.greenStatus=?1 where u.id=?2")
// void updateGreenStatusById(Integer greenStatus, Long id);
//
// @Transactional
// @Modifying
// @Query("update ImgFile u set u.greenTaskId=?1 where u.id=?2")
// void updateTaskIdById(String taskId, Long id);
//
// @Transactional
// @Modifying
// @Query("update ImgFile u set u.greenPoint=?1 where u.id=?2")
// void updateGreenPointById(float checkResult, Long id);
// }
| import io.loli.box.dao.ImgFileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
| package io.loli.box.green;
/**
* Created by chocotan on 2016/8/6.
*/
@Configuration
@ConditionalOnProperty(name = "admin.green.enabled", havingValue = "aliyun")
public class AliGreenConfiguration {
@Bean
public GreenService greenService() {
return new AliGreenService();
}
@Autowired
| // Path: lolibox-server/src/main/java/io/loli/box/dao/ImgFileRepository.java
// public interface ImgFileRepository extends JpaRepository<ImgFile, Long> {
// public ImgFile save(ImgFile file);
//
// int deleteByShortName(String name);
//
// ImgFile findByShortName(String name);
//
// @Transactional
// @Modifying
// @Query("update ImgFile u set u.delete=?2 where u.shortName=?1")
// void updateDeleteByShortName(String name, boolean i);
//
// Page<ImgFile> findByUserIdOrderByCreateDateDesc(Long userId, Pageable pageable);
//
// @Query(value = "select f.* " +
// "from img_file f " +
// "left join user_accounts u " +
// "on f.user_id = u.id " +
// "where u.id = ?1 and f.deleted = ?2 " +
// "order by f.create_date desc /*#pageable*/",
// countQuery = "select count(f.*) " +
// "from img_file f " +
// "left join user_accounts u " +
// "on f.user_id = u.id " +
// "where u.id = ?1 and f.deleted = ?2 ", nativeQuery = true)
// Page<ImgFile> findByUserIdAndDeleteOrderByCreateDate(Long userId, Boolean delete, Pageable pageable);
//
// List<ImgFile> findByGreenStatus(Integer greenStatus, Date from, Date end);
//
//
// @Transactional
// @Modifying
// @Query("update ImgFile u set u.greenStatus=?1 where u.id=?2")
// void updateGreenStatusById(Integer greenStatus, Long id);
//
// @Transactional
// @Modifying
// @Query("update ImgFile u set u.greenTaskId=?1 where u.id=?2")
// void updateTaskIdById(String taskId, Long id);
//
// @Transactional
// @Modifying
// @Query("update ImgFile u set u.greenPoint=?1 where u.id=?2")
// void updateGreenPointById(float checkResult, Long id);
// }
// Path: lolibox-server/src/main/java/io/loli/box/green/AliGreenConfiguration.java
import io.loli.box.dao.ImgFileRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
package io.loli.box.green;
/**
* Created by chocotan on 2016/8/6.
*/
@Configuration
@ConditionalOnProperty(name = "admin.green.enabled", havingValue = "aliyun")
public class AliGreenConfiguration {
@Bean
public GreenService greenService() {
return new AliGreenService();
}
@Autowired
| ImgFileRepository imgFileRepository;
|
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java | // Path: lolibox-server/src/main/java/io/loli/box/AdminProperties.java
// @ConfigurationProperties("admin")
// @Component
// public class AdminProperties {
// @NotNull
// private String email;
//
// private boolean anonymous = false;
//
// private boolean signupInvitation = true;
//
// private Integer invitationLimitDays = 7;
//
// private String imgHost;
// private String cdnHost;
//
// private String httpsHost;
//
// public String getHttpsHost() {
// return httpsHost;
// }
//
// public void setHttpsHost(String httpsHost) {
// this.httpsHost = httpsHost;
// }
//
// public boolean isAnonymous() {
// return anonymous;
// }
//
// public void setAnonymous(boolean anonymous) {
// this.anonymous = anonymous;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
//
// public boolean isSignupInvitation() {
// return signupInvitation;
// }
//
// public void setSignupInvitation(boolean signupInvitation) {
// this.signupInvitation = signupInvitation;
// }
//
// public Integer getInvitationLimitDays() {
// return invitationLimitDays;
// }
//
// public void setInvitationLimitDays(Integer invitationLimitDays) {
// this.invitationLimitDays = invitationLimitDays;
// }
//
// public String getCdnHost() {
// return cdnHost;
// }
//
// public void setCdnHost(String cdnHost) {
// this.cdnHost = cdnHost;
// }
//
// public String getImgHost() {
// return imgHost;
// }
//
// public void setImgHost(String imgHost) {
// this.imgHost = imgHost;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
| import io.loli.box.AdminProperties;
import io.loli.box.dao.UserRepository;
import io.loli.box.entity.Role;
import io.loli.box.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component; | package io.loli.box.social;
@Component
public class RepositoryUserDetailsService implements UserDetailsService {
| // Path: lolibox-server/src/main/java/io/loli/box/AdminProperties.java
// @ConfigurationProperties("admin")
// @Component
// public class AdminProperties {
// @NotNull
// private String email;
//
// private boolean anonymous = false;
//
// private boolean signupInvitation = true;
//
// private Integer invitationLimitDays = 7;
//
// private String imgHost;
// private String cdnHost;
//
// private String httpsHost;
//
// public String getHttpsHost() {
// return httpsHost;
// }
//
// public void setHttpsHost(String httpsHost) {
// this.httpsHost = httpsHost;
// }
//
// public boolean isAnonymous() {
// return anonymous;
// }
//
// public void setAnonymous(boolean anonymous) {
// this.anonymous = anonymous;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
//
// public boolean isSignupInvitation() {
// return signupInvitation;
// }
//
// public void setSignupInvitation(boolean signupInvitation) {
// this.signupInvitation = signupInvitation;
// }
//
// public Integer getInvitationLimitDays() {
// return invitationLimitDays;
// }
//
// public void setInvitationLimitDays(Integer invitationLimitDays) {
// this.invitationLimitDays = invitationLimitDays;
// }
//
// public String getCdnHost() {
// return cdnHost;
// }
//
// public void setCdnHost(String cdnHost) {
// this.cdnHost = cdnHost;
// }
//
// public String getImgHost() {
// return imgHost;
// }
//
// public void setImgHost(String imgHost) {
// this.imgHost = imgHost;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java
import io.loli.box.AdminProperties;
import io.loli.box.dao.UserRepository;
import io.loli.box.entity.Role;
import io.loli.box.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
package io.loli.box.social;
@Component
public class RepositoryUserDetailsService implements UserDetailsService {
| private UserRepository repository; |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java | // Path: lolibox-server/src/main/java/io/loli/box/AdminProperties.java
// @ConfigurationProperties("admin")
// @Component
// public class AdminProperties {
// @NotNull
// private String email;
//
// private boolean anonymous = false;
//
// private boolean signupInvitation = true;
//
// private Integer invitationLimitDays = 7;
//
// private String imgHost;
// private String cdnHost;
//
// private String httpsHost;
//
// public String getHttpsHost() {
// return httpsHost;
// }
//
// public void setHttpsHost(String httpsHost) {
// this.httpsHost = httpsHost;
// }
//
// public boolean isAnonymous() {
// return anonymous;
// }
//
// public void setAnonymous(boolean anonymous) {
// this.anonymous = anonymous;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
//
// public boolean isSignupInvitation() {
// return signupInvitation;
// }
//
// public void setSignupInvitation(boolean signupInvitation) {
// this.signupInvitation = signupInvitation;
// }
//
// public Integer getInvitationLimitDays() {
// return invitationLimitDays;
// }
//
// public void setInvitationLimitDays(Integer invitationLimitDays) {
// this.invitationLimitDays = invitationLimitDays;
// }
//
// public String getCdnHost() {
// return cdnHost;
// }
//
// public void setCdnHost(String cdnHost) {
// this.cdnHost = cdnHost;
// }
//
// public String getImgHost() {
// return imgHost;
// }
//
// public void setImgHost(String imgHost) {
// this.imgHost = imgHost;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
| import io.loli.box.AdminProperties;
import io.loli.box.dao.UserRepository;
import io.loli.box.entity.Role;
import io.loli.box.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component; | package io.loli.box.social;
@Component
public class RepositoryUserDetailsService implements UserDetailsService {
private UserRepository repository;
@Autowired
public RepositoryUserDetailsService(UserRepository repository) {
this.repository = repository;
}
@Autowired | // Path: lolibox-server/src/main/java/io/loli/box/AdminProperties.java
// @ConfigurationProperties("admin")
// @Component
// public class AdminProperties {
// @NotNull
// private String email;
//
// private boolean anonymous = false;
//
// private boolean signupInvitation = true;
//
// private Integer invitationLimitDays = 7;
//
// private String imgHost;
// private String cdnHost;
//
// private String httpsHost;
//
// public String getHttpsHost() {
// return httpsHost;
// }
//
// public void setHttpsHost(String httpsHost) {
// this.httpsHost = httpsHost;
// }
//
// public boolean isAnonymous() {
// return anonymous;
// }
//
// public void setAnonymous(boolean anonymous) {
// this.anonymous = anonymous;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
//
// public boolean isSignupInvitation() {
// return signupInvitation;
// }
//
// public void setSignupInvitation(boolean signupInvitation) {
// this.signupInvitation = signupInvitation;
// }
//
// public Integer getInvitationLimitDays() {
// return invitationLimitDays;
// }
//
// public void setInvitationLimitDays(Integer invitationLimitDays) {
// this.invitationLimitDays = invitationLimitDays;
// }
//
// public String getCdnHost() {
// return cdnHost;
// }
//
// public void setCdnHost(String cdnHost) {
// this.cdnHost = cdnHost;
// }
//
// public String getImgHost() {
// return imgHost;
// }
//
// public void setImgHost(String imgHost) {
// this.imgHost = imgHost;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java
import io.loli.box.AdminProperties;
import io.loli.box.dao.UserRepository;
import io.loli.box.entity.Role;
import io.loli.box.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
package io.loli.box.social;
@Component
public class RepositoryUserDetailsService implements UserDetailsService {
private UserRepository repository;
@Autowired
public RepositoryUserDetailsService(UserRepository repository) {
this.repository = repository;
}
@Autowired | private AdminProperties adminProperties; |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java | // Path: lolibox-server/src/main/java/io/loli/box/AdminProperties.java
// @ConfigurationProperties("admin")
// @Component
// public class AdminProperties {
// @NotNull
// private String email;
//
// private boolean anonymous = false;
//
// private boolean signupInvitation = true;
//
// private Integer invitationLimitDays = 7;
//
// private String imgHost;
// private String cdnHost;
//
// private String httpsHost;
//
// public String getHttpsHost() {
// return httpsHost;
// }
//
// public void setHttpsHost(String httpsHost) {
// this.httpsHost = httpsHost;
// }
//
// public boolean isAnonymous() {
// return anonymous;
// }
//
// public void setAnonymous(boolean anonymous) {
// this.anonymous = anonymous;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
//
// public boolean isSignupInvitation() {
// return signupInvitation;
// }
//
// public void setSignupInvitation(boolean signupInvitation) {
// this.signupInvitation = signupInvitation;
// }
//
// public Integer getInvitationLimitDays() {
// return invitationLimitDays;
// }
//
// public void setInvitationLimitDays(Integer invitationLimitDays) {
// this.invitationLimitDays = invitationLimitDays;
// }
//
// public String getCdnHost() {
// return cdnHost;
// }
//
// public void setCdnHost(String cdnHost) {
// this.cdnHost = cdnHost;
// }
//
// public String getImgHost() {
// return imgHost;
// }
//
// public void setImgHost(String imgHost) {
// this.imgHost = imgHost;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
| import io.loli.box.AdminProperties;
import io.loli.box.dao.UserRepository;
import io.loli.box.entity.Role;
import io.loli.box.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component; | package io.loli.box.social;
@Component
public class RepositoryUserDetailsService implements UserDetailsService {
private UserRepository repository;
@Autowired
public RepositoryUserDetailsService(UserRepository repository) {
this.repository = repository;
}
@Autowired
private AdminProperties adminProperties;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { | // Path: lolibox-server/src/main/java/io/loli/box/AdminProperties.java
// @ConfigurationProperties("admin")
// @Component
// public class AdminProperties {
// @NotNull
// private String email;
//
// private boolean anonymous = false;
//
// private boolean signupInvitation = true;
//
// private Integer invitationLimitDays = 7;
//
// private String imgHost;
// private String cdnHost;
//
// private String httpsHost;
//
// public String getHttpsHost() {
// return httpsHost;
// }
//
// public void setHttpsHost(String httpsHost) {
// this.httpsHost = httpsHost;
// }
//
// public boolean isAnonymous() {
// return anonymous;
// }
//
// public void setAnonymous(boolean anonymous) {
// this.anonymous = anonymous;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
//
// public boolean isSignupInvitation() {
// return signupInvitation;
// }
//
// public void setSignupInvitation(boolean signupInvitation) {
// this.signupInvitation = signupInvitation;
// }
//
// public Integer getInvitationLimitDays() {
// return invitationLimitDays;
// }
//
// public void setInvitationLimitDays(Integer invitationLimitDays) {
// this.invitationLimitDays = invitationLimitDays;
// }
//
// public String getCdnHost() {
// return cdnHost;
// }
//
// public void setCdnHost(String cdnHost) {
// this.cdnHost = cdnHost;
// }
//
// public String getImgHost() {
// return imgHost;
// }
//
// public void setImgHost(String imgHost) {
// this.imgHost = imgHost;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/dao/UserRepository.java
// public interface UserRepository extends JpaRepository<User, Long> {
//
// public User findByEmail(String email);
//
// public User findByUserName(String userName);
//
// User findByEmailOrUserName(String email, String name);
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/social/RepositoryUserDetailsService.java
import io.loli.box.AdminProperties;
import io.loli.box.dao.UserRepository;
import io.loli.box.entity.Role;
import io.loli.box.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
package io.loli.box.social;
@Component
public class RepositoryUserDetailsService implements UserDetailsService {
private UserRepository repository;
@Autowired
public RepositoryUserDetailsService(UserRepository repository) {
this.repository = repository;
}
@Autowired
private AdminProperties adminProperties;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { | User user = repository.findByEmail(email); |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/controller/AdminController.java | // Path: lolibox-server/src/main/java/io/loli/box/service/StorageService.java
// public interface StorageService {
//
// /**
// * Upload an InputStream with file name
// *
// * @param is file to upload. After uploaded, file name will be changed to
// * nano time.
// * @param filename origin name of this file
// * @param contentType
// * @return A relative url str generated by storage service
// * @throws IOException Will be throwed while IO error occurred
// */
// public String upload(InputStream is, String filename, String contentType, long length) throws IOException;
//
//
// @Transactional
// public void deleteFile(String name);
//
// @Transactional
// boolean deleteFile(String name, User user);
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/util/FileBean.java
// @XmlRootElement
// public class FileBean implements Serializable {
//
// public static final long serialVersionUID = -2126687016928386103L;
//
// private long size;
// private String name;
// private String url;
// private Date lastModified;
// private boolean file;
//
// public FileBean() {
// }
//
// public FileBean(File file) {
// setName(file.getName());
// setLastModified(new Date(file.lastModified()));
// setFile(file.isFile());
// if (this.isFile()) {
// this.setSize(file.length());
// } else {
// this.setSize(0L);
// }
// }
//
// public long getSize() {
// return size;
// }
//
// public void setSize(long size) {
// this.size = size;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(Date lastModified) {
// this.lastModified = lastModified;
// }
//
// public boolean isFile() {
// return file;
// }
//
// public void setFile(boolean file) {
// this.file = file;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
| import io.loli.box.service.StorageService;
import io.loli.box.util.FileBean;
import io.loli.box.util.StatusBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Comparator; | package io.loli.box.controller;
/**
* @author choco
*/
@Controller
@RequestMapping("/admin")
public class AdminController {
@Autowired | // Path: lolibox-server/src/main/java/io/loli/box/service/StorageService.java
// public interface StorageService {
//
// /**
// * Upload an InputStream with file name
// *
// * @param is file to upload. After uploaded, file name will be changed to
// * nano time.
// * @param filename origin name of this file
// * @param contentType
// * @return A relative url str generated by storage service
// * @throws IOException Will be throwed while IO error occurred
// */
// public String upload(InputStream is, String filename, String contentType, long length) throws IOException;
//
//
// @Transactional
// public void deleteFile(String name);
//
// @Transactional
// boolean deleteFile(String name, User user);
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/util/FileBean.java
// @XmlRootElement
// public class FileBean implements Serializable {
//
// public static final long serialVersionUID = -2126687016928386103L;
//
// private long size;
// private String name;
// private String url;
// private Date lastModified;
// private boolean file;
//
// public FileBean() {
// }
//
// public FileBean(File file) {
// setName(file.getName());
// setLastModified(new Date(file.lastModified()));
// setFile(file.isFile());
// if (this.isFile()) {
// this.setSize(file.length());
// } else {
// this.setSize(0L);
// }
// }
//
// public long getSize() {
// return size;
// }
//
// public void setSize(long size) {
// this.size = size;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(Date lastModified) {
// this.lastModified = lastModified;
// }
//
// public boolean isFile() {
// return file;
// }
//
// public void setFile(boolean file) {
// this.file = file;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/controller/AdminController.java
import io.loli.box.service.StorageService;
import io.loli.box.util.FileBean;
import io.loli.box.util.StatusBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Comparator;
package io.loli.box.controller;
/**
* @author choco
*/
@Controller
@RequestMapping("/admin")
public class AdminController {
@Autowired | private StorageService ss; |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/controller/AdminController.java | // Path: lolibox-server/src/main/java/io/loli/box/service/StorageService.java
// public interface StorageService {
//
// /**
// * Upload an InputStream with file name
// *
// * @param is file to upload. After uploaded, file name will be changed to
// * nano time.
// * @param filename origin name of this file
// * @param contentType
// * @return A relative url str generated by storage service
// * @throws IOException Will be throwed while IO error occurred
// */
// public String upload(InputStream is, String filename, String contentType, long length) throws IOException;
//
//
// @Transactional
// public void deleteFile(String name);
//
// @Transactional
// boolean deleteFile(String name, User user);
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/util/FileBean.java
// @XmlRootElement
// public class FileBean implements Serializable {
//
// public static final long serialVersionUID = -2126687016928386103L;
//
// private long size;
// private String name;
// private String url;
// private Date lastModified;
// private boolean file;
//
// public FileBean() {
// }
//
// public FileBean(File file) {
// setName(file.getName());
// setLastModified(new Date(file.lastModified()));
// setFile(file.isFile());
// if (this.isFile()) {
// this.setSize(file.length());
// } else {
// this.setSize(0L);
// }
// }
//
// public long getSize() {
// return size;
// }
//
// public void setSize(long size) {
// this.size = size;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(Date lastModified) {
// this.lastModified = lastModified;
// }
//
// public boolean isFile() {
// return file;
// }
//
// public void setFile(boolean file) {
// this.file = file;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
| import io.loli.box.service.StorageService;
import io.loli.box.util.FileBean;
import io.loli.box.util.StatusBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Comparator; | package io.loli.box.controller;
/**
* @author choco
*/
@Controller
@RequestMapping("/admin")
public class AdminController {
@Autowired
private StorageService ss;
| // Path: lolibox-server/src/main/java/io/loli/box/service/StorageService.java
// public interface StorageService {
//
// /**
// * Upload an InputStream with file name
// *
// * @param is file to upload. After uploaded, file name will be changed to
// * nano time.
// * @param filename origin name of this file
// * @param contentType
// * @return A relative url str generated by storage service
// * @throws IOException Will be throwed while IO error occurred
// */
// public String upload(InputStream is, String filename, String contentType, long length) throws IOException;
//
//
// @Transactional
// public void deleteFile(String name);
//
// @Transactional
// boolean deleteFile(String name, User user);
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/util/FileBean.java
// @XmlRootElement
// public class FileBean implements Serializable {
//
// public static final long serialVersionUID = -2126687016928386103L;
//
// private long size;
// private String name;
// private String url;
// private Date lastModified;
// private boolean file;
//
// public FileBean() {
// }
//
// public FileBean(File file) {
// setName(file.getName());
// setLastModified(new Date(file.lastModified()));
// setFile(file.isFile());
// if (this.isFile()) {
// this.setSize(file.length());
// } else {
// this.setSize(0L);
// }
// }
//
// public long getSize() {
// return size;
// }
//
// public void setSize(long size) {
// this.size = size;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public Date getLastModified() {
// return lastModified;
// }
//
// public void setLastModified(Date lastModified) {
// this.lastModified = lastModified;
// }
//
// public boolean isFile() {
// return file;
// }
//
// public void setFile(boolean file) {
// this.file = file;
// }
//
// public String getUrl() {
// return url;
// }
//
// public void setUrl(String url) {
// this.url = url;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/controller/AdminController.java
import io.loli.box.service.StorageService;
import io.loli.box.util.FileBean;
import io.loli.box.util.StatusBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Comparator;
package io.loli.box.controller;
/**
* @author choco
*/
@Controller
@RequestMapping("/admin")
public class AdminController {
@Autowired
private StorageService ss;
| private static Comparator<FileBean> fileComparator = new Comparator<FileBean>() { |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/LoliboxApplication.java | // Path: lolibox-server/src/main/java/io/loli/box/oauth2/AuthorizationServerConfiguration.java
// @Configuration
// @EnableAuthorizationServer
// @Order(3)
// @EntityScan("io.loli.box.oauth2")
// @ConfigurationProperties(prefix = "oauth2")
// public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
//
// private static final Log logger = LogFactory
// .getLog(AuthorizationServerConfiguration.class);
//
//
// private List<OauthClient> clients;
//
//
// @Autowired
// private AuthenticationManager authenticationManager;
//
// @Autowired(required = false)
// private TokenStore tokenStore;
//
// @Autowired
// private DataSource ds;
//
// @Override
// public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// // TODO Add JPA Builder
// JdbcClientDetailsServiceBuilder builder = clients
// .jdbc(ds);
// if (this.clients != null) {
// FinalValueHolder<ClientDetailsServiceBuilder> detailHolder = new FinalValueHolder<>(builder);
// this.clients.forEach(c -> detailHolder.setValue(detailHolder.getValue().withClient(c.getName()).secret(c.getSecret())
// .authorizedGrantTypes("password")
// .authorities("ROLE_CLIENT")
// .scopes("read", "write")
// .resourceIds("oauth2-resource")
// .accessTokenValiditySeconds(Integer.MAX_VALUE).and()));
// }
// }
//
// @Override
// public void configure(AuthorizationServerEndpointsConfigurer endpoints)
// throws Exception {
// if (this.tokenStore != null) {
// endpoints.tokenStore(this.tokenStore);
// }
// endpoints.authenticationManager(this.authenticationManager);
// }
//
// public static class OauthClient {
// private String name;
// private String secret;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getSecret() {
// return secret;
// }
//
// public void setSecret(String secret) {
// this.secret = secret;
// }
// }
//
// public List<OauthClient> getClients() {
// return clients;
// }
//
// public void setClients(List<OauthClient> clients) {
// this.clients = clients;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/oauth2/ResourceServer.java
// @Configuration
// @EnableResourceServer
// public class ResourceServer extends ResourceServerConfigurerAdapter {
//
// @Override
// public void configure(HttpSecurity http) throws Exception {
// http.antMatcher("/image/oauthUpload")
// .authorizeRequests().anyRequest().access("#oauth2.hasScope('write')");
// }
//
// @Autowired
// private TokenStore tokenStore;
//
// @Override
// public void configure(ResourceServerSecurityConfigurer resources)
// throws Exception {
// resources.tokenStore(tokenStore);
// }
//
// }
| import io.loli.box.oauth2.AuthorizationServerConfiguration;
import io.loli.box.oauth2.ResourceServer;
import org.hashids.Hashids;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.social.config.annotation.EnableSocial;
import javax.servlet.ServletContext; | package io.loli.box;
@SpringBootApplication
@EnableZuulProxy
@EnableJpaRepositories | // Path: lolibox-server/src/main/java/io/loli/box/oauth2/AuthorizationServerConfiguration.java
// @Configuration
// @EnableAuthorizationServer
// @Order(3)
// @EntityScan("io.loli.box.oauth2")
// @ConfigurationProperties(prefix = "oauth2")
// public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
//
// private static final Log logger = LogFactory
// .getLog(AuthorizationServerConfiguration.class);
//
//
// private List<OauthClient> clients;
//
//
// @Autowired
// private AuthenticationManager authenticationManager;
//
// @Autowired(required = false)
// private TokenStore tokenStore;
//
// @Autowired
// private DataSource ds;
//
// @Override
// public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// // TODO Add JPA Builder
// JdbcClientDetailsServiceBuilder builder = clients
// .jdbc(ds);
// if (this.clients != null) {
// FinalValueHolder<ClientDetailsServiceBuilder> detailHolder = new FinalValueHolder<>(builder);
// this.clients.forEach(c -> detailHolder.setValue(detailHolder.getValue().withClient(c.getName()).secret(c.getSecret())
// .authorizedGrantTypes("password")
// .authorities("ROLE_CLIENT")
// .scopes("read", "write")
// .resourceIds("oauth2-resource")
// .accessTokenValiditySeconds(Integer.MAX_VALUE).and()));
// }
// }
//
// @Override
// public void configure(AuthorizationServerEndpointsConfigurer endpoints)
// throws Exception {
// if (this.tokenStore != null) {
// endpoints.tokenStore(this.tokenStore);
// }
// endpoints.authenticationManager(this.authenticationManager);
// }
//
// public static class OauthClient {
// private String name;
// private String secret;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getSecret() {
// return secret;
// }
//
// public void setSecret(String secret) {
// this.secret = secret;
// }
// }
//
// public List<OauthClient> getClients() {
// return clients;
// }
//
// public void setClients(List<OauthClient> clients) {
// this.clients = clients;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/oauth2/ResourceServer.java
// @Configuration
// @EnableResourceServer
// public class ResourceServer extends ResourceServerConfigurerAdapter {
//
// @Override
// public void configure(HttpSecurity http) throws Exception {
// http.antMatcher("/image/oauthUpload")
// .authorizeRequests().anyRequest().access("#oauth2.hasScope('write')");
// }
//
// @Autowired
// private TokenStore tokenStore;
//
// @Override
// public void configure(ResourceServerSecurityConfigurer resources)
// throws Exception {
// resources.tokenStore(tokenStore);
// }
//
// }
// Path: lolibox-server/src/main/java/io/loli/box/LoliboxApplication.java
import io.loli.box.oauth2.AuthorizationServerConfiguration;
import io.loli.box.oauth2.ResourceServer;
import org.hashids.Hashids;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.social.config.annotation.EnableSocial;
import javax.servlet.ServletContext;
package io.loli.box;
@SpringBootApplication
@EnableZuulProxy
@EnableJpaRepositories | @Import({MvcConfig.class, SecurityConfig.class, AuthorizationServerConfiguration.class, ResourceServer.class}) |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/LoliboxApplication.java | // Path: lolibox-server/src/main/java/io/loli/box/oauth2/AuthorizationServerConfiguration.java
// @Configuration
// @EnableAuthorizationServer
// @Order(3)
// @EntityScan("io.loli.box.oauth2")
// @ConfigurationProperties(prefix = "oauth2")
// public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
//
// private static final Log logger = LogFactory
// .getLog(AuthorizationServerConfiguration.class);
//
//
// private List<OauthClient> clients;
//
//
// @Autowired
// private AuthenticationManager authenticationManager;
//
// @Autowired(required = false)
// private TokenStore tokenStore;
//
// @Autowired
// private DataSource ds;
//
// @Override
// public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// // TODO Add JPA Builder
// JdbcClientDetailsServiceBuilder builder = clients
// .jdbc(ds);
// if (this.clients != null) {
// FinalValueHolder<ClientDetailsServiceBuilder> detailHolder = new FinalValueHolder<>(builder);
// this.clients.forEach(c -> detailHolder.setValue(detailHolder.getValue().withClient(c.getName()).secret(c.getSecret())
// .authorizedGrantTypes("password")
// .authorities("ROLE_CLIENT")
// .scopes("read", "write")
// .resourceIds("oauth2-resource")
// .accessTokenValiditySeconds(Integer.MAX_VALUE).and()));
// }
// }
//
// @Override
// public void configure(AuthorizationServerEndpointsConfigurer endpoints)
// throws Exception {
// if (this.tokenStore != null) {
// endpoints.tokenStore(this.tokenStore);
// }
// endpoints.authenticationManager(this.authenticationManager);
// }
//
// public static class OauthClient {
// private String name;
// private String secret;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getSecret() {
// return secret;
// }
//
// public void setSecret(String secret) {
// this.secret = secret;
// }
// }
//
// public List<OauthClient> getClients() {
// return clients;
// }
//
// public void setClients(List<OauthClient> clients) {
// this.clients = clients;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/oauth2/ResourceServer.java
// @Configuration
// @EnableResourceServer
// public class ResourceServer extends ResourceServerConfigurerAdapter {
//
// @Override
// public void configure(HttpSecurity http) throws Exception {
// http.antMatcher("/image/oauthUpload")
// .authorizeRequests().anyRequest().access("#oauth2.hasScope('write')");
// }
//
// @Autowired
// private TokenStore tokenStore;
//
// @Override
// public void configure(ResourceServerSecurityConfigurer resources)
// throws Exception {
// resources.tokenStore(tokenStore);
// }
//
// }
| import io.loli.box.oauth2.AuthorizationServerConfiguration;
import io.loli.box.oauth2.ResourceServer;
import org.hashids.Hashids;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.social.config.annotation.EnableSocial;
import javax.servlet.ServletContext; | package io.loli.box;
@SpringBootApplication
@EnableZuulProxy
@EnableJpaRepositories | // Path: lolibox-server/src/main/java/io/loli/box/oauth2/AuthorizationServerConfiguration.java
// @Configuration
// @EnableAuthorizationServer
// @Order(3)
// @EntityScan("io.loli.box.oauth2")
// @ConfigurationProperties(prefix = "oauth2")
// public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
//
// private static final Log logger = LogFactory
// .getLog(AuthorizationServerConfiguration.class);
//
//
// private List<OauthClient> clients;
//
//
// @Autowired
// private AuthenticationManager authenticationManager;
//
// @Autowired(required = false)
// private TokenStore tokenStore;
//
// @Autowired
// private DataSource ds;
//
// @Override
// public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// // TODO Add JPA Builder
// JdbcClientDetailsServiceBuilder builder = clients
// .jdbc(ds);
// if (this.clients != null) {
// FinalValueHolder<ClientDetailsServiceBuilder> detailHolder = new FinalValueHolder<>(builder);
// this.clients.forEach(c -> detailHolder.setValue(detailHolder.getValue().withClient(c.getName()).secret(c.getSecret())
// .authorizedGrantTypes("password")
// .authorities("ROLE_CLIENT")
// .scopes("read", "write")
// .resourceIds("oauth2-resource")
// .accessTokenValiditySeconds(Integer.MAX_VALUE).and()));
// }
// }
//
// @Override
// public void configure(AuthorizationServerEndpointsConfigurer endpoints)
// throws Exception {
// if (this.tokenStore != null) {
// endpoints.tokenStore(this.tokenStore);
// }
// endpoints.authenticationManager(this.authenticationManager);
// }
//
// public static class OauthClient {
// private String name;
// private String secret;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getSecret() {
// return secret;
// }
//
// public void setSecret(String secret) {
// this.secret = secret;
// }
// }
//
// public List<OauthClient> getClients() {
// return clients;
// }
//
// public void setClients(List<OauthClient> clients) {
// this.clients = clients;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/oauth2/ResourceServer.java
// @Configuration
// @EnableResourceServer
// public class ResourceServer extends ResourceServerConfigurerAdapter {
//
// @Override
// public void configure(HttpSecurity http) throws Exception {
// http.antMatcher("/image/oauthUpload")
// .authorizeRequests().anyRequest().access("#oauth2.hasScope('write')");
// }
//
// @Autowired
// private TokenStore tokenStore;
//
// @Override
// public void configure(ResourceServerSecurityConfigurer resources)
// throws Exception {
// resources.tokenStore(tokenStore);
// }
//
// }
// Path: lolibox-server/src/main/java/io/loli/box/LoliboxApplication.java
import io.loli.box.oauth2.AuthorizationServerConfiguration;
import io.loli.box.oauth2.ResourceServer;
import org.hashids.Hashids;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.social.config.annotation.EnableSocial;
import javax.servlet.ServletContext;
package io.loli.box;
@SpringBootApplication
@EnableZuulProxy
@EnableJpaRepositories | @Import({MvcConfig.class, SecurityConfig.class, AuthorizationServerConfiguration.class, ResourceServer.class}) |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/service/impl/FileSystemStorageService.java | // Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
| import io.loli.box.entity.User;
import io.loli.box.service.AbstractStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Calendar; | package io.loli.box.service.impl;
@Component
@ConditionalOnProperty(name = "storage.type", havingValue = "filesystem")
@ConfigurationProperties(prefix = "storage.filesystem") | // Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/service/impl/FileSystemStorageService.java
import io.loli.box.entity.User;
import io.loli.box.service.AbstractStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Calendar;
package io.loli.box.service.impl;
@Component
@ConditionalOnProperty(name = "storage.type", havingValue = "filesystem")
@ConfigurationProperties(prefix = "storage.filesystem") | public class FileSystemStorageService extends AbstractStorageService { |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/service/impl/FileSystemStorageService.java | // Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
| import io.loli.box.entity.User;
import io.loli.box.service.AbstractStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Calendar; | if (day < 10) {
dayStr = "0" + dayStr;
}
String path = year + File.separator + monthStr + File.separator
+ dayStr;
String savePath = this.imgFolder;
if (savePath.endsWith(File.separator)) {
} else {
savePath += File.separator;
}
savePath += path;
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
return path;
}
public void deleteFile(String name) {
super.deleteFile(name);
String path = this.imgFolder + File.separator + name;
File f = new File(path);
if (f.exists()) {
f.delete();
}
}
@Override | // Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
//
// Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/service/impl/FileSystemStorageService.java
import io.loli.box.entity.User;
import io.loli.box.service.AbstractStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Calendar;
if (day < 10) {
dayStr = "0" + dayStr;
}
String path = year + File.separator + monthStr + File.separator
+ dayStr;
String savePath = this.imgFolder;
if (savePath.endsWith(File.separator)) {
} else {
savePath += File.separator;
}
savePath += path;
File file = new File(savePath);
if (!file.exists()) {
file.mkdirs();
}
return path;
}
public void deleteFile(String name) {
super.deleteFile(name);
String path = this.imgFolder + File.separator + name;
File f = new File(path);
if (f.exists()) {
f.delete();
}
}
@Override | public boolean deleteFile(String name, User user) { |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/service/StorageService.java | // Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
| import io.loli.box.entity.User;
import javax.transaction.Transactional;
import java.io.IOException;
import java.io.InputStream; | package io.loli.box.service;
/**
* All storage service should implements this interface
*
* @author choco
*/
public interface StorageService {
/**
* Upload an InputStream with file name
*
* @param is file to upload. After uploaded, file name will be changed to
* nano time.
* @param filename origin name of this file
* @param contentType
* @return A relative url str generated by storage service
* @throws IOException Will be throwed while IO error occurred
*/
public String upload(InputStream is, String filename, String contentType, long length) throws IOException;
@Transactional
public void deleteFile(String name);
@Transactional | // Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
// @Entity
// @Table(name = "user_accounts")
// public class User {
//
// @Id
// @GeneratedValue(strategy = GenerationType.AUTO)
// private Long id;
//
// @Column(name = "email", length = 100, nullable = false, unique = true)
// private String email;
//
// @Column(name = "user_name", length = 100, nullable = false,unique = true)
// private String userName;
//
// @Column(name = "password", length = 255)
// private String password;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "role", length = 20, nullable = false)
// private Role role;
//
// @Enumerated(EnumType.STRING)
// @Column(name = "sign_in_provider", length = 20)
// private SocialMediaService signInProvider;
//
// @Column(name = "create_date")
// private Date createDate = new Date();
//
// public Date getCreateDate() {
// return createDate;
// }
//
// public void setCreateDate(Date createDate) {
// this.createDate = createDate;
// }
//
// public User() {
//
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public String getUserName() {
// return userName;
// }
//
// public void setUserName(String userName) {
// this.userName = userName;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public Role getRole() {
// return role;
// }
//
// public void setRole(Role role) {
// this.role = role;
// }
//
// public SocialMediaService getSignInProvider() {
// return signInProvider;
// }
//
// public void setSignInProvider(SocialMediaService signInProvider) {
// this.signInProvider = signInProvider;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/service/StorageService.java
import io.loli.box.entity.User;
import javax.transaction.Transactional;
import java.io.IOException;
import java.io.InputStream;
package io.loli.box.service;
/**
* All storage service should implements this interface
*
* @author choco
*/
public interface StorageService {
/**
* Upload an InputStream with file name
*
* @param is file to upload. After uploaded, file name will be changed to
* nano time.
* @param filename origin name of this file
* @param contentType
* @return A relative url str generated by storage service
* @throws IOException Will be throwed while IO error occurred
*/
public String upload(InputStream is, String filename, String contentType, long length) throws IOException;
@Transactional
public void deleteFile(String name);
@Transactional | boolean deleteFile(String name, User user); |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/service/impl/QiniuStorageService.java | // Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
| import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.RSClient;
import io.loli.box.service.AbstractStorageService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream; | package io.loli.box.service.impl;
/**
* @author choco
*/
@Component
@ConditionalOnProperty(name = "storage.type", havingValue = "qiniu")
@ConfigurationProperties(prefix = "storage.qiniu") | // Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/service/impl/QiniuStorageService.java
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.RSClient;
import io.loli.box.service.AbstractStorageService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
package io.loli.box.service.impl;
/**
* @author choco
*/
@Component
@ConditionalOnProperty(name = "storage.type", havingValue = "qiniu")
@ConfigurationProperties(prefix = "storage.qiniu") | public class QiniuStorageService extends AbstractStorageService { |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/service/impl/CosStorageService.java | // Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
| import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import io.loli.box.service.AbstractStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream; | package io.loli.box.service.impl;
/**
* 腾讯云cos存储服务
*/
@Component
@ConditionalOnProperty(name = "storage.type", havingValue = "cos")
@ConfigurationProperties(prefix = "storage.cos") | // Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/service/impl/CosStorageService.java
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import io.loli.box.service.AbstractStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
package io.loli.box.service.impl;
/**
* 腾讯云cos存储服务
*/
@Component
@ConditionalOnProperty(name = "storage.type", havingValue = "cos")
@ConfigurationProperties(prefix = "storage.cos") | public class CosStorageService extends AbstractStorageService { |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/service/impl/AliStorageService.java | // Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
| import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import io.loli.box.service.AbstractStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date; | package io.loli.box.service.impl;
/**
* @author choco
*/
@Component
@ConditionalOnProperty(name = "storage.type", havingValue = "aliyun")
@ConfigurationProperties(prefix = "storage.aliyun") | // Path: lolibox-server/src/main/java/io/loli/box/service/AbstractStorageService.java
// public abstract class AbstractStorageService implements StorageService {
// @Autowired
// protected ImgFileRepository imgFileRepository;
//
// public void deleteFile(String name) {
// imgFileRepository.updateDeleteByShortName(name, true);
// }
//
// @Override
// public boolean deleteFile(String name, User user) {
// ImgFile file = imgFileRepository.findByShortName(name);
// if(file.getUser().getId().equals(user.getId())) {
// return true;
// } else {
// return false;
// }
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/service/impl/AliStorageService.java
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import io.loli.box.service.AbstractStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
package io.loli.box.service.impl;
/**
* @author choco
*/
@Component
@ConditionalOnProperty(name = "storage.type", havingValue = "aliyun")
@ConfigurationProperties(prefix = "storage.aliyun") | public class AliStorageService extends AbstractStorageService { |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/entity/User.java | // Path: lolibox-server/src/main/java/io/loli/box/social/SocialMediaService.java
// public enum SocialMediaService {
// WEIBO
// }
| import io.loli.box.social.SocialMediaService;
import javax.persistence.*;
import java.util.Date; | package io.loli.box.entity;
@Entity
@Table(name = "user_accounts")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "email", length = 100, nullable = false, unique = true)
private String email;
@Column(name = "user_name", length = 100, nullable = false,unique = true)
private String userName;
@Column(name = "password", length = 255)
private String password;
@Enumerated(EnumType.STRING)
@Column(name = "role", length = 20, nullable = false)
private Role role;
@Enumerated(EnumType.STRING)
@Column(name = "sign_in_provider", length = 20) | // Path: lolibox-server/src/main/java/io/loli/box/social/SocialMediaService.java
// public enum SocialMediaService {
// WEIBO
// }
// Path: lolibox-server/src/main/java/io/loli/box/entity/User.java
import io.loli.box.social.SocialMediaService;
import javax.persistence.*;
import java.util.Date;
package io.loli.box.entity;
@Entity
@Table(name = "user_accounts")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name = "email", length = 100, nullable = false, unique = true)
private String email;
@Column(name = "user_name", length = 100, nullable = false,unique = true)
private String userName;
@Column(name = "password", length = 255)
private String password;
@Enumerated(EnumType.STRING)
@Column(name = "role", length = 20, nullable = false)
private Role role;
@Enumerated(EnumType.STRING)
@Column(name = "sign_in_provider", length = 20) | private SocialMediaService signInProvider; |
chocotan/lolibox | lolibox-server/src/main/java/io/loli/box/social/SocialUserDetails.java | // Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
| import io.loli.box.entity.Role;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.social.security.SocialUser;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set; | package io.loli.box.social;
public class SocialUserDetails extends SocialUser {
private Long id;
private String email;
| // Path: lolibox-server/src/main/java/io/loli/box/entity/Role.java
// public enum Role {
// ROLE_USER("ROLE_USER"), ADMIN("ROLE_ADMIN");
//
// private String name;
//
//
// Role(String name) {
// this.name = name;
// }
//
// @Override
// public String toString() {
// return name;
// }
// }
// Path: lolibox-server/src/main/java/io/loli/box/social/SocialUserDetails.java
import io.loli.box.entity.Role;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.social.security.SocialUser;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
package io.loli.box.social;
public class SocialUserDetails extends SocialUser {
private Long id;
private String email;
| private Role role; |
anyjava/FiveStonesGame | omok/gameServer/GameRoom.java | // Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
//
// Path: omok/protocolData/Protocol.java
// public interface Protocol extends Serializable {
//
// public short getProtocol();
// public String getName();
// public String getMessage();
// public void setMessage(String message);
// public void setName(String name);
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.Vector;
import protocolData.ChatData;
import protocolData.Protocol; | package gameServer;
public class GameRoom implements GameRoomInterface , Serializable {
private static final long serialVersionUID = 1L;
private static int roomNO = 1;
private ClientManager userList;
private int number;
private String roomName;
private StoneAlgol analysisStone;
private boolean isStart = false;
public GameRoom(String roomName, ClientManager userList) {
this.roomName = roomName;
this.userList = userList;
this.analysisStone = new StoneAlgol();
number = roomNO++;
}
| // Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
//
// Path: omok/protocolData/Protocol.java
// public interface Protocol extends Serializable {
//
// public short getProtocol();
// public String getName();
// public String getMessage();
// public void setMessage(String message);
// public void setName(String name);
// }
// Path: omok/gameServer/GameRoom.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Vector;
import protocolData.ChatData;
import protocolData.Protocol;
package gameServer;
public class GameRoom implements GameRoomInterface , Serializable {
private static final long serialVersionUID = 1L;
private static int roomNO = 1;
private ClientManager userList;
private int number;
private String roomName;
private StoneAlgol analysisStone;
private boolean isStart = false;
public GameRoom(String roomName, ClientManager userList) {
this.roomName = roomName;
this.userList = userList;
this.analysisStone = new StoneAlgol();
number = roomNO++;
}
| public void broadcasting(Protocol data) { |
anyjava/FiveStonesGame | omok/gameServer/GameRoom.java | // Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
//
// Path: omok/protocolData/Protocol.java
// public interface Protocol extends Serializable {
//
// public short getProtocol();
// public String getName();
// public String getMessage();
// public void setMessage(String message);
// public void setName(String name);
// }
| import java.io.Serializable;
import java.util.ArrayList;
import java.util.Vector;
import protocolData.ChatData;
import protocolData.Protocol; | package gameServer;
public class GameRoom implements GameRoomInterface , Serializable {
private static final long serialVersionUID = 1L;
private static int roomNO = 1;
private ClientManager userList;
private int number;
private String roomName;
private StoneAlgol analysisStone;
private boolean isStart = false;
public GameRoom(String roomName, ClientManager userList) {
this.roomName = roomName;
this.userList = userList;
this.analysisStone = new StoneAlgol();
number = roomNO++;
}
public void broadcasting(Protocol data) {
System.out.println("in broadcast : " + data);
LogFrame.print("in broadcast : " + data);
for (GameServer temp : userList.getCollection(number)) {
if (!(temp.getUserLocation() == ServerInterface.LOBBY)) {
try {
temp.sendMessage(data);
} catch (Exception e) {
userList.subUser( temp );
System.out.println( temp.getName() + "의 연결을 끊었습니다." );
}
}
}
}
| // Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
//
// Path: omok/protocolData/Protocol.java
// public interface Protocol extends Serializable {
//
// public short getProtocol();
// public String getName();
// public String getMessage();
// public void setMessage(String message);
// public void setName(String name);
// }
// Path: omok/gameServer/GameRoom.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Vector;
import protocolData.ChatData;
import protocolData.Protocol;
package gameServer;
public class GameRoom implements GameRoomInterface , Serializable {
private static final long serialVersionUID = 1L;
private static int roomNO = 1;
private ClientManager userList;
private int number;
private String roomName;
private StoneAlgol analysisStone;
private boolean isStart = false;
public GameRoom(String roomName, ClientManager userList) {
this.roomName = roomName;
this.userList = userList;
this.analysisStone = new StoneAlgol();
number = roomNO++;
}
public void broadcasting(Protocol data) {
System.out.println("in broadcast : " + data);
LogFrame.print("in broadcast : " + data);
for (GameServer temp : userList.getCollection(number)) {
if (!(temp.getUserLocation() == ServerInterface.LOBBY)) {
try {
temp.sendMessage(data);
} catch (Exception e) {
userList.subUser( temp );
System.out.println( temp.getName() + "의 연결을 끊었습니다." );
}
}
}
}
| public void sendSlip(ChatData data) { |
anyjava/FiveStonesGame | omok/gui/SlipFrame.java | // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
//
// Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
| import gameClient.ClientInterface;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import protocolData.ChatData; | package gui;
public class SlipFrame extends JFrame {
private static final long serialVersionUID = 1L;
private boolean isSend;
| // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
//
// Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
// Path: omok/gui/SlipFrame.java
import gameClient.ClientInterface;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import protocolData.ChatData;
package gui;
public class SlipFrame extends JFrame {
private static final long serialVersionUID = 1L;
private boolean isSend;
| private ClientInterface client; |
anyjava/FiveStonesGame | omok/gui/SlipFrame.java | // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
//
// Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
| import gameClient.ClientInterface;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import protocolData.ChatData; | "Cancel");
/*
* 쪽지 보낼때의 생성자.
*/
public SlipFrame(final String to, String message, boolean isSend, final ClientInterface client) {
this.to = to;
this.message = message;
this.client = client;
this.isSend = isSend;
if (isSend) { // send
this.setTitle("쪽지 보내기");
m_labelID = new JLabel("To... ");
m_inputID.setText(to);
} else {
this.setTitle("받은쪽지");
m_labelID = new JLabel("From... "); // recive
m_message.setText(message);
}
showComponent();
if (isSend) {
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
client.sendSlip(m_inputID.getText(), m_message.getText(), | // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
//
// Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
// Path: omok/gui/SlipFrame.java
import gameClient.ClientInterface;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import protocolData.ChatData;
"Cancel");
/*
* 쪽지 보낼때의 생성자.
*/
public SlipFrame(final String to, String message, boolean isSend, final ClientInterface client) {
this.to = to;
this.message = message;
this.client = client;
this.isSend = isSend;
if (isSend) { // send
this.setTitle("쪽지 보내기");
m_labelID = new JLabel("To... ");
m_inputID.setText(to);
} else {
this.setTitle("받은쪽지");
m_labelID = new JLabel("From... "); // recive
m_message.setText(message);
}
showComponent();
if (isSend) {
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
client.sendSlip(m_inputID.getText(), m_message.getText(), | ChatData.MESSAGE_SLIP); |
anyjava/FiveStonesGame | omok/gui/GameLobby.java | // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
| import gameClient.ClientInterface;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField; |
private JTextArea m_logWindow = new JTextArea(5, 20);
private JTextField m_textInput = new JTextField();
private ImageButton m_sendButton = new ImageButton("image/gameLobbySendButton.jpg", "SEND", "image/gameLobbySendButtonOver.jpg");
private JScrollPane m_scPaneLogWin;
private JScrollBar m_vScroll;
/*
* Component of Info Panel
*/
private JPanel m_infoPanel = new JPanel() {
public void paint(Graphics g) {
this.paintComponents(g);
}
};
private ImageButton m_exitButton = new ImageButton("image/gameLobbyExitButton.jpg", "나가기", "image/gameLobbyExitButtonOver.jpg");
private ImageButton m_totalUserButton = new ImageButton("image/gameTotalUserButton.jpg","Total User", "image/gameTotalUserButtonOver.jpg");
protected AbstractButton m_startButton;
/*
* 임시...
*/
private Vector<String> vc = new Vector<String>();
| // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
// Path: omok/gui/GameLobby.java
import gameClient.ClientInterface;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
private JTextArea m_logWindow = new JTextArea(5, 20);
private JTextField m_textInput = new JTextField();
private ImageButton m_sendButton = new ImageButton("image/gameLobbySendButton.jpg", "SEND", "image/gameLobbySendButtonOver.jpg");
private JScrollPane m_scPaneLogWin;
private JScrollBar m_vScroll;
/*
* Component of Info Panel
*/
private JPanel m_infoPanel = new JPanel() {
public void paint(Graphics g) {
this.paintComponents(g);
}
};
private ImageButton m_exitButton = new ImageButton("image/gameLobbyExitButton.jpg", "나가기", "image/gameLobbyExitButtonOver.jpg");
private ImageButton m_totalUserButton = new ImageButton("image/gameTotalUserButton.jpg","Total User", "image/gameTotalUserButtonOver.jpg");
protected AbstractButton m_startButton;
/*
* 임시...
*/
private Vector<String> vc = new Vector<String>();
| private ClientInterface client; |
anyjava/FiveStonesGame | omok/gui/GameRoomGui.java | // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
| import gameClient.ClientInterface;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField; | package gui;
@SuppressWarnings("serial")
public class GameRoomGui extends JPanel implements RoomGuiInter {
private UserListFrame userListFrame;
/*
* Left Panel
*/
private JLabel m_titleLabel;
private GameBoardCanvas m_board = new GameBoardCanvas();
private JTextField m_input;
private JPanel m_canvasPanel;
/*
* Right Panel
*/
private JPanel m_rightPanel;
private JTextArea m_log;
private JList m_userList;
private JLabel m_gamer1,m_gamer2;
private ImageButton m_gamerCaptin, m_gamerCrhallenger;
private ImageButton m_exitButton, m_totalUserButton;
private ImageButton m_backButton;
private JScrollPane m_logScrollPan;
private JScrollBar m_vScroll;
| // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
// Path: omok/gui/GameRoomGui.java
import gameClient.ClientInterface;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
package gui;
@SuppressWarnings("serial")
public class GameRoomGui extends JPanel implements RoomGuiInter {
private UserListFrame userListFrame;
/*
* Left Panel
*/
private JLabel m_titleLabel;
private GameBoardCanvas m_board = new GameBoardCanvas();
private JTextField m_input;
private JPanel m_canvasPanel;
/*
* Right Panel
*/
private JPanel m_rightPanel;
private JTextArea m_log;
private JList m_userList;
private JLabel m_gamer1,m_gamer2;
private ImageButton m_gamerCaptin, m_gamerCrhallenger;
private ImageButton m_exitButton, m_totalUserButton;
private ImageButton m_backButton;
private JScrollPane m_logScrollPan;
private JScrollBar m_vScroll;
| private ClientInterface client; |
anyjava/FiveStonesGame | omok/gameServer/ServerInterface.java | // Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
//
// Path: omok/protocolData/Protocol.java
// public interface Protocol extends Serializable {
//
// public short getProtocol();
// public String getName();
// public String getMessage();
// public void setMessage(String message);
// public void setName(String name);
// }
| import java.util.Vector;
import protocolData.ChatData;
import protocolData.Protocol; | package gameServer;
public interface ServerInterface {
static int LOBBY = 1;
static int IN_GAME_ROOMKING = 2;
static int IN_GAME_CRHARANGER = 3;
static int IN_GAME_VIWER = 4;
| // Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
//
// Path: omok/protocolData/Protocol.java
// public interface Protocol extends Serializable {
//
// public short getProtocol();
// public String getName();
// public String getMessage();
// public void setMessage(String message);
// public void setName(String name);
// }
// Path: omok/gameServer/ServerInterface.java
import java.util.Vector;
import protocolData.ChatData;
import protocolData.Protocol;
package gameServer;
public interface ServerInterface {
static int LOBBY = 1;
static int IN_GAME_ROOMKING = 2;
static int IN_GAME_CRHARANGER = 3;
static int IN_GAME_VIWER = 4;
| void broadcasting(Protocol data); |
anyjava/FiveStonesGame | omok/gameServer/ServerInterface.java | // Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
//
// Path: omok/protocolData/Protocol.java
// public interface Protocol extends Serializable {
//
// public short getProtocol();
// public String getName();
// public String getMessage();
// public void setMessage(String message);
// public void setName(String name);
// }
| import java.util.Vector;
import protocolData.ChatData;
import protocolData.Protocol; | package gameServer;
public interface ServerInterface {
static int LOBBY = 1;
static int IN_GAME_ROOMKING = 2;
static int IN_GAME_CRHARANGER = 3;
static int IN_GAME_VIWER = 4;
void broadcasting(Protocol data);
void subSocket(String name); | // Path: omok/protocolData/ChatData.java
// public class ChatData implements Protocol {
// public static final short ENTER = 1000;
// public static final short LOGIN_CHECK = 1100;
// public static final short LOGIN_ERROR = 1200;
// public static final short MESSAGE = 2000;
// public static final short MESSAGE_SLIP = 2100;
// public static final short EXIT = 3000;
// public static final short SEND_USER_LIST = 4000;
// public static final short SEND_TOTAL_USER = 4100;
//
// private static final long serialVersionUID = 1L;
//
// private String name = null,
// message = null;
//
// private String receiver;
//
// private short state = 0;
//
// private Vector<String> userList = null;
//
//
// public ChatData(String name, String message, short state) {
// this.name = name;
// this.message = message;
// this.state = state;
// if ( ChatData.SEND_USER_LIST == state)
// userList = new Vector<String>();
// }
//
// public ChatData(String receiverName, String name, String message, short state) {
// this(name, message, state);
// receiver = receiverName;
// }
//
// public void setMessage(String message) {
// this.message = message;
// }
//
// public short getState() {
// return state;
// }
//
// public Vector<String> getUserList() {
// return userList;
// }
//
// public String getName() {
// return name;
// }
//
// public String getMessage() {
// return message;
// }
//
// public void setUserList(Vector<String> userList) {
// this.userList = null;
// this.userList = userList;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String toString() {
// return name + " " + message + " " + state + "\n" + userList;
// }
//
// public String getReceiver() {
// return receiver;
// }
//
// public short getProtocol() {
// return state;
// }
//
// public void setProtocol(short exit) {
// state = exit;
// }
// }
//
// Path: omok/protocolData/Protocol.java
// public interface Protocol extends Serializable {
//
// public short getProtocol();
// public String getName();
// public String getMessage();
// public void setMessage(String message);
// public void setName(String name);
// }
// Path: omok/gameServer/ServerInterface.java
import java.util.Vector;
import protocolData.ChatData;
import protocolData.Protocol;
package gameServer;
public interface ServerInterface {
static int LOBBY = 1;
static int IN_GAME_ROOMKING = 2;
static int IN_GAME_CRHARANGER = 3;
static int IN_GAME_VIWER = 4;
void broadcasting(Protocol data);
void subSocket(String name); | void sendSlip(ChatData data); |
anyjava/FiveStonesGame | omok/gameServer/GameRoomInterface.java | // Path: omok/protocolData/Protocol.java
// public interface Protocol extends Serializable {
//
// public short getProtocol();
// public String getName();
// public String getMessage();
// public void setMessage(String message);
// public void setName(String name);
// }
| import protocolData.Protocol; | package gameServer;
public interface GameRoomInterface extends ServerInterface {
String getRoomName();
String getRoomKingName();
void subRoom();
int getNumber();
boolean isAllReady(); | // Path: omok/protocolData/Protocol.java
// public interface Protocol extends Serializable {
//
// public short getProtocol();
// public String getName();
// public String getMessage();
// public void setMessage(String message);
// public void setName(String name);
// }
// Path: omok/gameServer/GameRoomInterface.java
import protocolData.Protocol;
package gameServer;
public interface GameRoomInterface extends ServerInterface {
String getRoomName();
String getRoomKingName();
void subRoom();
int getNumber();
boolean isAllReady(); | void sendTo(int toGamer, Protocol data); |
anyjava/FiveStonesGame | omok/gui/RoomGuiInter.java | // Path: omok/gui/GameRoomGui.java
// class GameBoardCanvas extends Canvas {
//
// /*
// * Image Size is 590,593
// */
//
// private static final long serialVersionUID = 1L;
//
// private ArrayList<StoneHistory> historyOfStone = new ArrayList<StoneHistory>();
//
// private Toolkit toolkit = Toolkit.getDefaultToolkit();
//
// private MediaTracker tracker;
//
// private Image image, lastStone;
//
// private BufferedImage bi;
//
// private int width, height;
//
// private int[] points;
//
// private int[] lastPoint = new int[2];
//
// private StoneHistory aStoneInfo;
//
// private boolean isRedraw = false;
//
// private int whatStone = 0;
//
// public GameBoardCanvas() {
// imageLoad();
// traker();
//
// /*
// * Mouse Click! Event catch!!
// *
// */
// addMouseListener(new MouseAdapter() {
// public void mouseClicked(MouseEvent e) {
// int[] point = new int[2];
//
// if ((16 < e.getX() && e.getX() < 555) && 20 < e.getY()
// && e.getY() < 560) {
//
// System.out.println("mouse click!");
// point = FindCrossPoint.find(e.getX(), e.getY());
//
// if(!isStoneDraw(point))
// client.sendMessage(point);
//
// // repaint();
// }
// }
// });
// }
//
// public void addHistory(int[] points, int kindOfStone) {
// aStoneInfo = new StoneHistory(points, StoneFactory.getInstance().getStone(kindOfStone));
// historyOfStone.add(aStoneInfo);
//
// repaint();
// }
//
// // Version 1.01 update
// protected boolean isStoneDraw(int[] points) {
//
// for (StoneHistory temp : historyOfStone) {
// if(temp.points[0] == points[0] && temp.points[1] == points[1])
// return true;
// }
// return false;
// }
//
// public void subHistory(int count) {
// historyOfStone.remove(historyOfStone.size()-1);
//
// if (count == 2) subHistory(1);
// }
//
// public void drawHistory() {
// isRedraw = true;
// repaint();
// }
//
// public void paint(Graphics g) {
// g.drawImage(bi, 0, 0, this);
// // System.out.println("paint()!");
// // update(g);
// }
//
// /*
// * when mouse click, stone is draw.
// */
// public void update(Graphics g) {
//
// // System.out.println("update()");
//
// drawStones(g);
// }
//
//
// /*
// * private Methid~!
// *
// */
// private void drawStones(Graphics g) {
//
// if (!isRedraw) {
// if (lastStone != null)
// g.drawImage(lastStone, lastPoint[0], lastPoint[1], this);
//
// System.out.println("add()" + historyOfStone);
// lastPoint[0] = aStoneInfo.points[0];
// lastPoint[1] = aStoneInfo.points[1];
// lastStone = aStoneInfo.getStone();
//
// g.drawImage(aStoneInfo.getStone(), lastPoint[0], lastPoint[1], this);
//
// } else {
// for (StoneHistory temp : historyOfStone) {
// g.drawImage(temp.getStone(), temp.points[0], temp.points[1], this);
// lastPoint[0] = temp.points[0];
// lastPoint[1] = temp.points[1];
// }
//
// isRedraw = false;
// }
//
// if (lastStone != null) {
// g.setColor(Color.RED);
// g.fillRect(lastPoint[0]+8, lastPoint[1]+8, 7,7);
// }
// }
//
// private StoneHistory getLastStone() {
// return historyOfStone.get(historyOfStone.size() - 1);
// }
//
// private void traker() {
// try {
// tracker = new MediaTracker(this);
// tracker.addImage(image, 0);
// tracker.waitForID(0);
// width = image.getWidth(null);
// height = image.getHeight(null);
// bi = new BufferedImage(width, height,
// BufferedImage.TYPE_INT_RGB);
// Graphics gg = bi.getGraphics();
// gg.drawImage(image, 0, 0, this);
// gg.dispose();
// repaint();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// private void imageLoad() {
// image = toolkit.createImage(URLGetter.getResource("image/badook_board.jpg"));
// }
//
// public void removeStones() {
// historyOfStone = new ArrayList<StoneHistory>();
// }
// }
| import gui.GameRoomGui.GameBoardCanvas;
import java.util.Vector; | package gui;
public interface RoomGuiInter extends PanelInterface {
int BLACK_STONE = 0;
int WHITE_STONE = 1;
void drawStone(int[] stoneLocation, boolean b);
void backOneStep(int n);
void setGameRoomInfo(String info);
void newGame();
void setRoomList(Vector<String> roomList); | // Path: omok/gui/GameRoomGui.java
// class GameBoardCanvas extends Canvas {
//
// /*
// * Image Size is 590,593
// */
//
// private static final long serialVersionUID = 1L;
//
// private ArrayList<StoneHistory> historyOfStone = new ArrayList<StoneHistory>();
//
// private Toolkit toolkit = Toolkit.getDefaultToolkit();
//
// private MediaTracker tracker;
//
// private Image image, lastStone;
//
// private BufferedImage bi;
//
// private int width, height;
//
// private int[] points;
//
// private int[] lastPoint = new int[2];
//
// private StoneHistory aStoneInfo;
//
// private boolean isRedraw = false;
//
// private int whatStone = 0;
//
// public GameBoardCanvas() {
// imageLoad();
// traker();
//
// /*
// * Mouse Click! Event catch!!
// *
// */
// addMouseListener(new MouseAdapter() {
// public void mouseClicked(MouseEvent e) {
// int[] point = new int[2];
//
// if ((16 < e.getX() && e.getX() < 555) && 20 < e.getY()
// && e.getY() < 560) {
//
// System.out.println("mouse click!");
// point = FindCrossPoint.find(e.getX(), e.getY());
//
// if(!isStoneDraw(point))
// client.sendMessage(point);
//
// // repaint();
// }
// }
// });
// }
//
// public void addHistory(int[] points, int kindOfStone) {
// aStoneInfo = new StoneHistory(points, StoneFactory.getInstance().getStone(kindOfStone));
// historyOfStone.add(aStoneInfo);
//
// repaint();
// }
//
// // Version 1.01 update
// protected boolean isStoneDraw(int[] points) {
//
// for (StoneHistory temp : historyOfStone) {
// if(temp.points[0] == points[0] && temp.points[1] == points[1])
// return true;
// }
// return false;
// }
//
// public void subHistory(int count) {
// historyOfStone.remove(historyOfStone.size()-1);
//
// if (count == 2) subHistory(1);
// }
//
// public void drawHistory() {
// isRedraw = true;
// repaint();
// }
//
// public void paint(Graphics g) {
// g.drawImage(bi, 0, 0, this);
// // System.out.println("paint()!");
// // update(g);
// }
//
// /*
// * when mouse click, stone is draw.
// */
// public void update(Graphics g) {
//
// // System.out.println("update()");
//
// drawStones(g);
// }
//
//
// /*
// * private Methid~!
// *
// */
// private void drawStones(Graphics g) {
//
// if (!isRedraw) {
// if (lastStone != null)
// g.drawImage(lastStone, lastPoint[0], lastPoint[1], this);
//
// System.out.println("add()" + historyOfStone);
// lastPoint[0] = aStoneInfo.points[0];
// lastPoint[1] = aStoneInfo.points[1];
// lastStone = aStoneInfo.getStone();
//
// g.drawImage(aStoneInfo.getStone(), lastPoint[0], lastPoint[1], this);
//
// } else {
// for (StoneHistory temp : historyOfStone) {
// g.drawImage(temp.getStone(), temp.points[0], temp.points[1], this);
// lastPoint[0] = temp.points[0];
// lastPoint[1] = temp.points[1];
// }
//
// isRedraw = false;
// }
//
// if (lastStone != null) {
// g.setColor(Color.RED);
// g.fillRect(lastPoint[0]+8, lastPoint[1]+8, 7,7);
// }
// }
//
// private StoneHistory getLastStone() {
// return historyOfStone.get(historyOfStone.size() - 1);
// }
//
// private void traker() {
// try {
// tracker = new MediaTracker(this);
// tracker.addImage(image, 0);
// tracker.waitForID(0);
// width = image.getWidth(null);
// height = image.getHeight(null);
// bi = new BufferedImage(width, height,
// BufferedImage.TYPE_INT_RGB);
// Graphics gg = bi.getGraphics();
// gg.drawImage(image, 0, 0, this);
// gg.dispose();
// repaint();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
// private void imageLoad() {
// image = toolkit.createImage(URLGetter.getResource("image/badook_board.jpg"));
// }
//
// public void removeStones() {
// historyOfStone = new ArrayList<StoneHistory>();
// }
// }
// Path: omok/gui/RoomGuiInter.java
import gui.GameRoomGui.GameBoardCanvas;
import java.util.Vector;
package gui;
public interface RoomGuiInter extends PanelInterface {
int BLACK_STONE = 0;
int WHITE_STONE = 1;
void drawStone(int[] stoneLocation, boolean b);
void backOneStep(int n);
void setGameRoomInfo(String info);
void newGame();
void setRoomList(Vector<String> roomList); | GameBoardCanvas getM_board(); |
anyjava/FiveStonesGame | omok/gui/UserListFrame.java | // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
| import gameClient.ClientInterface;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane; | package gui;
public class UserListFrame extends JFrame {
private static final long serialVersionUID = 1L;
private Container cp;
private JList m_userList;
private JScrollPane m_scList;
private JButton m_sendButton, m_closeButton;
| // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
// Path: omok/gui/UserListFrame.java
import gameClient.ClientInterface;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
package gui;
public class UserListFrame extends JFrame {
private static final long serialVersionUID = 1L;
private Container cp;
private JList m_userList;
private JScrollPane m_scList;
private JButton m_sendButton, m_closeButton;
| protected ClientInterface client; |
anyjava/FiveStonesGame | omok/gui/LobbyGui.java | // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
| import gameClient.ClientInterface;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel; | package gui;
/*
* Version 1.01 챗티창 라인보호.
*/
@SuppressWarnings("serial")
public class LobbyGui extends JPanel implements LobbyGuiInter, PanelInterface{
| // Path: omok/gameClient/ClientInterface.java
// public interface ClientInterface {
// void sendMessage(String message, short state);
// void sendSlip(String to, String text, short message_slip);
// GuiInterface getGui();
// void changeGui(GuiInterface gui);
// void sendMessage(int[] is);
// void setSlipTo(String slipTo);
// boolean isRoomKing();
// }
// Path: omok/gui/LobbyGui.java
import gameClient.ClientInterface;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
package gui;
/*
* Version 1.01 챗티창 라인보호.
*/
@SuppressWarnings("serial")
public class LobbyGui extends JPanel implements LobbyGuiInter, PanelInterface{
| private ClientInterface client; |
anyjava/FiveStonesGame | omok/gameClient/ClientInterface.java | // Path: omok/gui/GuiInterface.java
// public interface GuiInterface {
// public void setTextToLogWindow(String str);
// public void setUserList(Vector<String> userList);
// public void showMessageBox(String sender, String message, boolean option);
// public JList getJList();
// public void unShow();
// public String getInputText();
// public void setTextToInput(String string);
// public void setTotalUser(Vector<String> userList);
// public void setUserListFrame(UserListFrame userListFrame);
// public void setPanel(PanelInterface panel);
// public void setPanel(GameLobbyInter panel);
// public void setPanel(LobbyGuiInter panel);
// public void setPanel(RoomGuiInter panel);
// }
| import gui.GuiInterface; | package gameClient;
public interface ClientInterface {
void sendMessage(String message, short state);
void sendSlip(String to, String text, short message_slip); | // Path: omok/gui/GuiInterface.java
// public interface GuiInterface {
// public void setTextToLogWindow(String str);
// public void setUserList(Vector<String> userList);
// public void showMessageBox(String sender, String message, boolean option);
// public JList getJList();
// public void unShow();
// public String getInputText();
// public void setTextToInput(String string);
// public void setTotalUser(Vector<String> userList);
// public void setUserListFrame(UserListFrame userListFrame);
// public void setPanel(PanelInterface panel);
// public void setPanel(GameLobbyInter panel);
// public void setPanel(LobbyGuiInter panel);
// public void setPanel(RoomGuiInter panel);
// }
// Path: omok/gameClient/ClientInterface.java
import gui.GuiInterface;
package gameClient;
public interface ClientInterface {
void sendMessage(String message, short state);
void sendSlip(String to, String text, short message_slip); | GuiInterface getGui(); |
johnlcox/dagger-servlet | dagger-servlet/src/test/java/com/leacox/dagger/servlet/MultipleServletObjectGraphsTest.java | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/DaggerServletContextListener.java
// public static final String OBJECT_GRAPH_NAME = ObjectGraph.class.getName();
| import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import org.testng.annotations.Test;
import javax.inject.Singleton;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpServlet;
import static com.leacox.dagger.servlet.DaggerServletContextListener.OBJECT_GRAPH_NAME;
import static org.easymock.EasyMock.*;
import static org.testng.Assert.*; | /**
* Copyright (C) 2010 Google Inc.
* Copyright (C) 2014 John Leacox
*
* 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.leacox.dagger.servlet;
/**
* This gorgeous test asserts that multiple servlet pipelines can
* run in the SAME JVM. booya.
*
* @author [email protected] (Dhanji R. Prasanna)
* @author John Leacox
*/
public class MultipleServletObjectGraphsTest {
@Module(
injects = {
},
includes = {
ServletModule.class
},
library = true
)
static class TestModule {
@Provides
@Singleton
DummyServlet provideDummyServlet() {
return new DummyServlet();
}
@Provides
@Singleton
DummyFilterImpl provideDummyFilter() {
return new DummyFilterImpl();
}
}
@Test
public final void testTwoObjectGraphs() {
ServletContext fakeContextOne = createMock(ServletContext.class);
ServletContext fakeContextTwo = createMock(ServletContext.class);
| // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/DaggerServletContextListener.java
// public static final String OBJECT_GRAPH_NAME = ObjectGraph.class.getName();
// Path: dagger-servlet/src/test/java/com/leacox/dagger/servlet/MultipleServletObjectGraphsTest.java
import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import org.testng.annotations.Test;
import javax.inject.Singleton;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpServlet;
import static com.leacox.dagger.servlet.DaggerServletContextListener.OBJECT_GRAPH_NAME;
import static org.easymock.EasyMock.*;
import static org.testng.Assert.*;
/**
* Copyright (C) 2010 Google Inc.
* Copyright (C) 2014 John Leacox
*
* 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.leacox.dagger.servlet;
/**
* This gorgeous test asserts that multiple servlet pipelines can
* run in the SAME JVM. booya.
*
* @author [email protected] (Dhanji R. Prasanna)
* @author John Leacox
*/
public class MultipleServletObjectGraphsTest {
@Module(
injects = {
},
includes = {
ServletModule.class
},
library = true
)
static class TestModule {
@Provides
@Singleton
DummyServlet provideDummyServlet() {
return new DummyServlet();
}
@Provides
@Singleton
DummyFilterImpl provideDummyFilter() {
return new DummyFilterImpl();
}
}
@Test
public final void testTwoObjectGraphs() {
ServletContext fakeContextOne = createMock(ServletContext.class);
ServletContext fakeContextTwo = createMock(ServletContext.class);
| fakeContextOne.setAttribute(eq(OBJECT_GRAPH_NAME), isA(ObjectGraph.class)); |
johnlcox/dagger-servlet | dagger-servlet/src/test/java/com/leacox/dagger/servlet/ScopeRequestIntegrationTest.java | // Path: dagger-servlet/src/main/java/dagger/ScopingObjectGraph.java
// public class ScopingObjectGraph extends ObjectGraph {
// private final ObjectGraph objectGraph;
// private final Map<Class<? extends Annotation>, Object[]> scopedModules;
//
// private final Scope requestScope = ServletScopes.REQUEST;
//
// ScopingObjectGraph(ObjectGraph objectGraph, Map<Class<? extends Annotation>, Object[]> scopedModules) {
// this.objectGraph = objectGraph;
// this.scopedModules = scopedModules;
// }
//
// public static ScopingObjectGraph create(ObjectGraph objectGraph) {
// return new ScopingObjectGraph(objectGraph, Maps.<Class<? extends Annotation>, Object[]>newHashMap());
// }
//
// public ScopingObjectGraph addScopedModules(Class<? extends Annotation> scope, Object... modules) {
// scopedModules.put(scope, modules);
// return new ScopingObjectGraph(objectGraph, scopedModules);
// }
//
// @Override
// public <T> T get(Class<T> type) {
// HttpServletRequest request = DaggerFilter.getRequest();
// if (request == null && !ServletScopes.isNonHttpRequestScope()) {
// return objectGraph.get(type);
// }
//
// if (isRequestScoped(type)) {
// return requestScope.scope(type, objectGraph, scopedModules.get(RequestScoped.class));
// } else {
// return objectGraph.get(type);
// }
// }
//
// @Override
// public <T> T inject(T instance) {
// HttpServletRequest request = DaggerFilter.getRequest();
// if (request == null && !ServletScopes.isNonHttpRequestScope()) {
// return objectGraph.inject(instance);
// }
//
// if (isRequestScoped(instance.getClass())) {
// return requestScope.scopeInstance(instance, objectGraph, scopedModules.get(RequestScoped.class));
// } else {
// return objectGraph.inject(instance);
// }
// }
//
// @Override
// public ObjectGraph plus(Object... modules) {
// return new ScopingObjectGraph(objectGraph.plus(modules), scopedModules);
// }
//
// @Override
// public void validate() {
// objectGraph.validate();
//
// for (Object[] modules : scopedModules.values()) {
// objectGraph.plus(modules).validate();
// }
// }
//
// // TODO: Add validation of classes and objects so we can make sure the filter/servlet classes have injections
// // and fail early instead of when we try to inject it on an actual request.
//
// @Override
// public void injectStatics() {
// // Only need to inject on the base object graph. Plused modules do not do static injection.
// objectGraph.injectStatics();
// }
//
// private <T> boolean isRequestScoped(Class<T> type) {
// Object[] requestScopedModules = scopedModules.get(RequestScoped.class);
// for (Object requestScopedModule : requestScopedModules) {
// Module module;
// if (requestScopedModule instanceof Class<?>) {
// module = ((Class<?>) requestScopedModule).getAnnotation(Module.class);
// } else {
// module = requestScopedModule.getClass().getAnnotation(Module.class);
// }
//
// if (arrayContains(module.injects(), type)) {
// return true;
// }
// }
//
// return false;
// }
//
// private static <T> boolean arrayContains(final T[] array, final T value) {
// for (final T element : array) {
// if (element == value || (value != null && value.equals(element))) {
// return true;
// }
// }
//
// return false;
// }
// }
| import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import dagger.ScopingObjectGraph;
import org.testng.annotations.Test;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.fail; | ObjectGraph.class
},
includes = {
ServletModule.class
}
)
static class TestAppModule {
}
@Module(
injects = {
SomeObject.class
},
includes = {
ServletRequestModule.class
}
)
static class TestRequestModule {
@Provides
@Named(SomeObject.INVALID)
String provideInvalidString() {
return SHOULDNEVERBESEEN;
}
}
@Test
public final void testNonHttpRequestScopedCallable()
throws ServletException, IOException, InterruptedException, ExecutionException {
ExecutorService executor = Executors.newSingleThreadExecutor();
ObjectGraph baseGraph = ObjectGraph.create(TestAppModule.class); | // Path: dagger-servlet/src/main/java/dagger/ScopingObjectGraph.java
// public class ScopingObjectGraph extends ObjectGraph {
// private final ObjectGraph objectGraph;
// private final Map<Class<? extends Annotation>, Object[]> scopedModules;
//
// private final Scope requestScope = ServletScopes.REQUEST;
//
// ScopingObjectGraph(ObjectGraph objectGraph, Map<Class<? extends Annotation>, Object[]> scopedModules) {
// this.objectGraph = objectGraph;
// this.scopedModules = scopedModules;
// }
//
// public static ScopingObjectGraph create(ObjectGraph objectGraph) {
// return new ScopingObjectGraph(objectGraph, Maps.<Class<? extends Annotation>, Object[]>newHashMap());
// }
//
// public ScopingObjectGraph addScopedModules(Class<? extends Annotation> scope, Object... modules) {
// scopedModules.put(scope, modules);
// return new ScopingObjectGraph(objectGraph, scopedModules);
// }
//
// @Override
// public <T> T get(Class<T> type) {
// HttpServletRequest request = DaggerFilter.getRequest();
// if (request == null && !ServletScopes.isNonHttpRequestScope()) {
// return objectGraph.get(type);
// }
//
// if (isRequestScoped(type)) {
// return requestScope.scope(type, objectGraph, scopedModules.get(RequestScoped.class));
// } else {
// return objectGraph.get(type);
// }
// }
//
// @Override
// public <T> T inject(T instance) {
// HttpServletRequest request = DaggerFilter.getRequest();
// if (request == null && !ServletScopes.isNonHttpRequestScope()) {
// return objectGraph.inject(instance);
// }
//
// if (isRequestScoped(instance.getClass())) {
// return requestScope.scopeInstance(instance, objectGraph, scopedModules.get(RequestScoped.class));
// } else {
// return objectGraph.inject(instance);
// }
// }
//
// @Override
// public ObjectGraph plus(Object... modules) {
// return new ScopingObjectGraph(objectGraph.plus(modules), scopedModules);
// }
//
// @Override
// public void validate() {
// objectGraph.validate();
//
// for (Object[] modules : scopedModules.values()) {
// objectGraph.plus(modules).validate();
// }
// }
//
// // TODO: Add validation of classes and objects so we can make sure the filter/servlet classes have injections
// // and fail early instead of when we try to inject it on an actual request.
//
// @Override
// public void injectStatics() {
// // Only need to inject on the base object graph. Plused modules do not do static injection.
// objectGraph.injectStatics();
// }
//
// private <T> boolean isRequestScoped(Class<T> type) {
// Object[] requestScopedModules = scopedModules.get(RequestScoped.class);
// for (Object requestScopedModule : requestScopedModules) {
// Module module;
// if (requestScopedModule instanceof Class<?>) {
// module = ((Class<?>) requestScopedModule).getAnnotation(Module.class);
// } else {
// module = requestScopedModule.getClass().getAnnotation(Module.class);
// }
//
// if (arrayContains(module.injects(), type)) {
// return true;
// }
// }
//
// return false;
// }
//
// private static <T> boolean arrayContains(final T[] array, final T value) {
// for (final T element : array) {
// if (element == value || (value != null && value.equals(element))) {
// return true;
// }
// }
//
// return false;
// }
// }
// Path: dagger-servlet/src/test/java/com/leacox/dagger/servlet/ScopeRequestIntegrationTest.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import dagger.ScopingObjectGraph;
import org.testng.annotations.Test;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.fail;
ObjectGraph.class
},
includes = {
ServletModule.class
}
)
static class TestAppModule {
}
@Module(
injects = {
SomeObject.class
},
includes = {
ServletRequestModule.class
}
)
static class TestRequestModule {
@Provides
@Named(SomeObject.INVALID)
String provideInvalidString() {
return SHOULDNEVERBESEEN;
}
}
@Test
public final void testNonHttpRequestScopedCallable()
throws ServletException, IOException, InterruptedException, ExecutionException {
ExecutorService executor = Executors.newSingleThreadExecutor();
ObjectGraph baseGraph = ObjectGraph.create(TestAppModule.class); | ObjectGraph scopingGraph = ScopingObjectGraph.create(baseGraph) |
johnlcox/dagger-servlet | dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletDefinition.java | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ManagedServletPipeline.java
// public static final String REQUEST_DISPATCHER_REQUEST = "javax.servlet.forward.servlet_path";
| import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import static com.leacox.dagger.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import dagger.ObjectGraph;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException; | private String path;
private boolean pathComputed = false;
//must use a boolean on the memo field, because null is a legal value (TODO no, it's not)
private boolean pathInfoComputed = false;
private String pathInfo;
@Override
public String getPathInfo() {
if (!isPathInfoComputed()) {
int servletPathLength = getServletPath().length();
pathInfo = getRequestURI().substring(getContextPath().length()).replaceAll("[/]{2,}", "/");
pathInfo = pathInfo.length() > servletPathLength ? pathInfo.substring(servletPathLength) : null;
// Corner case: when servlet path and request path match exactly (without trailing '/'),
// then pathinfo is null
if ("".equals(pathInfo) && servletPathLength != 0) {
pathInfo = null;
}
pathInfoComputed = true;
}
return pathInfo;
}
// NOTE(dhanji): These two are a bit of a hack to help ensure that request dipatcher-sent
// requests don't use the same path info that was memoized for the original request.
private boolean isPathInfoComputed() {
return pathInfoComputed | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ManagedServletPipeline.java
// public static final String REQUEST_DISPATCHER_REQUEST = "javax.servlet.forward.servlet_path";
// Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletDefinition.java
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import static com.leacox.dagger.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import dagger.ObjectGraph;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
private String path;
private boolean pathComputed = false;
//must use a boolean on the memo field, because null is a legal value (TODO no, it's not)
private boolean pathInfoComputed = false;
private String pathInfo;
@Override
public String getPathInfo() {
if (!isPathInfoComputed()) {
int servletPathLength = getServletPath().length();
pathInfo = getRequestURI().substring(getContextPath().length()).replaceAll("[/]{2,}", "/");
pathInfo = pathInfo.length() > servletPathLength ? pathInfo.substring(servletPathLength) : null;
// Corner case: when servlet path and request path match exactly (without trailing '/'),
// then pathinfo is null
if ("".equals(pathInfo) && servletPathLength != 0) {
pathInfo = null;
}
pathInfoComputed = true;
}
return pathInfo;
}
// NOTE(dhanji): These two are a bit of a hack to help ensure that request dipatcher-sent
// requests don't use the same path info that was memoized for the original request.
private boolean isPathInfoComputed() {
return pathInfoComputed | && !(null != servletRequest.getAttribute(REQUEST_DISPATCHER_REQUEST)); |
johnlcox/dagger-servlet | dagger-servlet/src/test/java/com/leacox/dagger/servlet/FilterDispatchIntegrationTest.java | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ManagedServletPipeline.java
// public static final String REQUEST_DISPATCHER_REQUEST = "javax.servlet.forward.servlet_path";
| import dagger.Module;
import dagger.ObjectGraph;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.leacox.dagger.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import static org.easymock.EasyMock.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue; | filter("/*").through(TestFilter.class);
filter("*.html").through(TestFilter.class);
filter("/*").through(TestFilter.class);
// These filters should never fire
filter("/index/*").through(TestFilter.class);
filter("*.jsp").through(TestFilter.class);
// Bind a servlet
serve("*.html").with(TestServlet.class);
}
};
ServletContext servletContext = createMock("blah", ServletContext.class);
contextListener.contextInitialized(new ServletContextEvent(servletContext));
final ObjectGraph objectGraph = contextListener.getObjectGraph();
final FilterPipeline pipeline = objectGraph.get(FilterPipeline.class);
pipeline.initPipeline(null);
// create ourselves a mock request with test URI
HttpServletRequest requestMock = control.createMock(HttpServletRequest.class);
expect(requestMock.getRequestURI())
.andReturn("/index.html")
.anyTimes();
expect(requestMock.getContextPath())
.andReturn("")
.anyTimes();
| // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ManagedServletPipeline.java
// public static final String REQUEST_DISPATCHER_REQUEST = "javax.servlet.forward.servlet_path";
// Path: dagger-servlet/src/test/java/com/leacox/dagger/servlet/FilterDispatchIntegrationTest.java
import dagger.Module;
import dagger.ObjectGraph;
import org.easymock.EasyMock;
import org.easymock.IMocksControl;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.leacox.dagger.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import static org.easymock.EasyMock.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
filter("/*").through(TestFilter.class);
filter("*.html").through(TestFilter.class);
filter("/*").through(TestFilter.class);
// These filters should never fire
filter("/index/*").through(TestFilter.class);
filter("*.jsp").through(TestFilter.class);
// Bind a servlet
serve("*.html").with(TestServlet.class);
}
};
ServletContext servletContext = createMock("blah", ServletContext.class);
contextListener.contextInitialized(new ServletContextEvent(servletContext));
final ObjectGraph objectGraph = contextListener.getObjectGraph();
final FilterPipeline pipeline = objectGraph.get(FilterPipeline.class);
pipeline.initPipeline(null);
// create ourselves a mock request with test URI
HttpServletRequest requestMock = control.createMock(HttpServletRequest.class);
expect(requestMock.getRequestURI())
.andReturn("/index.html")
.anyTimes();
expect(requestMock.getContextPath())
.andReturn("")
.anyTimes();
| requestMock.setAttribute(REQUEST_DISPATCHER_REQUEST, true); |
johnlcox/dagger-servlet | dagger-servlet/src/test/java/com/leacox/dagger/servlet/ServletPipelineRequestDispatcherTest.java | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ManagedServletPipeline.java
// public static final String REQUEST_DISPATCHER_REQUEST = "javax.servlet.forward.servlet_path";
| import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import dagger.ObjectGraph;
import org.testng.annotations.Test;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import static com.leacox.dagger.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue; | /**
* Copyright (C) 2008 Google Inc.
* Copyright (C) 2014 John Leacox
*
* 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.leacox.dagger.servlet;
/**
* Tests forwarding and inclusion (RequestDispatcher actions from the
* servlet spec).
*
* @author Dhanji R. Prasanna (dhanji@gmail com)
* @author John Leacox
*/
public class ServletPipelineRequestDispatcherTest {
private static final Class<?> HTTP_SERLVET_CLASS = HttpServlet.class;
private static final String A_KEY = "thinglyDEgintly" + new Date() + UUID.randomUUID();
private static final String A_VALUE = ServletPipelineRequestDispatcherTest.class.toString()
+ new Date() + UUID.randomUUID();
@Test
public final void testIncludeManagedServlet() throws IOException, ServletException {
String pattern = "blah.html";
final ServletDefinition servletDefinition = new ServletDefinition(pattern,
HttpServlet.class, UriPatternType.get(UriPatternType.SERVLET, pattern),
new HashMap<String, String>(), null);
ObjectGraph objectGraph = createMock(ObjectGraph.class);
final HttpServletRequest requestMock = createMock(HttpServletRequest.class);
expect(requestMock.getAttribute(A_KEY))
.andReturn(A_VALUE);
| // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ManagedServletPipeline.java
// public static final String REQUEST_DISPATCHER_REQUEST = "javax.servlet.forward.servlet_path";
// Path: dagger-servlet/src/test/java/com/leacox/dagger/servlet/ServletPipelineRequestDispatcherTest.java
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import dagger.ObjectGraph;
import org.testng.annotations.Test;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import static com.leacox.dagger.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
/**
* Copyright (C) 2008 Google Inc.
* Copyright (C) 2014 John Leacox
*
* 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.leacox.dagger.servlet;
/**
* Tests forwarding and inclusion (RequestDispatcher actions from the
* servlet spec).
*
* @author Dhanji R. Prasanna (dhanji@gmail com)
* @author John Leacox
*/
public class ServletPipelineRequestDispatcherTest {
private static final Class<?> HTTP_SERLVET_CLASS = HttpServlet.class;
private static final String A_KEY = "thinglyDEgintly" + new Date() + UUID.randomUUID();
private static final String A_VALUE = ServletPipelineRequestDispatcherTest.class.toString()
+ new Date() + UUID.randomUUID();
@Test
public final void testIncludeManagedServlet() throws IOException, ServletException {
String pattern = "blah.html";
final ServletDefinition servletDefinition = new ServletDefinition(pattern,
HttpServlet.class, UriPatternType.get(UriPatternType.SERVLET, pattern),
new HashMap<String, String>(), null);
ObjectGraph objectGraph = createMock(ObjectGraph.class);
final HttpServletRequest requestMock = createMock(HttpServletRequest.class);
expect(requestMock.getAttribute(A_KEY))
.andReturn(A_VALUE);
| requestMock.setAttribute(REQUEST_DISPATCHER_REQUEST, true); |
johnlcox/dagger-servlet | dagger-jersey/src/main/java/com/leacox/dagger/jersey/JerseyModule.java | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletModule.java
// @Module(
// injects = {
// ServletContext.class
// },
// includes = {
// InternalServletModule.class
// }
// )
// public class ServletModule {
// @Provides
// @Singleton
// ServletContext provideServletContext(ServletContextProvider servletContextProvider) {
// return servletContextProvider.get();
// }
// }
| import com.leacox.dagger.servlet.ServletModule;
import com.leacox.dagger.servlet.internal.ModuleClasses;
import com.sun.jersey.api.core.ResourceContext;
import com.sun.jersey.core.util.FeaturesAndProperties;
import com.sun.jersey.spi.MessageBodyWorkers;
import com.sun.jersey.spi.container.ExceptionMapperContext;
import com.sun.jersey.spi.container.WebApplication;
import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import javax.inject.Singleton;
import javax.ws.rs.ext.Providers; | /**
* Copyright (C) 2014 John Leacox
*
* 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.leacox.dagger.jersey;
/**
* A Dagger module that provides application wide JAX-RS and Jersey related bindings. In addition to the internal
* bindings the following bindings are provided:
* <ul>
* <li>{@link com.sun.jersey.spi.container.WebApplication}</li>
* <li>{@link javax.ws.rs.ext.Providers}</li>
* <li>{@link com.sun.jersey.core.util.FeaturesAndProperties}</li>
* <li>{@link com.sun.jersey.spi.MessageBodyWorkers}</li>
* <li>{@link com.sun.jersey.spi.container.ExceptionMapperContext}</li>
* <li>{@link com.sun.jersey.api.core.ResourceContext}</li>
* </ul>
*
* @author John Leacox
*/
@Module(
injects = {
DaggerContainer.class
},
includes = { | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletModule.java
// @Module(
// injects = {
// ServletContext.class
// },
// includes = {
// InternalServletModule.class
// }
// )
// public class ServletModule {
// @Provides
// @Singleton
// ServletContext provideServletContext(ServletContextProvider servletContextProvider) {
// return servletContextProvider.get();
// }
// }
// Path: dagger-jersey/src/main/java/com/leacox/dagger/jersey/JerseyModule.java
import com.leacox.dagger.servlet.ServletModule;
import com.leacox.dagger.servlet.internal.ModuleClasses;
import com.sun.jersey.api.core.ResourceContext;
import com.sun.jersey.core.util.FeaturesAndProperties;
import com.sun.jersey.spi.MessageBodyWorkers;
import com.sun.jersey.spi.container.ExceptionMapperContext;
import com.sun.jersey.spi.container.WebApplication;
import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import javax.inject.Singleton;
import javax.ws.rs.ext.Providers;
/**
* Copyright (C) 2014 John Leacox
*
* 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.leacox.dagger.jersey;
/**
* A Dagger module that provides application wide JAX-RS and Jersey related bindings. In addition to the internal
* bindings the following bindings are provided:
* <ul>
* <li>{@link com.sun.jersey.spi.container.WebApplication}</li>
* <li>{@link javax.ws.rs.ext.Providers}</li>
* <li>{@link com.sun.jersey.core.util.FeaturesAndProperties}</li>
* <li>{@link com.sun.jersey.spi.MessageBodyWorkers}</li>
* <li>{@link com.sun.jersey.spi.container.ExceptionMapperContext}</li>
* <li>{@link com.sun.jersey.api.core.ResourceContext}</li>
* </ul>
*
* @author John Leacox
*/
@Module(
injects = {
DaggerContainer.class
},
includes = { | ServletModule.class |
johnlcox/dagger-servlet | examples/jersey-simple/src/main/java/com/leacox/dagger/example/simple/SimpleModule.java | // Path: dagger-jersey/src/main/java/com/leacox/dagger/jersey/JerseyModule.java
// @Module(
// injects = {
// DaggerContainer.class
// },
// includes = {
// ServletModule.class
// },
// library = true
// )
// public class JerseyModule {
// @Provides
// @Singleton
// public DaggerContainer provideDaggerContainer(ObjectGraph objectGraph, @ModuleClasses Object[] modules) {
// return new DaggerContainer(objectGraph, modules);
// }
//
// @Provides
// public WebApplication webApplication(DaggerContainer daggerContainer) {
// return daggerContainer.getWebApplication();
// }
//
// @Provides
// public Providers provideProviders(WebApplication webApplication) {
// return webApplication.getProviders();
// }
//
// @Provides
// public FeaturesAndProperties provideFeaturesAndProperties(WebApplication webApplication) {
// return webApplication.getFeaturesAndProperties();
// }
//
// @Provides
// public MessageBodyWorkers provideMessageBodyWorkers(WebApplication webApplication) {
// return webApplication.getMessageBodyWorkers();
// }
//
// @Provides
// public ExceptionMapperContext provideExceptionMapperContext(WebApplication webApplication) {
// return webApplication.getExceptionMapperContext();
// }
//
// @Provides
// public ResourceContext provideResourceContext(WebApplication webApplication) {
// return webApplication.getResourceContext();
// }
// }
//
// Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletModule.java
// @Module(
// injects = {
// ServletContext.class
// },
// includes = {
// InternalServletModule.class
// }
// )
// public class ServletModule {
// @Provides
// @Singleton
// ServletContext provideServletContext(ServletContextProvider servletContextProvider) {
// return servletContextProvider.get();
// }
// }
| import com.leacox.dagger.jersey.JerseyModule;
import com.leacox.dagger.servlet.ServletModule;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton; | /**
* Copyright (C) 2014 John Leacox
*
* 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.leacox.dagger.example.simple;
/**
* @author John Leacox
*/
@Module(
injects = {
SimpleService.class,
SimpleResource.class
},
includes = { | // Path: dagger-jersey/src/main/java/com/leacox/dagger/jersey/JerseyModule.java
// @Module(
// injects = {
// DaggerContainer.class
// },
// includes = {
// ServletModule.class
// },
// library = true
// )
// public class JerseyModule {
// @Provides
// @Singleton
// public DaggerContainer provideDaggerContainer(ObjectGraph objectGraph, @ModuleClasses Object[] modules) {
// return new DaggerContainer(objectGraph, modules);
// }
//
// @Provides
// public WebApplication webApplication(DaggerContainer daggerContainer) {
// return daggerContainer.getWebApplication();
// }
//
// @Provides
// public Providers provideProviders(WebApplication webApplication) {
// return webApplication.getProviders();
// }
//
// @Provides
// public FeaturesAndProperties provideFeaturesAndProperties(WebApplication webApplication) {
// return webApplication.getFeaturesAndProperties();
// }
//
// @Provides
// public MessageBodyWorkers provideMessageBodyWorkers(WebApplication webApplication) {
// return webApplication.getMessageBodyWorkers();
// }
//
// @Provides
// public ExceptionMapperContext provideExceptionMapperContext(WebApplication webApplication) {
// return webApplication.getExceptionMapperContext();
// }
//
// @Provides
// public ResourceContext provideResourceContext(WebApplication webApplication) {
// return webApplication.getResourceContext();
// }
// }
//
// Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletModule.java
// @Module(
// injects = {
// ServletContext.class
// },
// includes = {
// InternalServletModule.class
// }
// )
// public class ServletModule {
// @Provides
// @Singleton
// ServletContext provideServletContext(ServletContextProvider servletContextProvider) {
// return servletContextProvider.get();
// }
// }
// Path: examples/jersey-simple/src/main/java/com/leacox/dagger/example/simple/SimpleModule.java
import com.leacox.dagger.jersey.JerseyModule;
import com.leacox.dagger.servlet.ServletModule;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
/**
* Copyright (C) 2014 John Leacox
*
* 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.leacox.dagger.example.simple;
/**
* @author John Leacox
*/
@Module(
injects = {
SimpleService.class,
SimpleResource.class
},
includes = { | ServletModule.class, |
johnlcox/dagger-servlet | examples/jersey-simple/src/main/java/com/leacox/dagger/example/simple/SimpleModule.java | // Path: dagger-jersey/src/main/java/com/leacox/dagger/jersey/JerseyModule.java
// @Module(
// injects = {
// DaggerContainer.class
// },
// includes = {
// ServletModule.class
// },
// library = true
// )
// public class JerseyModule {
// @Provides
// @Singleton
// public DaggerContainer provideDaggerContainer(ObjectGraph objectGraph, @ModuleClasses Object[] modules) {
// return new DaggerContainer(objectGraph, modules);
// }
//
// @Provides
// public WebApplication webApplication(DaggerContainer daggerContainer) {
// return daggerContainer.getWebApplication();
// }
//
// @Provides
// public Providers provideProviders(WebApplication webApplication) {
// return webApplication.getProviders();
// }
//
// @Provides
// public FeaturesAndProperties provideFeaturesAndProperties(WebApplication webApplication) {
// return webApplication.getFeaturesAndProperties();
// }
//
// @Provides
// public MessageBodyWorkers provideMessageBodyWorkers(WebApplication webApplication) {
// return webApplication.getMessageBodyWorkers();
// }
//
// @Provides
// public ExceptionMapperContext provideExceptionMapperContext(WebApplication webApplication) {
// return webApplication.getExceptionMapperContext();
// }
//
// @Provides
// public ResourceContext provideResourceContext(WebApplication webApplication) {
// return webApplication.getResourceContext();
// }
// }
//
// Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletModule.java
// @Module(
// injects = {
// ServletContext.class
// },
// includes = {
// InternalServletModule.class
// }
// )
// public class ServletModule {
// @Provides
// @Singleton
// ServletContext provideServletContext(ServletContextProvider servletContextProvider) {
// return servletContextProvider.get();
// }
// }
| import com.leacox.dagger.jersey.JerseyModule;
import com.leacox.dagger.servlet.ServletModule;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton; | /**
* Copyright (C) 2014 John Leacox
*
* 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.leacox.dagger.example.simple;
/**
* @author John Leacox
*/
@Module(
injects = {
SimpleService.class,
SimpleResource.class
},
includes = {
ServletModule.class, | // Path: dagger-jersey/src/main/java/com/leacox/dagger/jersey/JerseyModule.java
// @Module(
// injects = {
// DaggerContainer.class
// },
// includes = {
// ServletModule.class
// },
// library = true
// )
// public class JerseyModule {
// @Provides
// @Singleton
// public DaggerContainer provideDaggerContainer(ObjectGraph objectGraph, @ModuleClasses Object[] modules) {
// return new DaggerContainer(objectGraph, modules);
// }
//
// @Provides
// public WebApplication webApplication(DaggerContainer daggerContainer) {
// return daggerContainer.getWebApplication();
// }
//
// @Provides
// public Providers provideProviders(WebApplication webApplication) {
// return webApplication.getProviders();
// }
//
// @Provides
// public FeaturesAndProperties provideFeaturesAndProperties(WebApplication webApplication) {
// return webApplication.getFeaturesAndProperties();
// }
//
// @Provides
// public MessageBodyWorkers provideMessageBodyWorkers(WebApplication webApplication) {
// return webApplication.getMessageBodyWorkers();
// }
//
// @Provides
// public ExceptionMapperContext provideExceptionMapperContext(WebApplication webApplication) {
// return webApplication.getExceptionMapperContext();
// }
//
// @Provides
// public ResourceContext provideResourceContext(WebApplication webApplication) {
// return webApplication.getResourceContext();
// }
// }
//
// Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletModule.java
// @Module(
// injects = {
// ServletContext.class
// },
// includes = {
// InternalServletModule.class
// }
// )
// public class ServletModule {
// @Provides
// @Singleton
// ServletContext provideServletContext(ServletContextProvider servletContextProvider) {
// return servletContextProvider.get();
// }
// }
// Path: examples/jersey-simple/src/main/java/com/leacox/dagger/example/simple/SimpleModule.java
import com.leacox.dagger.jersey.JerseyModule;
import com.leacox.dagger.servlet.ServletModule;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
/**
* Copyright (C) 2014 John Leacox
*
* 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.leacox.dagger.example.simple;
/**
* @author John Leacox
*/
@Module(
injects = {
SimpleService.class,
SimpleResource.class
},
includes = {
ServletModule.class, | JerseyModule.class |
johnlcox/dagger-servlet | dagger-servlet/src/main/java/com/leacox/dagger/servlet/ContinuingHttpServletRequest.java | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/scope/OutOfScopeException.java
// public final class OutOfScopeException extends RuntimeException {
//
// public OutOfScopeException(String message) {
// super(message);
// }
//
// public OutOfScopeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OutOfScopeException(Throwable cause) {
// super(cause);
// }
// }
| import com.google.common.collect.Maps;
import com.leacox.dagger.servlet.scope.OutOfScopeException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map; | /**
* Copyright (C) 2010 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.leacox.dagger.servlet;
/**
* A wrapper for requests that makes requests immutable, taking a snapshot
* of the original request.
*
* @author [email protected] (Dhanji R. Prasanna)
*/
class ContinuingHttpServletRequest extends HttpServletRequestWrapper {
// We clear out the attributes as they are mutable and not thread-safe.
private final Map<String, Object> attributes = Maps.newHashMap();
public ContinuingHttpServletRequest(HttpServletRequest request) {
super(request);
}
@Override
public HttpSession getSession() { | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/scope/OutOfScopeException.java
// public final class OutOfScopeException extends RuntimeException {
//
// public OutOfScopeException(String message) {
// super(message);
// }
//
// public OutOfScopeException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public OutOfScopeException(Throwable cause) {
// super(cause);
// }
// }
// Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ContinuingHttpServletRequest.java
import com.google.common.collect.Maps;
import com.leacox.dagger.servlet.scope.OutOfScopeException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
/**
* Copyright (C) 2010 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.leacox.dagger.servlet;
/**
* A wrapper for requests that makes requests immutable, taking a snapshot
* of the original request.
*
* @author [email protected] (Dhanji R. Prasanna)
*/
class ContinuingHttpServletRequest extends HttpServletRequestWrapper {
// We clear out the attributes as they are mutable and not thread-safe.
private final Map<String, Object> attributes = Maps.newHashMap();
public ContinuingHttpServletRequest(HttpServletRequest request) {
super(request);
}
@Override
public HttpSession getSession() { | throw new OutOfScopeException("Cannot access the session in a continued request"); |
johnlcox/dagger-servlet | dagger-servlet/src/test/java/com/leacox/dagger/servlet/ServletTest.java | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletScopes.java
// enum NullObject {
// INSTANCE
// }
| import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.inject.Singleton;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import static com.leacox.dagger.servlet.ServletScopes.NullObject;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue; |
@Override
protected Class<?>[] getRequestScopedModules() {
return new Class<?>[]{TestRequestModule.class};
}
@Override
protected void configureServlets() {
}
};
ServletContext servletContext = createMock(ServletContext.class);
contextListener.contextInitialized(new ServletContextEvent(servletContext));
final ObjectGraph objectGraph = contextListener.getObjectGraph();
DaggerFilter filter = new DaggerFilter();
final HttpServletRequest request = createMock(HttpServletRequest.class);
String inRequestKey = IN_REQUEST_KEY.toString();
expect(request.getAttribute(inRequestKey)).andReturn(null);
request.setAttribute(eq(inRequestKey), isA(InRequest.class));
String objectGraphKey = OBJECT_GRAPH_KEY.toString();
expect(request.getAttribute(objectGraphKey)).andReturn(null);
request.setAttribute(eq(objectGraphKey), isA(ObjectGraph.class));
expectLastCall();
String inRequestNullKey = IN_REQUEST_NULLABLE_KEY.toString();
expect(request.getAttribute(inRequestNullKey)).andReturn(null); | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletScopes.java
// enum NullObject {
// INSTANCE
// }
// Path: dagger-servlet/src/test/java/com/leacox/dagger/servlet/ServletTest.java
import dagger.Module;
import dagger.ObjectGraph;
import dagger.Provides;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import javax.inject.Singleton;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import static com.leacox.dagger.servlet.ServletScopes.NullObject;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.isA;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue;
@Override
protected Class<?>[] getRequestScopedModules() {
return new Class<?>[]{TestRequestModule.class};
}
@Override
protected void configureServlets() {
}
};
ServletContext servletContext = createMock(ServletContext.class);
contextListener.contextInitialized(new ServletContextEvent(servletContext));
final ObjectGraph objectGraph = contextListener.getObjectGraph();
DaggerFilter filter = new DaggerFilter();
final HttpServletRequest request = createMock(HttpServletRequest.class);
String inRequestKey = IN_REQUEST_KEY.toString();
expect(request.getAttribute(inRequestKey)).andReturn(null);
request.setAttribute(eq(inRequestKey), isA(InRequest.class));
String objectGraphKey = OBJECT_GRAPH_KEY.toString();
expect(request.getAttribute(objectGraphKey)).andReturn(null);
request.setAttribute(eq(objectGraphKey), isA(ObjectGraph.class));
expectLastCall();
String inRequestNullKey = IN_REQUEST_NULLABLE_KEY.toString();
expect(request.getAttribute(inRequestNullKey)).andReturn(null); | request.setAttribute(eq(inRequestNullKey), eq(NullObject.INSTANCE)); |
johnlcox/dagger-servlet | dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletScopes.java | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/scope/Scope.java
// public interface Scope {
// public <T> T scope(Class<T> type, ObjectGraph baseGraph, Object[] scopedModules);
//
// public <T> T scopeInstance(T value, ObjectGraph baseGraph, Object[] scopedModules);
//
// String toString();
// }
| import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.leacox.dagger.servlet.scope.Scope;
import dagger.ObjectGraph;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.Callable; | this.type = type;
}
public static DaggerKey get(Class<?> type) {
return new DaggerKey(type);
}
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DaggerKey that = (DaggerKey) o;
return Objects.equal(this.type, that.type);
}
@Override
public final int hashCode() {
return Objects.hashCode(type);
}
@Override
public final String toString() {
return "DaggerKey[type=" + type + "]";
}
}
/**
* HTTP servlet request scope.
*/ | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/scope/Scope.java
// public interface Scope {
// public <T> T scope(Class<T> type, ObjectGraph baseGraph, Object[] scopedModules);
//
// public <T> T scopeInstance(T value, ObjectGraph baseGraph, Object[] scopedModules);
//
// String toString();
// }
// Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ServletScopes.java
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.leacox.dagger.servlet.scope.Scope;
import dagger.ObjectGraph;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.Callable;
this.type = type;
}
public static DaggerKey get(Class<?> type) {
return new DaggerKey(type);
}
@Override
public final boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DaggerKey that = (DaggerKey) o;
return Objects.equal(this.type, that.type);
}
@Override
public final int hashCode() {
return Objects.hashCode(type);
}
@Override
public final String toString() {
return "DaggerKey[type=" + type + "]";
}
}
/**
* HTTP servlet request scope.
*/ | public static final Scope REQUEST = new Scope() { |
johnlcox/dagger-servlet | dagger-servlet/src/test/java/com/leacox/dagger/servlet/ServletDispatchIntegrationTest.java | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ManagedServletPipeline.java
// public static final String REQUEST_DISPATCHER_REQUEST = "javax.servlet.forward.servlet_path";
| import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dagger.Module;
import dagger.ObjectGraph;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static com.leacox.dagger.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue; | @Singleton
public static class ForwardingServlet extends HttpServlet {
@Inject
ForwardingServlet() {}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
request.getRequestDispatcher("/blah.jsp")
.forward(servletRequest, servletResponse);
}
}
@Singleton
public static class ForwardedServlet extends HttpServlet {
static int forwardedTo = 0;
// Reset for test.
@Inject
public ForwardedServlet() {
forwardedTo = 0;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
| // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ManagedServletPipeline.java
// public static final String REQUEST_DISPATCHER_REQUEST = "javax.servlet.forward.servlet_path";
// Path: dagger-servlet/src/test/java/com/leacox/dagger/servlet/ServletDispatchIntegrationTest.java
import java.io.IOException;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dagger.Module;
import dagger.ObjectGraph;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static com.leacox.dagger.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.createNiceMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
@Singleton
public static class ForwardingServlet extends HttpServlet {
@Inject
ForwardingServlet() {}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
request.getRequestDispatcher("/blah.jsp")
.forward(servletRequest, servletResponse);
}
}
@Singleton
public static class ForwardedServlet extends HttpServlet {
static int forwardedTo = 0;
// Reset for test.
@Inject
public ForwardedServlet() {
forwardedTo = 0;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
final HttpServletRequest request = (HttpServletRequest) servletRequest;
| assertTrue((Boolean) request.getAttribute(REQUEST_DISPATCHER_REQUEST)); |
johnlcox/dagger-servlet | dagger-servlet/src/test/java/com/leacox/dagger/servlet/ServletDefinitionPathsTest.java | // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ManagedServletPipeline.java
// public static final String REQUEST_DISPATCHER_REQUEST = "javax.servlet.forward.servlet_path";
| import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import dagger.ObjectGraph;
import org.testng.annotations.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import static com.leacox.dagger.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue; | protected void service(HttpServletRequest servletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
final String path = servletRequest.getPathInfo();
if (null == expectedPathInfo) {
assertNull(path, String.format("expected [%s] but was [%s]", expectedPathInfo, path));
} else {
assertEquals(path, expectedPathInfo,
String.format("expected [%s] but was [%s]", expectedPathInfo, path));
}
//assert memoizer
//noinspection StringEquality
assertSame(servletRequest.getPathInfo(), path, "memo field did not work");
run[0] = true;
}
});
expect(request.getRequestURI())
.andReturn(requestUri);
expect(request.getServletPath())
.andReturn(servletPath)
.anyTimes();
expect(request.getContextPath())
.andReturn(contextPath);
| // Path: dagger-servlet/src/main/java/com/leacox/dagger/servlet/ManagedServletPipeline.java
// public static final String REQUEST_DISPATCHER_REQUEST = "javax.servlet.forward.servlet_path";
// Path: dagger-servlet/src/test/java/com/leacox/dagger/servlet/ServletDefinitionPathsTest.java
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import dagger.ObjectGraph;
import org.testng.annotations.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import static com.leacox.dagger.servlet.ManagedServletPipeline.REQUEST_DISPATCHER_REQUEST;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue;
protected void service(HttpServletRequest servletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
final String path = servletRequest.getPathInfo();
if (null == expectedPathInfo) {
assertNull(path, String.format("expected [%s] but was [%s]", expectedPathInfo, path));
} else {
assertEquals(path, expectedPathInfo,
String.format("expected [%s] but was [%s]", expectedPathInfo, path));
}
//assert memoizer
//noinspection StringEquality
assertSame(servletRequest.getPathInfo(), path, "memo field did not work");
run[0] = true;
}
});
expect(request.getRequestURI())
.andReturn(requestUri);
expect(request.getServletPath())
.andReturn(servletPath)
.anyTimes();
expect(request.getContextPath())
.andReturn(contextPath);
| expect(request.getAttribute(REQUEST_DISPATCHER_REQUEST)).andReturn(null); |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/Configuration.java | // Path: src/com/fieldexpert/fbapi4j/dispatch/Dispatch.java
// public interface Dispatch {
//
// Response invoke(String method, URL url);
//
// Response invoke(Request request);
//
// Response invoke(String method, URL url, Request request);
//
// URL getEndpoint();
//
// URL getUrl();
//
// Properties getProperties();
//
// String getProperty(String name);
//
// void setProperty(String name, String value);
//
// String getEmail();
//
// String getPassword();
//
// }
//
// Path: src/com/fieldexpert/fbapi4j/dispatch/HttpDispatch.java
// public final class HttpDispatch implements Dispatch {
//
// private Configuration configuration;
// private DocumentBuilder builder;
//
// public HttpDispatch(Configuration configuration) {
// this.configuration = new Configuration(configuration);
//
// try {
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// builder = factory.newDocumentBuilder();
// } catch (Exception e) {
// throw new DispatchException(e);
// }
// }
//
// public Response invoke(String method, URL url) {
// return invoke(method, url, null);
// }
//
// public Response invoke(Request request) {
// return invoke(Http.POST, configuration.getUrl(), request);
// }
//
// public Response invoke(String method, URL url, Request request) {
// Map<String, String> parameters;
// if (request != null && !request.isEmpty()) {
// parameters = new HashMap<String, String>(request.size());
// for (Entry<String, Object> e : request.entrySet()) {
// String key = e.getKey();
// Object value = e.getValue();
// parameters.put(key, value == null ? "null" : value.toString());
// }
// } else {
// parameters = Collections.emptyMap();
// }
//
// InputStream resp = null;
// if (request != null && request.getAttachments().size() > 0) {
// resp = Http.req(method, url, parameters, request.getAttachments());
// } else {
// resp = Http.req(method, url, parameters);
// }
//
// // for now, we only handle errors from the actual document,
// // in the future, we should refactor a bit so that we can
// // include errors from http as well
// Document document = document(resp);
//
// // possibly throw an exception
// error(document);
//
// return new Response(document);
// }
//
// public URL getEndpoint() {
// return configuration.getEndpoint();
// }
//
// public URL getUrl() {
// return configuration.getUrl();
// }
//
// public Properties getProperties() {
// return configuration.getProperties();
// }
//
// public String getProperty(String name) {
// return configuration.getProperty(name);
// }
//
// public void setProperty(String name, String value) {
// configuration.setProperty(name, value);
// }
//
// private Document document(InputStream input) {
// Document document = null;
// try {
// document = builder.parse(input);
// } catch (Exception e) {
// throw new DispatchException(e);
// }
//
// return document;
// }
//
// public String getEmail() {
// return configuration.getEmail();
// }
//
// public String getPassword() {
// return configuration.getPassword();
// }
//
// private void error(Document document) {
// try {
// Element response = document.getDocumentElement();
// NodeList errors = response.getElementsByTagName("error");
// if (errors.getLength() > 0) {
// Node error = errors.item(0);
// String code = error.getAttributes().getNamedItem("code").getTextContent();
// String message = error.getTextContent();
// throw new DispatchException(code, message);
// }
// } catch (Exception e) {
// throw new DispatchException(e);
// }
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import com.fieldexpert.fbapi4j.dispatch.Dispatch;
import com.fieldexpert.fbapi4j.dispatch.HttpDispatch; | package com.fieldexpert.fbapi4j;
public final class Configuration {
private static final String ENDPOINT = "endpoint";
private static final String EMAIL = "email";
private static final String PASSWORD = "password";
private static final String PATH = "path";
private Properties properties;
public Configuration() {
properties = new Properties();
}
public Configuration(Configuration configuration) {
this.properties = configuration.getProperties();
}
public Session buildSession() {
return new SessionFactory().createSession(this);
}
| // Path: src/com/fieldexpert/fbapi4j/dispatch/Dispatch.java
// public interface Dispatch {
//
// Response invoke(String method, URL url);
//
// Response invoke(Request request);
//
// Response invoke(String method, URL url, Request request);
//
// URL getEndpoint();
//
// URL getUrl();
//
// Properties getProperties();
//
// String getProperty(String name);
//
// void setProperty(String name, String value);
//
// String getEmail();
//
// String getPassword();
//
// }
//
// Path: src/com/fieldexpert/fbapi4j/dispatch/HttpDispatch.java
// public final class HttpDispatch implements Dispatch {
//
// private Configuration configuration;
// private DocumentBuilder builder;
//
// public HttpDispatch(Configuration configuration) {
// this.configuration = new Configuration(configuration);
//
// try {
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// builder = factory.newDocumentBuilder();
// } catch (Exception e) {
// throw new DispatchException(e);
// }
// }
//
// public Response invoke(String method, URL url) {
// return invoke(method, url, null);
// }
//
// public Response invoke(Request request) {
// return invoke(Http.POST, configuration.getUrl(), request);
// }
//
// public Response invoke(String method, URL url, Request request) {
// Map<String, String> parameters;
// if (request != null && !request.isEmpty()) {
// parameters = new HashMap<String, String>(request.size());
// for (Entry<String, Object> e : request.entrySet()) {
// String key = e.getKey();
// Object value = e.getValue();
// parameters.put(key, value == null ? "null" : value.toString());
// }
// } else {
// parameters = Collections.emptyMap();
// }
//
// InputStream resp = null;
// if (request != null && request.getAttachments().size() > 0) {
// resp = Http.req(method, url, parameters, request.getAttachments());
// } else {
// resp = Http.req(method, url, parameters);
// }
//
// // for now, we only handle errors from the actual document,
// // in the future, we should refactor a bit so that we can
// // include errors from http as well
// Document document = document(resp);
//
// // possibly throw an exception
// error(document);
//
// return new Response(document);
// }
//
// public URL getEndpoint() {
// return configuration.getEndpoint();
// }
//
// public URL getUrl() {
// return configuration.getUrl();
// }
//
// public Properties getProperties() {
// return configuration.getProperties();
// }
//
// public String getProperty(String name) {
// return configuration.getProperty(name);
// }
//
// public void setProperty(String name, String value) {
// configuration.setProperty(name, value);
// }
//
// private Document document(InputStream input) {
// Document document = null;
// try {
// document = builder.parse(input);
// } catch (Exception e) {
// throw new DispatchException(e);
// }
//
// return document;
// }
//
// public String getEmail() {
// return configuration.getEmail();
// }
//
// public String getPassword() {
// return configuration.getPassword();
// }
//
// private void error(Document document) {
// try {
// Element response = document.getDocumentElement();
// NodeList errors = response.getElementsByTagName("error");
// if (errors.getLength() > 0) {
// Node error = errors.item(0);
// String code = error.getAttributes().getNamedItem("code").getTextContent();
// String message = error.getTextContent();
// throw new DispatchException(code, message);
// }
// } catch (Exception e) {
// throw new DispatchException(e);
// }
// }
// }
// Path: src/com/fieldexpert/fbapi4j/Configuration.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import com.fieldexpert.fbapi4j.dispatch.Dispatch;
import com.fieldexpert.fbapi4j.dispatch.HttpDispatch;
package com.fieldexpert.fbapi4j;
public final class Configuration {
private static final String ENDPOINT = "endpoint";
private static final String EMAIL = "email";
private static final String PASSWORD = "password";
private static final String PATH = "path";
private Properties properties;
public Configuration() {
properties = new Properties();
}
public Configuration(Configuration configuration) {
this.properties = configuration.getProperties();
}
public Session buildSession() {
return new SessionFactory().createSession(this);
}
| public Dispatch buildDispatch() { |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/Configuration.java | // Path: src/com/fieldexpert/fbapi4j/dispatch/Dispatch.java
// public interface Dispatch {
//
// Response invoke(String method, URL url);
//
// Response invoke(Request request);
//
// Response invoke(String method, URL url, Request request);
//
// URL getEndpoint();
//
// URL getUrl();
//
// Properties getProperties();
//
// String getProperty(String name);
//
// void setProperty(String name, String value);
//
// String getEmail();
//
// String getPassword();
//
// }
//
// Path: src/com/fieldexpert/fbapi4j/dispatch/HttpDispatch.java
// public final class HttpDispatch implements Dispatch {
//
// private Configuration configuration;
// private DocumentBuilder builder;
//
// public HttpDispatch(Configuration configuration) {
// this.configuration = new Configuration(configuration);
//
// try {
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// builder = factory.newDocumentBuilder();
// } catch (Exception e) {
// throw new DispatchException(e);
// }
// }
//
// public Response invoke(String method, URL url) {
// return invoke(method, url, null);
// }
//
// public Response invoke(Request request) {
// return invoke(Http.POST, configuration.getUrl(), request);
// }
//
// public Response invoke(String method, URL url, Request request) {
// Map<String, String> parameters;
// if (request != null && !request.isEmpty()) {
// parameters = new HashMap<String, String>(request.size());
// for (Entry<String, Object> e : request.entrySet()) {
// String key = e.getKey();
// Object value = e.getValue();
// parameters.put(key, value == null ? "null" : value.toString());
// }
// } else {
// parameters = Collections.emptyMap();
// }
//
// InputStream resp = null;
// if (request != null && request.getAttachments().size() > 0) {
// resp = Http.req(method, url, parameters, request.getAttachments());
// } else {
// resp = Http.req(method, url, parameters);
// }
//
// // for now, we only handle errors from the actual document,
// // in the future, we should refactor a bit so that we can
// // include errors from http as well
// Document document = document(resp);
//
// // possibly throw an exception
// error(document);
//
// return new Response(document);
// }
//
// public URL getEndpoint() {
// return configuration.getEndpoint();
// }
//
// public URL getUrl() {
// return configuration.getUrl();
// }
//
// public Properties getProperties() {
// return configuration.getProperties();
// }
//
// public String getProperty(String name) {
// return configuration.getProperty(name);
// }
//
// public void setProperty(String name, String value) {
// configuration.setProperty(name, value);
// }
//
// private Document document(InputStream input) {
// Document document = null;
// try {
// document = builder.parse(input);
// } catch (Exception e) {
// throw new DispatchException(e);
// }
//
// return document;
// }
//
// public String getEmail() {
// return configuration.getEmail();
// }
//
// public String getPassword() {
// return configuration.getPassword();
// }
//
// private void error(Document document) {
// try {
// Element response = document.getDocumentElement();
// NodeList errors = response.getElementsByTagName("error");
// if (errors.getLength() > 0) {
// Node error = errors.item(0);
// String code = error.getAttributes().getNamedItem("code").getTextContent();
// String message = error.getTextContent();
// throw new DispatchException(code, message);
// }
// } catch (Exception e) {
// throw new DispatchException(e);
// }
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import com.fieldexpert.fbapi4j.dispatch.Dispatch;
import com.fieldexpert.fbapi4j.dispatch.HttpDispatch; | package com.fieldexpert.fbapi4j;
public final class Configuration {
private static final String ENDPOINT = "endpoint";
private static final String EMAIL = "email";
private static final String PASSWORD = "password";
private static final String PATH = "path";
private Properties properties;
public Configuration() {
properties = new Properties();
}
public Configuration(Configuration configuration) {
this.properties = configuration.getProperties();
}
public Session buildSession() {
return new SessionFactory().createSession(this);
}
public Dispatch buildDispatch() {
verify(ENDPOINT, EMAIL, PASSWORD); | // Path: src/com/fieldexpert/fbapi4j/dispatch/Dispatch.java
// public interface Dispatch {
//
// Response invoke(String method, URL url);
//
// Response invoke(Request request);
//
// Response invoke(String method, URL url, Request request);
//
// URL getEndpoint();
//
// URL getUrl();
//
// Properties getProperties();
//
// String getProperty(String name);
//
// void setProperty(String name, String value);
//
// String getEmail();
//
// String getPassword();
//
// }
//
// Path: src/com/fieldexpert/fbapi4j/dispatch/HttpDispatch.java
// public final class HttpDispatch implements Dispatch {
//
// private Configuration configuration;
// private DocumentBuilder builder;
//
// public HttpDispatch(Configuration configuration) {
// this.configuration = new Configuration(configuration);
//
// try {
// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// builder = factory.newDocumentBuilder();
// } catch (Exception e) {
// throw new DispatchException(e);
// }
// }
//
// public Response invoke(String method, URL url) {
// return invoke(method, url, null);
// }
//
// public Response invoke(Request request) {
// return invoke(Http.POST, configuration.getUrl(), request);
// }
//
// public Response invoke(String method, URL url, Request request) {
// Map<String, String> parameters;
// if (request != null && !request.isEmpty()) {
// parameters = new HashMap<String, String>(request.size());
// for (Entry<String, Object> e : request.entrySet()) {
// String key = e.getKey();
// Object value = e.getValue();
// parameters.put(key, value == null ? "null" : value.toString());
// }
// } else {
// parameters = Collections.emptyMap();
// }
//
// InputStream resp = null;
// if (request != null && request.getAttachments().size() > 0) {
// resp = Http.req(method, url, parameters, request.getAttachments());
// } else {
// resp = Http.req(method, url, parameters);
// }
//
// // for now, we only handle errors from the actual document,
// // in the future, we should refactor a bit so that we can
// // include errors from http as well
// Document document = document(resp);
//
// // possibly throw an exception
// error(document);
//
// return new Response(document);
// }
//
// public URL getEndpoint() {
// return configuration.getEndpoint();
// }
//
// public URL getUrl() {
// return configuration.getUrl();
// }
//
// public Properties getProperties() {
// return configuration.getProperties();
// }
//
// public String getProperty(String name) {
// return configuration.getProperty(name);
// }
//
// public void setProperty(String name, String value) {
// configuration.setProperty(name, value);
// }
//
// private Document document(InputStream input) {
// Document document = null;
// try {
// document = builder.parse(input);
// } catch (Exception e) {
// throw new DispatchException(e);
// }
//
// return document;
// }
//
// public String getEmail() {
// return configuration.getEmail();
// }
//
// public String getPassword() {
// return configuration.getPassword();
// }
//
// private void error(Document document) {
// try {
// Element response = document.getDocumentElement();
// NodeList errors = response.getElementsByTagName("error");
// if (errors.getLength() > 0) {
// Node error = errors.item(0);
// String code = error.getAttributes().getNamedItem("code").getTextContent();
// String message = error.getTextContent();
// throw new DispatchException(code, message);
// }
// } catch (Exception e) {
// throw new DispatchException(e);
// }
// }
// }
// Path: src/com/fieldexpert/fbapi4j/Configuration.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import com.fieldexpert.fbapi4j.dispatch.Dispatch;
import com.fieldexpert.fbapi4j.dispatch.HttpDispatch;
package com.fieldexpert.fbapi4j;
public final class Configuration {
private static final String ENDPOINT = "endpoint";
private static final String EMAIL = "email";
private static final String PASSWORD = "password";
private static final String PATH = "path";
private Properties properties;
public Configuration() {
properties = new Properties();
}
public Configuration(Configuration configuration) {
this.properties = configuration.getProperties();
}
public Session buildSession() {
return new SessionFactory().createSession(this);
}
public Dispatch buildDispatch() {
verify(ENDPOINT, EMAIL, PASSWORD); | return new HttpDispatch(this); |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/http/MultiPartOutputStream.java | // Path: src/com/fieldexpert/fbapi4j/common/Assert.java
// public class Assert {
//
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void notNull(Object object) {
// notNull(object, "[Assertion failed] - this argument is required; it must not be null");
// }
// }
| import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.fieldexpert.fbapi4j.common.Assert; | package com.fieldexpert.fbapi4j.http;
class MultiPartOutputStream {
private static final String NEWLINE = "\r\n";
private static final String PREFIX = "--";
private final DataOutputStream out;
private final String boundary;
MultiPartOutputStream(OutputStream os, String boundary) {
if (os == null) {
throw new IllegalArgumentException("Outputstream cannot be null.");
}
this.out = new DataOutputStream(os);
this.boundary = boundary;
}
void writeEnd() throws IOException {
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(PREFIX);
out.writeBytes(NEWLINE);
out.flush();
}
private String contentDisposition(String name) {
return "Content-Disposition: form-data; name=\"" + name + "\"";
}
void write(String name, Object value) throws IOException { | // Path: src/com/fieldexpert/fbapi4j/common/Assert.java
// public class Assert {
//
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void notNull(Object object) {
// notNull(object, "[Assertion failed] - this argument is required; it must not be null");
// }
// }
// Path: src/com/fieldexpert/fbapi4j/http/MultiPartOutputStream.java
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.fieldexpert.fbapi4j.common.Assert;
package com.fieldexpert.fbapi4j.http;
class MultiPartOutputStream {
private static final String NEWLINE = "\r\n";
private static final String PREFIX = "--";
private final DataOutputStream out;
private final String boundary;
MultiPartOutputStream(OutputStream os, String boundary) {
if (os == null) {
throw new IllegalArgumentException("Outputstream cannot be null.");
}
this.out = new DataOutputStream(os);
this.boundary = boundary;
}
void writeEnd() throws IOException {
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(PREFIX);
out.writeBytes(NEWLINE);
out.flush();
}
private String contentDisposition(String name) {
return "Content-Disposition: form-data; name=\"" + name + "\"";
}
void write(String name, Object value) throws IOException { | Assert.notNull(name); |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/MuxSession.java | // Path: src/com/fieldexpert/fbapi4j/dispatch/Dispatch.java
// public interface Dispatch {
//
// Response invoke(String method, URL url);
//
// Response invoke(Request request);
//
// Response invoke(String method, URL url, Request request);
//
// URL getEndpoint();
//
// URL getUrl();
//
// Properties getProperties();
//
// String getProperty(String name);
//
// void setProperty(String name, String value);
//
// String getEmail();
//
// String getPassword();
//
// }
| import java.util.List;
import com.fieldexpert.fbapi4j.dispatch.Dispatch; | package com.fieldexpert.fbapi4j;
class MuxSession implements Session {
private ConnectedSession connected;
private Session disconnected;
private Session state;
| // Path: src/com/fieldexpert/fbapi4j/dispatch/Dispatch.java
// public interface Dispatch {
//
// Response invoke(String method, URL url);
//
// Response invoke(Request request);
//
// Response invoke(String method, URL url, Request request);
//
// URL getEndpoint();
//
// URL getUrl();
//
// Properties getProperties();
//
// String getProperty(String name);
//
// void setProperty(String name, String value);
//
// String getEmail();
//
// String getPassword();
//
// }
// Path: src/com/fieldexpert/fbapi4j/MuxSession.java
import java.util.List;
import com.fieldexpert.fbapi4j.dispatch.Dispatch;
package com.fieldexpert.fbapi4j;
class MuxSession implements Session {
private ConnectedSession connected;
private Session disconnected;
private Session state;
| public MuxSession(Dispatch dispatch) { |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/Case.java | // Path: src/com/fieldexpert/fbapi4j/common/StringUtil.java
// public static String collectionToCommaDelimitedString(Collection<?> col) {
// return collectionToDelimitedString(col, ",");
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Assert.java
// public class Assert {
//
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void notNull(Object object) {
// notNull(object, "[Assertion failed] - this argument is required; it must not be null");
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/DateFormatUtil.java
// public class DateFormatUtil {
// public static final String FB_DATE = "yyyy-MM-dd'T'HH:mm:ss'Z'";
//
// private static DateFormat getParser() {
// return new SimpleDateFormat(FB_DATE);
// }
//
// public static String format(Date date) {
// return date == null ? null : getParser().format(date);
// }
//
// public static Date parse(String date) {
// if (date == null || date.equals("")) {
// return null;
// }
// try {
// return getParser().parse(date);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// }
| import static com.fieldexpert.fbapi4j.common.StringUtil.collectionToCommaDelimitedString;
import static java.util.Arrays.asList;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fieldexpert.fbapi4j.common.Assert;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.common.DateFormatUtil; | package com.fieldexpert.fbapi4j;
@EntityConfig(element = "case", list = Fbapi4j.QUERY, single = Fbapi4j.QUERY, id = Fbapi4j.IX_BUG)
public class Case extends Entity { | // Path: src/com/fieldexpert/fbapi4j/common/StringUtil.java
// public static String collectionToCommaDelimitedString(Collection<?> col) {
// return collectionToDelimitedString(col, ",");
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Assert.java
// public class Assert {
//
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void notNull(Object object) {
// notNull(object, "[Assertion failed] - this argument is required; it must not be null");
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/DateFormatUtil.java
// public class DateFormatUtil {
// public static final String FB_DATE = "yyyy-MM-dd'T'HH:mm:ss'Z'";
//
// private static DateFormat getParser() {
// return new SimpleDateFormat(FB_DATE);
// }
//
// public static String format(Date date) {
// return date == null ? null : getParser().format(date);
// }
//
// public static Date parse(String date) {
// if (date == null || date.equals("")) {
// return null;
// }
// try {
// return getParser().parse(date);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// }
// Path: src/com/fieldexpert/fbapi4j/Case.java
import static com.fieldexpert.fbapi4j.common.StringUtil.collectionToCommaDelimitedString;
import static java.util.Arrays.asList;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fieldexpert.fbapi4j.common.Assert;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.common.DateFormatUtil;
package com.fieldexpert.fbapi4j;
@EntityConfig(element = "case", list = Fbapi4j.QUERY, single = Fbapi4j.QUERY, id = Fbapi4j.IX_BUG)
public class Case extends Entity { | private List<Attachment> attachments; |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/Case.java | // Path: src/com/fieldexpert/fbapi4j/common/StringUtil.java
// public static String collectionToCommaDelimitedString(Collection<?> col) {
// return collectionToDelimitedString(col, ",");
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Assert.java
// public class Assert {
//
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void notNull(Object object) {
// notNull(object, "[Assertion failed] - this argument is required; it must not be null");
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/DateFormatUtil.java
// public class DateFormatUtil {
// public static final String FB_DATE = "yyyy-MM-dd'T'HH:mm:ss'Z'";
//
// private static DateFormat getParser() {
// return new SimpleDateFormat(FB_DATE);
// }
//
// public static String format(Date date) {
// return date == null ? null : getParser().format(date);
// }
//
// public static Date parse(String date) {
// if (date == null || date.equals("")) {
// return null;
// }
// try {
// return getParser().parse(date);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// }
| import static com.fieldexpert.fbapi4j.common.StringUtil.collectionToCommaDelimitedString;
import static java.util.Arrays.asList;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fieldexpert.fbapi4j.common.Assert;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.common.DateFormatUtil; | package com.fieldexpert.fbapi4j;
@EntityConfig(element = "case", list = Fbapi4j.QUERY, single = Fbapi4j.QUERY, id = Fbapi4j.IX_BUG)
public class Case extends Entity {
private List<Attachment> attachments;
private List<Event> events;
private Set<AllowedOperation> allowedOperations;
public Case(String project, String area, String title, String description) {
this(null, project, area, title, description);
}
Case(Integer id, String project, String area, String title, String description) {
this(id, project, area, title, description, new ArrayList<Event>());
}
Case(Integer id, String project, String area, String title, String description, List<Event> events) {
fields.put(Fbapi4j.S_PROJECT, project);
fields.put(Fbapi4j.S_AREA, area);
fields.put(Fbapi4j.S_TITLE, title);
fields.put(Fbapi4j.S_EVENT, description);
fields.put(Fbapi4j.IX_BUG, id);
this.attachments = new ArrayList<Attachment>();
this.events = events;
}
public Case attach(Attachment attachment) { | // Path: src/com/fieldexpert/fbapi4j/common/StringUtil.java
// public static String collectionToCommaDelimitedString(Collection<?> col) {
// return collectionToDelimitedString(col, ",");
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Assert.java
// public class Assert {
//
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void notNull(Object object) {
// notNull(object, "[Assertion failed] - this argument is required; it must not be null");
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/DateFormatUtil.java
// public class DateFormatUtil {
// public static final String FB_DATE = "yyyy-MM-dd'T'HH:mm:ss'Z'";
//
// private static DateFormat getParser() {
// return new SimpleDateFormat(FB_DATE);
// }
//
// public static String format(Date date) {
// return date == null ? null : getParser().format(date);
// }
//
// public static Date parse(String date) {
// if (date == null || date.equals("")) {
// return null;
// }
// try {
// return getParser().parse(date);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// }
// Path: src/com/fieldexpert/fbapi4j/Case.java
import static com.fieldexpert.fbapi4j.common.StringUtil.collectionToCommaDelimitedString;
import static java.util.Arrays.asList;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fieldexpert.fbapi4j.common.Assert;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.common.DateFormatUtil;
package com.fieldexpert.fbapi4j;
@EntityConfig(element = "case", list = Fbapi4j.QUERY, single = Fbapi4j.QUERY, id = Fbapi4j.IX_BUG)
public class Case extends Entity {
private List<Attachment> attachments;
private List<Event> events;
private Set<AllowedOperation> allowedOperations;
public Case(String project, String area, String title, String description) {
this(null, project, area, title, description);
}
Case(Integer id, String project, String area, String title, String description) {
this(id, project, area, title, description, new ArrayList<Event>());
}
Case(Integer id, String project, String area, String title, String description, List<Event> events) {
fields.put(Fbapi4j.S_PROJECT, project);
fields.put(Fbapi4j.S_AREA, area);
fields.put(Fbapi4j.S_TITLE, title);
fields.put(Fbapi4j.S_EVENT, description);
fields.put(Fbapi4j.IX_BUG, id);
this.attachments = new ArrayList<Attachment>();
this.events = events;
}
public Case attach(Attachment attachment) { | Assert.notNull(attachment); |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/Case.java | // Path: src/com/fieldexpert/fbapi4j/common/StringUtil.java
// public static String collectionToCommaDelimitedString(Collection<?> col) {
// return collectionToDelimitedString(col, ",");
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Assert.java
// public class Assert {
//
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void notNull(Object object) {
// notNull(object, "[Assertion failed] - this argument is required; it must not be null");
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/DateFormatUtil.java
// public class DateFormatUtil {
// public static final String FB_DATE = "yyyy-MM-dd'T'HH:mm:ss'Z'";
//
// private static DateFormat getParser() {
// return new SimpleDateFormat(FB_DATE);
// }
//
// public static String format(Date date) {
// return date == null ? null : getParser().format(date);
// }
//
// public static Date parse(String date) {
// if (date == null || date.equals("")) {
// return null;
// }
// try {
// return getParser().parse(date);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// }
| import static com.fieldexpert.fbapi4j.common.StringUtil.collectionToCommaDelimitedString;
import static java.util.Arrays.asList;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fieldexpert.fbapi4j.common.Assert;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.common.DateFormatUtil; | }
public String getTitle() {
return (String) fields.get(Fbapi4j.S_TITLE);
}
public String getScoutDescription() {
return (String) fields.get(Fbapi4j.S_SCOUT_DESCRIPTION);
}
public List<Attachment> getAttachments() {
return Collections.unmodifiableList(this.attachments);
}
public List<Event> getEvents() {
return Collections.unmodifiableList(this.events);
}
public void setArea(String area) {
fields.put(Fbapi4j.S_AREA, area);
}
public void setParent(Case parent) {
if (parent.getId() == null) {
throw new Fbapi4jException("The parent case must be persisted first");
}
fields.put(Fbapi4j.IX_BUG_PARENT, parent.getId());
}
public void setTags(String... tags) { | // Path: src/com/fieldexpert/fbapi4j/common/StringUtil.java
// public static String collectionToCommaDelimitedString(Collection<?> col) {
// return collectionToDelimitedString(col, ",");
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Assert.java
// public class Assert {
//
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void notNull(Object object) {
// notNull(object, "[Assertion failed] - this argument is required; it must not be null");
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/DateFormatUtil.java
// public class DateFormatUtil {
// public static final String FB_DATE = "yyyy-MM-dd'T'HH:mm:ss'Z'";
//
// private static DateFormat getParser() {
// return new SimpleDateFormat(FB_DATE);
// }
//
// public static String format(Date date) {
// return date == null ? null : getParser().format(date);
// }
//
// public static Date parse(String date) {
// if (date == null || date.equals("")) {
// return null;
// }
// try {
// return getParser().parse(date);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// }
// Path: src/com/fieldexpert/fbapi4j/Case.java
import static com.fieldexpert.fbapi4j.common.StringUtil.collectionToCommaDelimitedString;
import static java.util.Arrays.asList;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fieldexpert.fbapi4j.common.Assert;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.common.DateFormatUtil;
}
public String getTitle() {
return (String) fields.get(Fbapi4j.S_TITLE);
}
public String getScoutDescription() {
return (String) fields.get(Fbapi4j.S_SCOUT_DESCRIPTION);
}
public List<Attachment> getAttachments() {
return Collections.unmodifiableList(this.attachments);
}
public List<Event> getEvents() {
return Collections.unmodifiableList(this.events);
}
public void setArea(String area) {
fields.put(Fbapi4j.S_AREA, area);
}
public void setParent(Case parent) {
if (parent.getId() == null) {
throw new Fbapi4jException("The parent case must be persisted first");
}
fields.put(Fbapi4j.IX_BUG_PARENT, parent.getId());
}
public void setTags(String... tags) { | fields.put(Fbapi4j.S_TAGS, collectionToCommaDelimitedString(asList(tags))); |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/Case.java | // Path: src/com/fieldexpert/fbapi4j/common/StringUtil.java
// public static String collectionToCommaDelimitedString(Collection<?> col) {
// return collectionToDelimitedString(col, ",");
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Assert.java
// public class Assert {
//
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void notNull(Object object) {
// notNull(object, "[Assertion failed] - this argument is required; it must not be null");
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/DateFormatUtil.java
// public class DateFormatUtil {
// public static final String FB_DATE = "yyyy-MM-dd'T'HH:mm:ss'Z'";
//
// private static DateFormat getParser() {
// return new SimpleDateFormat(FB_DATE);
// }
//
// public static String format(Date date) {
// return date == null ? null : getParser().format(date);
// }
//
// public static Date parse(String date) {
// if (date == null || date.equals("")) {
// return null;
// }
// try {
// return getParser().parse(date);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// }
| import static com.fieldexpert.fbapi4j.common.StringUtil.collectionToCommaDelimitedString;
import static java.util.Arrays.asList;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fieldexpert.fbapi4j.common.Assert;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.common.DateFormatUtil; | fields.put(Fbapi4j.S_AREA, area);
}
public void setParent(Case parent) {
if (parent.getId() == null) {
throw new Fbapi4jException("The parent case must be persisted first");
}
fields.put(Fbapi4j.IX_BUG_PARENT, parent.getId());
}
public void setTags(String... tags) {
fields.put(Fbapi4j.S_TAGS, collectionToCommaDelimitedString(asList(tags)));
}
public void setDescription(String description) {
fields.put(Fbapi4j.S_EVENT, description);
}
public void setPriority(int priority) {
if (priority < 1 || priority > 7) {
throw new IllegalArgumentException("Priority must be between 1 and 7");
}
fields.put(Fbapi4j.IX_PRIORITY, priority);
}
public void setPriority(Priority priority) {
setPriority(priority.getId().intValue());
}
public void setDueDate(Date date) { | // Path: src/com/fieldexpert/fbapi4j/common/StringUtil.java
// public static String collectionToCommaDelimitedString(Collection<?> col) {
// return collectionToDelimitedString(col, ",");
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Assert.java
// public class Assert {
//
// public static void notNull(Object object, String message) {
// if (object == null) {
// throw new IllegalArgumentException(message);
// }
// }
//
// public static void notNull(Object object) {
// notNull(object, "[Assertion failed] - this argument is required; it must not be null");
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/DateFormatUtil.java
// public class DateFormatUtil {
// public static final String FB_DATE = "yyyy-MM-dd'T'HH:mm:ss'Z'";
//
// private static DateFormat getParser() {
// return new SimpleDateFormat(FB_DATE);
// }
//
// public static String format(Date date) {
// return date == null ? null : getParser().format(date);
// }
//
// public static Date parse(String date) {
// if (date == null || date.equals("")) {
// return null;
// }
// try {
// return getParser().parse(date);
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// }
// Path: src/com/fieldexpert/fbapi4j/Case.java
import static com.fieldexpert.fbapi4j.common.StringUtil.collectionToCommaDelimitedString;
import static java.util.Arrays.asList;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.fieldexpert.fbapi4j.common.Assert;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.common.DateFormatUtil;
fields.put(Fbapi4j.S_AREA, area);
}
public void setParent(Case parent) {
if (parent.getId() == null) {
throw new Fbapi4jException("The parent case must be persisted first");
}
fields.put(Fbapi4j.IX_BUG_PARENT, parent.getId());
}
public void setTags(String... tags) {
fields.put(Fbapi4j.S_TAGS, collectionToCommaDelimitedString(asList(tags)));
}
public void setDescription(String description) {
fields.put(Fbapi4j.S_EVENT, description);
}
public void setPriority(int priority) {
if (priority < 1 || priority > 7) {
throw new IllegalArgumentException("Priority must be between 1 and 7");
}
fields.put(Fbapi4j.IX_PRIORITY, priority);
}
public void setPriority(Priority priority) {
setPriority(priority.getId().intValue());
}
public void setDueDate(Date date) { | fields.put(Fbapi4j.DT_DUE, DateFormatUtil.format(date)); |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/SessionFactory.java | // Path: src/com/fieldexpert/fbapi4j/dispatch/Dispatch.java
// public interface Dispatch {
//
// Response invoke(String method, URL url);
//
// Response invoke(Request request);
//
// Response invoke(String method, URL url, Request request);
//
// URL getEndpoint();
//
// URL getUrl();
//
// Properties getProperties();
//
// String getProperty(String name);
//
// void setProperty(String name, String value);
//
// String getEmail();
//
// String getPassword();
//
// }
| import com.fieldexpert.fbapi4j.dispatch.Dispatch; | package com.fieldexpert.fbapi4j;
class SessionFactory {
Session createSession(Configuration configuration) {
return new MuxSession(configuration.buildDispatch());
}
| // Path: src/com/fieldexpert/fbapi4j/dispatch/Dispatch.java
// public interface Dispatch {
//
// Response invoke(String method, URL url);
//
// Response invoke(Request request);
//
// Response invoke(String method, URL url, Request request);
//
// URL getEndpoint();
//
// URL getUrl();
//
// Properties getProperties();
//
// String getProperty(String name);
//
// void setProperty(String name, String value);
//
// String getEmail();
//
// String getPassword();
//
// }
// Path: src/com/fieldexpert/fbapi4j/SessionFactory.java
import com.fieldexpert.fbapi4j.dispatch.Dispatch;
package com.fieldexpert.fbapi4j;
class SessionFactory {
Session createSession(Configuration configuration) {
return new MuxSession(configuration.buildDispatch());
}
| Session createSession(Dispatch dispatch) { |
fieldexpert/fbapi4j | test/com/fieldexpert/fbapi4j/http/HttpTest.java | // Path: test/com/fieldexpert/fbapi4j/common/IOUtil.java
// public static String string(File file) throws java.io.IOException {
// return string(new FileInputStream(file));
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: test/com/fieldexpert/fbapi4j/http/server/MockServer.java
// public class MockServer {
// private final HttpServer server;
//
// public MockServer(String path) {
// this("127.0.0.1", 9000, path);
// }
//
// public MockServer(int port, String path) {
// this("127.0.0.1", port, path);
// }
//
// public MockServer(String host, int port, String path) {
// InetSocketAddress address = new InetSocketAddress(host, port);
// try {
// server = HttpServer.create(address, 0);
// HttpContext context = server.createContext(path, new EchoHandler());
// context.getFilters().add(new ParamsFilter());
// } catch (IOException e) {
// throw new RuntimeException("Unable to create server on " + host + ":" + port);
// }
// }
//
// public void start() {
// server.start();
// }
//
// public void stop() {
// if (server == null) {
// return;
// }
// server.stop(0);
// }
//
// }
| import static com.fieldexpert.fbapi4j.common.IOUtil.string;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.http.server.MockServer; | package com.fieldexpert.fbapi4j.http;
public class HttpTest {
private static MockServer server;
private static URL url;
private Map<String, String> params;
@Test
public void get() throws IOException {
InputStream is = Http.get(url, params);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Map<String, String> returnedParams = params(br.readLine());
assertEquals(params, returnedParams);
}
@Test
public void post() throws IOException {
InputStream is = Http.post(url, params);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Map<String, String> returnedParams = params(br.readLine());
assertEquals(params, returnedParams);
}
@Test
public void attachment() throws IOException { | // Path: test/com/fieldexpert/fbapi4j/common/IOUtil.java
// public static String string(File file) throws java.io.IOException {
// return string(new FileInputStream(file));
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: test/com/fieldexpert/fbapi4j/http/server/MockServer.java
// public class MockServer {
// private final HttpServer server;
//
// public MockServer(String path) {
// this("127.0.0.1", 9000, path);
// }
//
// public MockServer(int port, String path) {
// this("127.0.0.1", port, path);
// }
//
// public MockServer(String host, int port, String path) {
// InetSocketAddress address = new InetSocketAddress(host, port);
// try {
// server = HttpServer.create(address, 0);
// HttpContext context = server.createContext(path, new EchoHandler());
// context.getFilters().add(new ParamsFilter());
// } catch (IOException e) {
// throw new RuntimeException("Unable to create server on " + host + ":" + port);
// }
// }
//
// public void start() {
// server.start();
// }
//
// public void stop() {
// if (server == null) {
// return;
// }
// server.stop(0);
// }
//
// }
// Path: test/com/fieldexpert/fbapi4j/http/HttpTest.java
import static com.fieldexpert.fbapi4j.common.IOUtil.string;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.http.server.MockServer;
package com.fieldexpert.fbapi4j.http;
public class HttpTest {
private static MockServer server;
private static URL url;
private Map<String, String> params;
@Test
public void get() throws IOException {
InputStream is = Http.get(url, params);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Map<String, String> returnedParams = params(br.readLine());
assertEquals(params, returnedParams);
}
@Test
public void post() throws IOException {
InputStream is = Http.post(url, params);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Map<String, String> returnedParams = params(br.readLine());
assertEquals(params, returnedParams);
}
@Test
public void attachment() throws IOException { | List<Attachment> attachments = asList(new Attachment("foo.txt", "text/plain", "This is my test file.")); |
fieldexpert/fbapi4j | test/com/fieldexpert/fbapi4j/http/HttpTest.java | // Path: test/com/fieldexpert/fbapi4j/common/IOUtil.java
// public static String string(File file) throws java.io.IOException {
// return string(new FileInputStream(file));
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: test/com/fieldexpert/fbapi4j/http/server/MockServer.java
// public class MockServer {
// private final HttpServer server;
//
// public MockServer(String path) {
// this("127.0.0.1", 9000, path);
// }
//
// public MockServer(int port, String path) {
// this("127.0.0.1", port, path);
// }
//
// public MockServer(String host, int port, String path) {
// InetSocketAddress address = new InetSocketAddress(host, port);
// try {
// server = HttpServer.create(address, 0);
// HttpContext context = server.createContext(path, new EchoHandler());
// context.getFilters().add(new ParamsFilter());
// } catch (IOException e) {
// throw new RuntimeException("Unable to create server on " + host + ":" + port);
// }
// }
//
// public void start() {
// server.start();
// }
//
// public void stop() {
// if (server == null) {
// return;
// }
// server.stop(0);
// }
//
// }
| import static com.fieldexpert.fbapi4j.common.IOUtil.string;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.http.server.MockServer; | package com.fieldexpert.fbapi4j.http;
public class HttpTest {
private static MockServer server;
private static URL url;
private Map<String, String> params;
@Test
public void get() throws IOException {
InputStream is = Http.get(url, params);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Map<String, String> returnedParams = params(br.readLine());
assertEquals(params, returnedParams);
}
@Test
public void post() throws IOException {
InputStream is = Http.post(url, params);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Map<String, String> returnedParams = params(br.readLine());
assertEquals(params, returnedParams);
}
@Test
public void attachment() throws IOException {
List<Attachment> attachments = asList(new Attachment("foo.txt", "text/plain", "This is my test file."));
InputStream is = Http.post(url, params, attachments);
| // Path: test/com/fieldexpert/fbapi4j/common/IOUtil.java
// public static String string(File file) throws java.io.IOException {
// return string(new FileInputStream(file));
// }
//
// Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
//
// Path: test/com/fieldexpert/fbapi4j/http/server/MockServer.java
// public class MockServer {
// private final HttpServer server;
//
// public MockServer(String path) {
// this("127.0.0.1", 9000, path);
// }
//
// public MockServer(int port, String path) {
// this("127.0.0.1", port, path);
// }
//
// public MockServer(String host, int port, String path) {
// InetSocketAddress address = new InetSocketAddress(host, port);
// try {
// server = HttpServer.create(address, 0);
// HttpContext context = server.createContext(path, new EchoHandler());
// context.getFilters().add(new ParamsFilter());
// } catch (IOException e) {
// throw new RuntimeException("Unable to create server on " + host + ":" + port);
// }
// }
//
// public void start() {
// server.start();
// }
//
// public void stop() {
// if (server == null) {
// return;
// }
// server.stop(0);
// }
//
// }
// Path: test/com/fieldexpert/fbapi4j/http/HttpTest.java
import static com.fieldexpert.fbapi4j.common.IOUtil.string;
import static java.util.Arrays.asList;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fieldexpert.fbapi4j.common.Attachment;
import com.fieldexpert.fbapi4j.http.server.MockServer;
package com.fieldexpert.fbapi4j.http;
public class HttpTest {
private static MockServer server;
private static URL url;
private Map<String, String> params;
@Test
public void get() throws IOException {
InputStream is = Http.get(url, params);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Map<String, String> returnedParams = params(br.readLine());
assertEquals(params, returnedParams);
}
@Test
public void post() throws IOException {
InputStream is = Http.post(url, params);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Map<String, String> returnedParams = params(br.readLine());
assertEquals(params, returnedParams);
}
@Test
public void attachment() throws IOException {
List<Attachment> attachments = asList(new Attachment("foo.txt", "text/plain", "This is my test file."));
InputStream is = Http.post(url, params, attachments);
| Map<String, String> returnedParams = params(string(is)); |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/Event.java | // Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
| import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import com.fieldexpert.fbapi4j.common.Attachment; | this.description = description;
this.date = date;
this.createdBy = createdBy;
this.attachments = attachments;
}
public String getId() {
return id;
}
public Case getBug() {
return bug;
}
public String getVerb() {
return verb;
}
public String getDescription() {
return description;
}
public Date getDate() {
return date;
}
public String getCreatedBy() {
return createdBy;
}
| // Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
// Path: src/com/fieldexpert/fbapi4j/Event.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import com.fieldexpert.fbapi4j.common.Attachment;
this.description = description;
this.date = date;
this.createdBy = createdBy;
this.attachments = attachments;
}
public String getId() {
return id;
}
public Case getBug() {
return bug;
}
public String getVerb() {
return verb;
}
public String getDescription() {
return description;
}
public Date getDate() {
return date;
}
public String getCreatedBy() {
return createdBy;
}
| public List<? extends Attachment> getAttachments() { |
fieldexpert/fbapi4j | test/com/fieldexpert/fbapi4j/http/server/ParameterParser.java | // Path: test/com/fieldexpert/fbapi4j/common/IOUtil.java
// public static String string(File file) throws java.io.IOException {
// return string(new FileInputStream(file));
// }
| import static com.fieldexpert.fbapi4j.common.IOUtil.string;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange; | package com.fieldexpert.fbapi4j.http.server;
class ParameterParser {
Map<String, String> parse(HttpExchange exchange) throws UnsupportedEncodingException, IOException {
if ("get".equalsIgnoreCase(exchange.getRequestMethod())) {
URI requestedUri = exchange.getRequestURI();
return parseQuery(requestedUri.getRawQuery());
} else if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
Headers headers = exchange.getRequestHeaders();
String contentType = headers.get("Content-Type").get(0);
if (contentType.startsWith("multipart/form-data")) {
return parseMultiForm(exchange);
} else { | // Path: test/com/fieldexpert/fbapi4j/common/IOUtil.java
// public static String string(File file) throws java.io.IOException {
// return string(new FileInputStream(file));
// }
// Path: test/com/fieldexpert/fbapi4j/http/server/ParameterParser.java
import static com.fieldexpert.fbapi4j.common.IOUtil.string;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
package com.fieldexpert.fbapi4j.http.server;
class ParameterParser {
Map<String, String> parse(HttpExchange exchange) throws UnsupportedEncodingException, IOException {
if ("get".equalsIgnoreCase(exchange.getRequestMethod())) {
URI requestedUri = exchange.getRequestURI();
return parseQuery(requestedUri.getRawQuery());
} else if ("post".equalsIgnoreCase(exchange.getRequestMethod())) {
Headers headers = exchange.getRequestHeaders();
String contentType = headers.get("Content-Type").get(0);
if (contentType.startsWith("multipart/form-data")) {
return parseMultiForm(exchange);
} else { | return parseQuery(string(exchange.getRequestBody())); |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/http/Http.java | // Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
| import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
import com.fieldexpert.fbapi4j.common.Attachment; | package com.fieldexpert.fbapi4j.http;
public class Http {
public static final String GET = "GET";
public static final String POST = "POST";
public static InputStream get(URL url, Map<String, String> parameters) {
return req(GET, url, parameters);
}
public static InputStream post(URL url, Map<String, String> parameters) {
return req(POST, url, parameters);
}
| // Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
// Path: src/com/fieldexpert/fbapi4j/http/Http.java
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;
import com.fieldexpert.fbapi4j.common.Attachment;
package com.fieldexpert.fbapi4j.http;
public class Http {
public static final String GET = "GET";
public static final String POST = "POST";
public static InputStream get(URL url, Map<String, String> parameters) {
return req(GET, url, parameters);
}
public static InputStream post(URL url, Map<String, String> parameters) {
return req(POST, url, parameters);
}
| public static InputStream post(URL url, Map<String, String> parameters, List<Attachment> attachments) { |
fieldexpert/fbapi4j | test/com/fieldexpert/fbapi4j/SessionTest.java | // Path: src/com/fieldexpert/fbapi4j/Configuration.java
// public final class Configuration {
//
// private static final String ENDPOINT = "endpoint";
// private static final String EMAIL = "email";
// private static final String PASSWORD = "password";
// private static final String PATH = "path";
//
// private Properties properties;
//
// public Configuration() {
// properties = new Properties();
// }
//
// public Configuration(Configuration configuration) {
// this.properties = configuration.getProperties();
// }
//
// public Session buildSession() {
// return new SessionFactory().createSession(this);
// }
//
// public Dispatch buildDispatch() {
// verify(ENDPOINT, EMAIL, PASSWORD);
// return new HttpDispatch(this);
// }
//
// /**
// * Merge <tt>properties</tt> into the current properties.
// */
// public Configuration addProperties(Properties properties) {
// this.properties.putAll(properties);
// return this;
// }
//
// private InputStream configurationStream(String path) {
// try {
// return this.getClass().getClassLoader().getResourceAsStream(path);
// } catch (Exception e) {
// throw new RuntimeException("Could not find file: " + path, e);
// }
// }
//
// /**
// * Use the properties specified in the resource <tt>fb4api.properties</tt>.
// */
// public Configuration configure() {
// return configure("fbapi4j.properties");
// }
//
// /**
// * Use <tt>file</tt> to build the properties.
// */
// public Configuration configure(File file) {
// try {
// return configure(new FileInputStream(file));
// } catch (IOException e) {
// throw new RuntimeException("Could not open file: " + file, e);
// }
// }
//
// private Configuration configure(InputStream stream) {
// try {
// this.properties.load(stream);
// } catch (IOException e) {
// throw new RuntimeException("Could not load properties from InputStream: " + e);
// }
// return this;
// }
//
// /**
// * Use the properties specified in <tt>resource</tt>.
// */
// public Configuration configure(String resource) {
// InputStream stream = configurationStream(resource);
// return configure(stream);
// }
//
// /**
// * Use the properties specified in <tt>url</tt>.
// */
// public Configuration configure(URL url) {
// try {
// return configure(url.openStream());
// } catch (IOException e) {
// throw new RuntimeException("Could not configure from URL: " + url, e);
// }
// }
//
// public String getEmail() {
// verify(EMAIL);
// return getProperty(EMAIL);
// }
//
// public URL getEndpoint() {
// verify(ENDPOINT);
// URL url = null;
// try {
// url = new URL(getProperty(ENDPOINT));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return url;
// }
//
// public String getPassword() {
// verify(PASSWORD);
// return getProperty(PASSWORD);
// }
//
// public Properties getProperties() {
// Properties properties = new Properties();
// properties.putAll(this.properties);
// return properties;
// }
//
// public String getProperty(String name) {
// return properties.getProperty(name);
// }
//
// public String getPath() {
// return properties.getProperty(PATH);
// }
//
// public URL getUrl() {
// verify(PATH);
// URL url = null;
// try {
// url = new URL(getEndpoint(), getProperty(PATH));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return url;
// }
//
// /**
// * Override current properties with new <tt>properties</tt>.
// */
// public Configuration setProperties(Properties properties) {
// this.properties = properties;
// return this;
// }
//
// /**
// * Set a property.
// */
// public Configuration setProperty(String name, String value) {
// properties.setProperty(name, value);
// return this;
// }
//
// private void verify(String... properties) {
// for (String prop : properties) {
// if (!this.properties.containsKey(prop)) {
// throw new IllegalStateException("Properties file missing property '" + prop + "'");
// }
// }
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/Session.java
// public interface Session {
//
// void close();
//
// void close(Case bug);
//
// void create(Entity t);
//
// List<Case> query(String... criterion);
//
// <T extends Entity> T get(Class<T> clazz, Integer id);
//
// <T extends Entity> T get(Class<T> clazz, String name);
//
// <T extends Entity> List<T> findAll(Class<T> clazz);
//
// void edit(Case bug);
//
// void reactivate(Case bug);
//
// void reopen(Case bug);
//
// void resolve(Case bug);
//
// void scout(Case bug);
//
// }
| import org.junit.Test;
import com.fieldexpert.fbapi4j.Configuration;
import com.fieldexpert.fbapi4j.Session; | package com.fieldexpert.fbapi4j;
public class SessionTest {
@Test
public void neverConnects() { | // Path: src/com/fieldexpert/fbapi4j/Configuration.java
// public final class Configuration {
//
// private static final String ENDPOINT = "endpoint";
// private static final String EMAIL = "email";
// private static final String PASSWORD = "password";
// private static final String PATH = "path";
//
// private Properties properties;
//
// public Configuration() {
// properties = new Properties();
// }
//
// public Configuration(Configuration configuration) {
// this.properties = configuration.getProperties();
// }
//
// public Session buildSession() {
// return new SessionFactory().createSession(this);
// }
//
// public Dispatch buildDispatch() {
// verify(ENDPOINT, EMAIL, PASSWORD);
// return new HttpDispatch(this);
// }
//
// /**
// * Merge <tt>properties</tt> into the current properties.
// */
// public Configuration addProperties(Properties properties) {
// this.properties.putAll(properties);
// return this;
// }
//
// private InputStream configurationStream(String path) {
// try {
// return this.getClass().getClassLoader().getResourceAsStream(path);
// } catch (Exception e) {
// throw new RuntimeException("Could not find file: " + path, e);
// }
// }
//
// /**
// * Use the properties specified in the resource <tt>fb4api.properties</tt>.
// */
// public Configuration configure() {
// return configure("fbapi4j.properties");
// }
//
// /**
// * Use <tt>file</tt> to build the properties.
// */
// public Configuration configure(File file) {
// try {
// return configure(new FileInputStream(file));
// } catch (IOException e) {
// throw new RuntimeException("Could not open file: " + file, e);
// }
// }
//
// private Configuration configure(InputStream stream) {
// try {
// this.properties.load(stream);
// } catch (IOException e) {
// throw new RuntimeException("Could not load properties from InputStream: " + e);
// }
// return this;
// }
//
// /**
// * Use the properties specified in <tt>resource</tt>.
// */
// public Configuration configure(String resource) {
// InputStream stream = configurationStream(resource);
// return configure(stream);
// }
//
// /**
// * Use the properties specified in <tt>url</tt>.
// */
// public Configuration configure(URL url) {
// try {
// return configure(url.openStream());
// } catch (IOException e) {
// throw new RuntimeException("Could not configure from URL: " + url, e);
// }
// }
//
// public String getEmail() {
// verify(EMAIL);
// return getProperty(EMAIL);
// }
//
// public URL getEndpoint() {
// verify(ENDPOINT);
// URL url = null;
// try {
// url = new URL(getProperty(ENDPOINT));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return url;
// }
//
// public String getPassword() {
// verify(PASSWORD);
// return getProperty(PASSWORD);
// }
//
// public Properties getProperties() {
// Properties properties = new Properties();
// properties.putAll(this.properties);
// return properties;
// }
//
// public String getProperty(String name) {
// return properties.getProperty(name);
// }
//
// public String getPath() {
// return properties.getProperty(PATH);
// }
//
// public URL getUrl() {
// verify(PATH);
// URL url = null;
// try {
// url = new URL(getEndpoint(), getProperty(PATH));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return url;
// }
//
// /**
// * Override current properties with new <tt>properties</tt>.
// */
// public Configuration setProperties(Properties properties) {
// this.properties = properties;
// return this;
// }
//
// /**
// * Set a property.
// */
// public Configuration setProperty(String name, String value) {
// properties.setProperty(name, value);
// return this;
// }
//
// private void verify(String... properties) {
// for (String prop : properties) {
// if (!this.properties.containsKey(prop)) {
// throw new IllegalStateException("Properties file missing property '" + prop + "'");
// }
// }
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/Session.java
// public interface Session {
//
// void close();
//
// void close(Case bug);
//
// void create(Entity t);
//
// List<Case> query(String... criterion);
//
// <T extends Entity> T get(Class<T> clazz, Integer id);
//
// <T extends Entity> T get(Class<T> clazz, String name);
//
// <T extends Entity> List<T> findAll(Class<T> clazz);
//
// void edit(Case bug);
//
// void reactivate(Case bug);
//
// void reopen(Case bug);
//
// void resolve(Case bug);
//
// void scout(Case bug);
//
// }
// Path: test/com/fieldexpert/fbapi4j/SessionTest.java
import org.junit.Test;
import com.fieldexpert.fbapi4j.Configuration;
import com.fieldexpert.fbapi4j.Session;
package com.fieldexpert.fbapi4j;
public class SessionTest {
@Test
public void neverConnects() { | Configuration config = new Configuration().configure(); |
fieldexpert/fbapi4j | test/com/fieldexpert/fbapi4j/SessionTest.java | // Path: src/com/fieldexpert/fbapi4j/Configuration.java
// public final class Configuration {
//
// private static final String ENDPOINT = "endpoint";
// private static final String EMAIL = "email";
// private static final String PASSWORD = "password";
// private static final String PATH = "path";
//
// private Properties properties;
//
// public Configuration() {
// properties = new Properties();
// }
//
// public Configuration(Configuration configuration) {
// this.properties = configuration.getProperties();
// }
//
// public Session buildSession() {
// return new SessionFactory().createSession(this);
// }
//
// public Dispatch buildDispatch() {
// verify(ENDPOINT, EMAIL, PASSWORD);
// return new HttpDispatch(this);
// }
//
// /**
// * Merge <tt>properties</tt> into the current properties.
// */
// public Configuration addProperties(Properties properties) {
// this.properties.putAll(properties);
// return this;
// }
//
// private InputStream configurationStream(String path) {
// try {
// return this.getClass().getClassLoader().getResourceAsStream(path);
// } catch (Exception e) {
// throw new RuntimeException("Could not find file: " + path, e);
// }
// }
//
// /**
// * Use the properties specified in the resource <tt>fb4api.properties</tt>.
// */
// public Configuration configure() {
// return configure("fbapi4j.properties");
// }
//
// /**
// * Use <tt>file</tt> to build the properties.
// */
// public Configuration configure(File file) {
// try {
// return configure(new FileInputStream(file));
// } catch (IOException e) {
// throw new RuntimeException("Could not open file: " + file, e);
// }
// }
//
// private Configuration configure(InputStream stream) {
// try {
// this.properties.load(stream);
// } catch (IOException e) {
// throw new RuntimeException("Could not load properties from InputStream: " + e);
// }
// return this;
// }
//
// /**
// * Use the properties specified in <tt>resource</tt>.
// */
// public Configuration configure(String resource) {
// InputStream stream = configurationStream(resource);
// return configure(stream);
// }
//
// /**
// * Use the properties specified in <tt>url</tt>.
// */
// public Configuration configure(URL url) {
// try {
// return configure(url.openStream());
// } catch (IOException e) {
// throw new RuntimeException("Could not configure from URL: " + url, e);
// }
// }
//
// public String getEmail() {
// verify(EMAIL);
// return getProperty(EMAIL);
// }
//
// public URL getEndpoint() {
// verify(ENDPOINT);
// URL url = null;
// try {
// url = new URL(getProperty(ENDPOINT));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return url;
// }
//
// public String getPassword() {
// verify(PASSWORD);
// return getProperty(PASSWORD);
// }
//
// public Properties getProperties() {
// Properties properties = new Properties();
// properties.putAll(this.properties);
// return properties;
// }
//
// public String getProperty(String name) {
// return properties.getProperty(name);
// }
//
// public String getPath() {
// return properties.getProperty(PATH);
// }
//
// public URL getUrl() {
// verify(PATH);
// URL url = null;
// try {
// url = new URL(getEndpoint(), getProperty(PATH));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return url;
// }
//
// /**
// * Override current properties with new <tt>properties</tt>.
// */
// public Configuration setProperties(Properties properties) {
// this.properties = properties;
// return this;
// }
//
// /**
// * Set a property.
// */
// public Configuration setProperty(String name, String value) {
// properties.setProperty(name, value);
// return this;
// }
//
// private void verify(String... properties) {
// for (String prop : properties) {
// if (!this.properties.containsKey(prop)) {
// throw new IllegalStateException("Properties file missing property '" + prop + "'");
// }
// }
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/Session.java
// public interface Session {
//
// void close();
//
// void close(Case bug);
//
// void create(Entity t);
//
// List<Case> query(String... criterion);
//
// <T extends Entity> T get(Class<T> clazz, Integer id);
//
// <T extends Entity> T get(Class<T> clazz, String name);
//
// <T extends Entity> List<T> findAll(Class<T> clazz);
//
// void edit(Case bug);
//
// void reactivate(Case bug);
//
// void reopen(Case bug);
//
// void resolve(Case bug);
//
// void scout(Case bug);
//
// }
| import org.junit.Test;
import com.fieldexpert.fbapi4j.Configuration;
import com.fieldexpert.fbapi4j.Session; | package com.fieldexpert.fbapi4j;
public class SessionTest {
@Test
public void neverConnects() {
Configuration config = new Configuration().configure(); | // Path: src/com/fieldexpert/fbapi4j/Configuration.java
// public final class Configuration {
//
// private static final String ENDPOINT = "endpoint";
// private static final String EMAIL = "email";
// private static final String PASSWORD = "password";
// private static final String PATH = "path";
//
// private Properties properties;
//
// public Configuration() {
// properties = new Properties();
// }
//
// public Configuration(Configuration configuration) {
// this.properties = configuration.getProperties();
// }
//
// public Session buildSession() {
// return new SessionFactory().createSession(this);
// }
//
// public Dispatch buildDispatch() {
// verify(ENDPOINT, EMAIL, PASSWORD);
// return new HttpDispatch(this);
// }
//
// /**
// * Merge <tt>properties</tt> into the current properties.
// */
// public Configuration addProperties(Properties properties) {
// this.properties.putAll(properties);
// return this;
// }
//
// private InputStream configurationStream(String path) {
// try {
// return this.getClass().getClassLoader().getResourceAsStream(path);
// } catch (Exception e) {
// throw new RuntimeException("Could not find file: " + path, e);
// }
// }
//
// /**
// * Use the properties specified in the resource <tt>fb4api.properties</tt>.
// */
// public Configuration configure() {
// return configure("fbapi4j.properties");
// }
//
// /**
// * Use <tt>file</tt> to build the properties.
// */
// public Configuration configure(File file) {
// try {
// return configure(new FileInputStream(file));
// } catch (IOException e) {
// throw new RuntimeException("Could not open file: " + file, e);
// }
// }
//
// private Configuration configure(InputStream stream) {
// try {
// this.properties.load(stream);
// } catch (IOException e) {
// throw new RuntimeException("Could not load properties from InputStream: " + e);
// }
// return this;
// }
//
// /**
// * Use the properties specified in <tt>resource</tt>.
// */
// public Configuration configure(String resource) {
// InputStream stream = configurationStream(resource);
// return configure(stream);
// }
//
// /**
// * Use the properties specified in <tt>url</tt>.
// */
// public Configuration configure(URL url) {
// try {
// return configure(url.openStream());
// } catch (IOException e) {
// throw new RuntimeException("Could not configure from URL: " + url, e);
// }
// }
//
// public String getEmail() {
// verify(EMAIL);
// return getProperty(EMAIL);
// }
//
// public URL getEndpoint() {
// verify(ENDPOINT);
// URL url = null;
// try {
// url = new URL(getProperty(ENDPOINT));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return url;
// }
//
// public String getPassword() {
// verify(PASSWORD);
// return getProperty(PASSWORD);
// }
//
// public Properties getProperties() {
// Properties properties = new Properties();
// properties.putAll(this.properties);
// return properties;
// }
//
// public String getProperty(String name) {
// return properties.getProperty(name);
// }
//
// public String getPath() {
// return properties.getProperty(PATH);
// }
//
// public URL getUrl() {
// verify(PATH);
// URL url = null;
// try {
// url = new URL(getEndpoint(), getProperty(PATH));
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// return url;
// }
//
// /**
// * Override current properties with new <tt>properties</tt>.
// */
// public Configuration setProperties(Properties properties) {
// this.properties = properties;
// return this;
// }
//
// /**
// * Set a property.
// */
// public Configuration setProperty(String name, String value) {
// properties.setProperty(name, value);
// return this;
// }
//
// private void verify(String... properties) {
// for (String prop : properties) {
// if (!this.properties.containsKey(prop)) {
// throw new IllegalStateException("Properties file missing property '" + prop + "'");
// }
// }
// }
// }
//
// Path: src/com/fieldexpert/fbapi4j/Session.java
// public interface Session {
//
// void close();
//
// void close(Case bug);
//
// void create(Entity t);
//
// List<Case> query(String... criterion);
//
// <T extends Entity> T get(Class<T> clazz, Integer id);
//
// <T extends Entity> T get(Class<T> clazz, String name);
//
// <T extends Entity> List<T> findAll(Class<T> clazz);
//
// void edit(Case bug);
//
// void reactivate(Case bug);
//
// void reopen(Case bug);
//
// void resolve(Case bug);
//
// void scout(Case bug);
//
// }
// Path: test/com/fieldexpert/fbapi4j/SessionTest.java
import org.junit.Test;
import com.fieldexpert.fbapi4j.Configuration;
import com.fieldexpert.fbapi4j.Session;
package com.fieldexpert.fbapi4j;
public class SessionTest {
@Test
public void neverConnects() {
Configuration config = new Configuration().configure(); | Session session = config.buildSession(); |
fieldexpert/fbapi4j | src/com/fieldexpert/fbapi4j/DefaultCaseBuilder.java | // Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
| import java.io.PrintWriter;
import java.io.StringWriter;
import com.fieldexpert.fbapi4j.common.Attachment; | package com.fieldexpert.fbapi4j;
public class DefaultCaseBuilder {
private String project;
private String area;
public DefaultCaseBuilder(String project, String area) {
this.project = project;
this.area = area;
}
public Case build(Throwable t, boolean attachStackTrace) {
StackTraceElement firstCause = getFirstCause(t).getStackTrace()[0];
String className = firstCause.getClassName();
String exceptionName = firstCause.getClass().getName();
String fileName = firstCause.getFileName();
int lineNumber = firstCause.getLineNumber();
String title = exceptionName + " " + className + ":" + fileName + ":" + lineNumber;
StringBuilder description = new StringBuilder();
description.append(exceptionName + " \n");
description.append(className + "\n");
description.append(fileName + ":" + lineNumber + "\n");
description.append("\n");
StringWriter stackTraceWriter = new StringWriter();
PrintWriter pw = new PrintWriter(stackTraceWriter);
t.printStackTrace(pw);
if (!attachStackTrace) {
description.append(stackTraceWriter.toString());
}
Case fbCase = new Case(getProject(), getArea(), title, description.toString());
if (attachStackTrace) { | // Path: src/com/fieldexpert/fbapi4j/common/Attachment.java
// public class Attachment {
//
// static {
// registerMimeDetector(ExtensionMimeDetector.class.getName());
// registerMimeDetector(MagicMimeMimeDetector.class.getName());
// }
//
// public static String getType(File file) {
// Collection<?> types = getMimeTypes(file);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(InputStream is) {
// Collection<?> types = getMimeTypes(is);
// return getMostSpecificMimeType(types).toString();
// }
//
// public static String getType(byte[] bytes) {
// Collection<?> types = getMimeTypes(bytes);
// return getMostSpecificMimeType(types).toString();
// }
//
// private String filename;
// private String type;
// private InputStream content;
//
// // not for you
// protected Attachment(String name) {
// this.filename = name;
// }
//
// public Attachment(String filename, String type, byte[] content) {
// this(filename, type, new ByteArrayInputStream(content));
// }
//
// public Attachment(String filename, String type, String content) {
// this(filename, type, content.getBytes(Charset.forName("UTF-8")));
// }
//
// public Attachment(String filename, String type, InputStream content) {
// this.filename = filename;
// this.type = type;
// this.content = content;
// }
//
// // can't chain this constructor call, because we need to try/catch
// public Attachment(File file) {
// Assert.notNull(file);
//
// this.filename = file.getName();
// this.type = getType(file);
// try {
// this.content = new FileInputStream(file);
// } catch (Exception e) {
// throw new RuntimeException("Error reading file: '" + file.getName() + "'");
// }
// }
//
// public InputStream getContent() {
// return content;
// }
//
// public String getFilename() {
// return filename;
// }
//
// public String getType() {
// return type;
// }
// }
// Path: src/com/fieldexpert/fbapi4j/DefaultCaseBuilder.java
import java.io.PrintWriter;
import java.io.StringWriter;
import com.fieldexpert.fbapi4j.common.Attachment;
package com.fieldexpert.fbapi4j;
public class DefaultCaseBuilder {
private String project;
private String area;
public DefaultCaseBuilder(String project, String area) {
this.project = project;
this.area = area;
}
public Case build(Throwable t, boolean attachStackTrace) {
StackTraceElement firstCause = getFirstCause(t).getStackTrace()[0];
String className = firstCause.getClassName();
String exceptionName = firstCause.getClass().getName();
String fileName = firstCause.getFileName();
int lineNumber = firstCause.getLineNumber();
String title = exceptionName + " " + className + ":" + fileName + ":" + lineNumber;
StringBuilder description = new StringBuilder();
description.append(exceptionName + " \n");
description.append(className + "\n");
description.append(fileName + ":" + lineNumber + "\n");
description.append("\n");
StringWriter stackTraceWriter = new StringWriter();
PrintWriter pw = new PrintWriter(stackTraceWriter);
t.printStackTrace(pw);
if (!attachStackTrace) {
description.append(stackTraceWriter.toString());
}
Case fbCase = new Case(getProject(), getArea(), title, description.toString());
if (attachStackTrace) { | Attachment attachment = new Attachment(exceptionName + ".txt", "text/plain", stackTraceWriter.toString()); |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/ext/SharedServerSocket.java | // Path: src/main/java/org/projectnyx/network/ext/udp/SharedUdpServerSocket.java
// public class SharedUdpServerSocket extends SharedServerSocket {
// public final static String TYPE = "UDP";
// @Getter private final UdpBufferThread thread;
//
// private Task task;
// private Map<InetSocketAddress, UdpSessionHandler> sessions = new HashMap<>();
// private List<UdpSessionHandler> sessionsToClose = new LinkedList<>();
//
// public SharedUdpServerSocket(InetSocketAddress address) {
// super(TYPE, address.getAddress(), address.getPort());
// thread = new UdpBufferThread(this, address);
// thread.start();
// Nyx.getLog().info(String.format("Started UDP server socket listening on %s", address.toString()));
// }
//
// @Override
// public void tick() {
// super.tick();
//
// PacketWithAddress pk;
// while((pk = thread.shiftReceive()) != null) {
// UdpSessionHandler session = getSessionOrCreate(pk.getAddress());
// Nyx.getLog().debug(String.format("Received packet from %s", pk.getAddress()));
// session.onReceive(pk);
// Nyx.getLog().debug(String.format("Handled packet from %s", pk.getAddress()));
// }
//
// sessions.values().forEach(UdpSessionHandler::tick);
// for(UdpSessionHandler handler : sessionsToClose) {
// sessions.values().remove(handler);
// }
// sessionsToClose.clear();
// }
//
// public UdpSessionHandler getSession(InetSocketAddress address) {
// return sessions.get(address);
// }
//
// public UdpSessionHandler getSessionOrCreate(InetSocketAddress address) {
// if(!sessions.containsKey(address)) {
// sessions.put(address, new UdpSessionHandler(address, this));
// }
// return sessions.get(address);
// }
//
// void addSession(UdpSessionHandler session) {
// sessions.put(session.getAddress(), session);
// }
//
// public void onSessionClosed(UdpSessionHandler handler) {
// if(handler.getSocket() != this) {
// throw new IllegalArgumentException();
// }
// sessionsToClose.add(handler);
// }
//
// public Collection<UdpSessionHandler> getSessions() {
// return sessions.values();
// }
//
// @Override
// public void close() {
// super.close();
// }
// }
| import java.net.InetAddress;
import java.net.InetSocketAddress;
import lombok.Getter;
import lombok.Value;
import org.projectnyx.network.ext.udp.SharedUdpServerSocket; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.ext;
public abstract class SharedServerSocket {
@Getter private final Identifier identifier;
public SharedServerSocket(String type, InetAddress address, int port) {
this(new Identifier(type, address, port));
}
public SharedServerSocket(Identifier identifier) {
this.identifier = identifier;
SharedSocketPool.getInstance().addSocket(this);
}
public void close() {
SharedSocketPool.getInstance().removeSocket(this);
}
public void tick() {
}
@Value
public static class Identifier {
String type;
InetAddress address;
int port;
public SharedServerSocket create() {
switch(type) { | // Path: src/main/java/org/projectnyx/network/ext/udp/SharedUdpServerSocket.java
// public class SharedUdpServerSocket extends SharedServerSocket {
// public final static String TYPE = "UDP";
// @Getter private final UdpBufferThread thread;
//
// private Task task;
// private Map<InetSocketAddress, UdpSessionHandler> sessions = new HashMap<>();
// private List<UdpSessionHandler> sessionsToClose = new LinkedList<>();
//
// public SharedUdpServerSocket(InetSocketAddress address) {
// super(TYPE, address.getAddress(), address.getPort());
// thread = new UdpBufferThread(this, address);
// thread.start();
// Nyx.getLog().info(String.format("Started UDP server socket listening on %s", address.toString()));
// }
//
// @Override
// public void tick() {
// super.tick();
//
// PacketWithAddress pk;
// while((pk = thread.shiftReceive()) != null) {
// UdpSessionHandler session = getSessionOrCreate(pk.getAddress());
// Nyx.getLog().debug(String.format("Received packet from %s", pk.getAddress()));
// session.onReceive(pk);
// Nyx.getLog().debug(String.format("Handled packet from %s", pk.getAddress()));
// }
//
// sessions.values().forEach(UdpSessionHandler::tick);
// for(UdpSessionHandler handler : sessionsToClose) {
// sessions.values().remove(handler);
// }
// sessionsToClose.clear();
// }
//
// public UdpSessionHandler getSession(InetSocketAddress address) {
// return sessions.get(address);
// }
//
// public UdpSessionHandler getSessionOrCreate(InetSocketAddress address) {
// if(!sessions.containsKey(address)) {
// sessions.put(address, new UdpSessionHandler(address, this));
// }
// return sessions.get(address);
// }
//
// void addSession(UdpSessionHandler session) {
// sessions.put(session.getAddress(), session);
// }
//
// public void onSessionClosed(UdpSessionHandler handler) {
// if(handler.getSocket() != this) {
// throw new IllegalArgumentException();
// }
// sessionsToClose.add(handler);
// }
//
// public Collection<UdpSessionHandler> getSessions() {
// return sessions.values();
// }
//
// @Override
// public void close() {
// super.close();
// }
// }
// Path: src/main/java/org/projectnyx/network/ext/SharedServerSocket.java
import java.net.InetAddress;
import java.net.InetSocketAddress;
import lombok.Getter;
import lombok.Value;
import org.projectnyx.network.ext.udp.SharedUdpServerSocket;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.ext;
public abstract class SharedServerSocket {
@Getter private final Identifier identifier;
public SharedServerSocket(String type, InetAddress address, int port) {
this(new Identifier(type, address, port));
}
public SharedServerSocket(Identifier identifier) {
this.identifier = identifier;
SharedSocketPool.getInstance().addSocket(this);
}
public void close() {
SharedSocketPool.getInstance().removeSocket(this);
}
public void tick() {
}
@Value
public static class Identifier {
String type;
InetAddress address;
int port;
public SharedServerSocket create() {
switch(type) { | case SharedUdpServerSocket.TYPE: |
Project-Nyx/Nyx | src/main/java/org/projectnyx/config/ConfigParser.java | // Path: src/main/java/org/projectnyx/properties/NyxConfig.java
// public class NyxConfig extends ConfigElement {
// /**
// * The servers to launch
// */
// public Servers servers;
// }
| import java.io.*;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.projectnyx.properties.NyxConfig;
import static org.xmlpull.v1.XmlPullParser.*; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.config;
/**
* The class for parsing a Nyx-style XML config file.
*/
public class ConfigParser {
private final Reader input;
private final XmlPullParser parser; | // Path: src/main/java/org/projectnyx/properties/NyxConfig.java
// public class NyxConfig extends ConfigElement {
// /**
// * The servers to launch
// */
// public Servers servers;
// }
// Path: src/main/java/org/projectnyx/config/ConfigParser.java
import java.io.*;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.projectnyx.properties.NyxConfig;
import static org.xmlpull.v1.XmlPullParser.*;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.config;
/**
* The class for parsing a Nyx-style XML config file.
*/
public class ConfigParser {
private final Reader input;
private final XmlPullParser parser; | @Getter @Setter private String packageContext = NyxConfig.class.getPackage().getName(); |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/mcpe/raknet/RawDataPacket.java | // Path: src/main/java/org/projectnyx/network/mcpe/ReceivedPacket.java
// public abstract class ReceivedPacket extends ByteBufferReader implements Cloneable {
// public void parse(ByteBuffer buffer) {
// this.buffer = buffer;
// buffer.order(ByteOrder.BIG_ENDIAN);
//
// decode();
// }
//
// public abstract byte getId();
//
// protected abstract void decode();
//
// @SneakyThrows(CloneNotSupportedException.class)
// public ReceivedPacket getClone() {
// return (ReceivedPacket) clone();
// }
// }
| import java.nio.ByteBuffer;
import org.projectnyx.network.mcpe.ReceivedPacket; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.mcpe.raknet;
public class RawDataPacket {
public final static byte RELIABILITY_UNRELIABLE = (byte) 0x00;
public final static byte RELIABILITY_UNRELIABLE_SEQUENCED = (byte) 0x01;
public final static byte RELIABILITY_RELIABLE = (byte) 0x02;
public final static byte RELIABILITY_RELIABLE_ORDERED = (byte) 0x03;
public final static byte RELIABILITY_RELIABLE_SEQUENCED = (byte) 0x04;
public final static byte RELIABILITY_UNRELIABLE_WITH_ACK_RECEIPT = (byte) 0x05;
public final static byte RELIABILITY_UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT = (byte) 0x06;
public final static byte RELIABILITY_RELIABLE_WITH_ACK_RECEIPT = (byte) 0x07;
public final static byte RELIABILITY_RELIABLE_ORDERED_WITH_ACK_RECEIPT = (byte) 0x08;
public final static byte RELIABILITY_RELIABLE_SEQUENCED_WITH_ACK_RECEIPT = (byte) 0x09;
public byte[] buffer;
public byte reliability;
public boolean hasSplit;
public int orderIndex;
public int messageIndex;
public byte orderChannel;
public int splitCount;
public short splitId;
public int splitIndex;
| // Path: src/main/java/org/projectnyx/network/mcpe/ReceivedPacket.java
// public abstract class ReceivedPacket extends ByteBufferReader implements Cloneable {
// public void parse(ByteBuffer buffer) {
// this.buffer = buffer;
// buffer.order(ByteOrder.BIG_ENDIAN);
//
// decode();
// }
//
// public abstract byte getId();
//
// protected abstract void decode();
//
// @SneakyThrows(CloneNotSupportedException.class)
// public ReceivedPacket getClone() {
// return (ReceivedPacket) clone();
// }
// }
// Path: src/main/java/org/projectnyx/network/mcpe/raknet/RawDataPacket.java
import java.nio.ByteBuffer;
import org.projectnyx.network.mcpe.ReceivedPacket;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.mcpe.raknet;
public class RawDataPacket {
public final static byte RELIABILITY_UNRELIABLE = (byte) 0x00;
public final static byte RELIABILITY_UNRELIABLE_SEQUENCED = (byte) 0x01;
public final static byte RELIABILITY_RELIABLE = (byte) 0x02;
public final static byte RELIABILITY_RELIABLE_ORDERED = (byte) 0x03;
public final static byte RELIABILITY_RELIABLE_SEQUENCED = (byte) 0x04;
public final static byte RELIABILITY_UNRELIABLE_WITH_ACK_RECEIPT = (byte) 0x05;
public final static byte RELIABILITY_UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT = (byte) 0x06;
public final static byte RELIABILITY_RELIABLE_WITH_ACK_RECEIPT = (byte) 0x07;
public final static byte RELIABILITY_RELIABLE_ORDERED_WITH_ACK_RECEIPT = (byte) 0x08;
public final static byte RELIABILITY_RELIABLE_SEQUENCED_WITH_ACK_RECEIPT = (byte) 0x09;
public byte[] buffer;
public byte reliability;
public boolean hasSplit;
public int orderIndex;
public int messageIndex;
public byte orderChannel;
public int splitCount;
public short splitId;
public int splitIndex;
| public static RawDataPacket read(ReceivedPacket packet) { |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/Protocol.java | // Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
// @RequiredArgsConstructor
// public abstract class SessionHandler {
// @Getter private final InetSocketAddress address;
// @Getter private final SharedServerSocket socket;
//
// public abstract void onReceive(PacketWithAddress pk);
//
// public abstract void send(ByteBuffer buffer);
//
// public abstract void close();
//
// public abstract Protocol getProtocol();
//
// public void tick() {
//
// }
//
// /**
// * <p>Returns whether this session an orphan.</p>
// *
// * <p>An orphan session is a session that has not been recognized by any sessions yet.</p>
// *
// * @return whether this session is an orphan.
// */
// public abstract boolean isOrphan();
// }
| import org.projectnyx.network.ext.SessionHandler; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network;
public abstract class Protocol {
protected Protocol() {
init();
}
public abstract void init();
| // Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
// @RequiredArgsConstructor
// public abstract class SessionHandler {
// @Getter private final InetSocketAddress address;
// @Getter private final SharedServerSocket socket;
//
// public abstract void onReceive(PacketWithAddress pk);
//
// public abstract void send(ByteBuffer buffer);
//
// public abstract void close();
//
// public abstract Protocol getProtocol();
//
// public void tick() {
//
// }
//
// /**
// * <p>Returns whether this session an orphan.</p>
// *
// * <p>An orphan session is a session that has not been recognized by any sessions yet.</p>
// *
// * @return whether this session is an orphan.
// */
// public abstract boolean isOrphan();
// }
// Path: src/main/java/org/projectnyx/network/Protocol.java
import org.projectnyx.network.ext.SessionHandler;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network;
public abstract class Protocol {
protected Protocol() {
init();
}
public abstract void init();
| public abstract Client acceptSession(SessionHandler session); |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/xml/Packet.java | // Path: src/main/java/org/projectnyx/token/request/Request.java
// public class Request {
// }
//
// Path: src/main/java/org/projectnyx/token/response/Response.java
// public class Response {
// }
| import java.util.List;
import org.projectnyx.config.DefaultPackage;
import org.projectnyx.token.request.Request;
import org.projectnyx.token.response.Response; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.xml;
public class Packet {
public byte id; | // Path: src/main/java/org/projectnyx/token/request/Request.java
// public class Request {
// }
//
// Path: src/main/java/org/projectnyx/token/response/Response.java
// public class Response {
// }
// Path: src/main/java/org/projectnyx/network/xml/Packet.java
import java.util.List;
import org.projectnyx.config.DefaultPackage;
import org.projectnyx.token.request.Request;
import org.projectnyx.token.response.Response;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.xml;
public class Packet {
public byte id; | @DefaultPackage("org.projectnyx.token.request") public List<Class<? extends Request>> tokenRequests; |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/xml/Packet.java | // Path: src/main/java/org/projectnyx/token/request/Request.java
// public class Request {
// }
//
// Path: src/main/java/org/projectnyx/token/response/Response.java
// public class Response {
// }
| import java.util.List;
import org.projectnyx.config.DefaultPackage;
import org.projectnyx.token.request.Request;
import org.projectnyx.token.response.Response; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.xml;
public class Packet {
public byte id;
@DefaultPackage("org.projectnyx.token.request") public List<Class<? extends Request>> tokenRequests; | // Path: src/main/java/org/projectnyx/token/request/Request.java
// public class Request {
// }
//
// Path: src/main/java/org/projectnyx/token/response/Response.java
// public class Response {
// }
// Path: src/main/java/org/projectnyx/network/xml/Packet.java
import java.util.List;
import org.projectnyx.config.DefaultPackage;
import org.projectnyx.token.request.Request;
import org.projectnyx.token.response.Response;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.xml;
public class Packet {
public byte id;
@DefaultPackage("org.projectnyx.token.request") public List<Class<? extends Request>> tokenRequests; | @DefaultPackage("org.projectnyx.token.response") public List<Class<? extends Response>> tokenResponses; |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/Client.java | // Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
// @RequiredArgsConstructor
// public abstract class SessionHandler {
// @Getter private final InetSocketAddress address;
// @Getter private final SharedServerSocket socket;
//
// public abstract void onReceive(PacketWithAddress pk);
//
// public abstract void send(ByteBuffer buffer);
//
// public abstract void close();
//
// public abstract Protocol getProtocol();
//
// public void tick() {
//
// }
//
// /**
// * <p>Returns whether this session an orphan.</p>
// *
// * <p>An orphan session is a session that has not been recognized by any sessions yet.</p>
// *
// * @return whether this session is an orphan.
// */
// public abstract boolean isOrphan();
// }
//
// Path: src/main/java/org/projectnyx/network/mcpe/PingStats.java
// public class PingStats {
// @Getter private List<Datum> data = new LinkedList<>();
//
// public void addDatum(long sendTime, boolean success) {
// Datum datum = success ? new Datum(sendTime, (System.nanoTime() - sendTime) * 1e-9d) : new Datum(sendTime);
// while(data.size() > 20) {
// data.remove(0);
// }
// data.add(datum);
// }
//
// public double getAverageSuccessfulPing() {
// int count = 0;
// double total = 0d;
// for(Datum datum : data) {
// if(datum.isSuccessful()) {
// count++;
// total += datum.getLatencySecs();
// }
// }
// return total / count;
// }
//
// public double getPacketLossRatio() {
// return data.stream().filter(datum -> !datum.isSuccessful()).count() / (double) data.size();
// }
//
// @RequiredArgsConstructor
// @AllArgsConstructor
// @Getter
// public static class Datum {
// private final long sendTime;
// private double latencySecs = POSITIVE_INFINITY;
//
// public boolean isSuccessful() {
// return latencySecs != POSITIVE_INFINITY;
// }
// }
// }
//
// Path: src/main/java/org/projectnyx/player/Player.java
// public class Player {
// private List<Client> connectedClients;
//
// /**
// * Attach a client to this player
// *
// * @param client the client to attach
// */
// public void attachClient(Client client) {
// connectedClients.add(client); // TODO checks
// }
//
// /**
// * Detach a client from this player, i.e. a client disconnect
// *
// * @param client the client to detach
// */
// public void detachClient(Client client) {
// connectedClients.remove(client); // TODO checks
// }
// }
| import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import lombok.Getter;
import org.projectnyx.network.ext.SessionHandler;
import org.projectnyx.network.mcpe.PingStats;
import org.projectnyx.player.Player; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network;
/**
* An object
*/
public abstract class Client {
@Getter private Player assignedPlayer; | // Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
// @RequiredArgsConstructor
// public abstract class SessionHandler {
// @Getter private final InetSocketAddress address;
// @Getter private final SharedServerSocket socket;
//
// public abstract void onReceive(PacketWithAddress pk);
//
// public abstract void send(ByteBuffer buffer);
//
// public abstract void close();
//
// public abstract Protocol getProtocol();
//
// public void tick() {
//
// }
//
// /**
// * <p>Returns whether this session an orphan.</p>
// *
// * <p>An orphan session is a session that has not been recognized by any sessions yet.</p>
// *
// * @return whether this session is an orphan.
// */
// public abstract boolean isOrphan();
// }
//
// Path: src/main/java/org/projectnyx/network/mcpe/PingStats.java
// public class PingStats {
// @Getter private List<Datum> data = new LinkedList<>();
//
// public void addDatum(long sendTime, boolean success) {
// Datum datum = success ? new Datum(sendTime, (System.nanoTime() - sendTime) * 1e-9d) : new Datum(sendTime);
// while(data.size() > 20) {
// data.remove(0);
// }
// data.add(datum);
// }
//
// public double getAverageSuccessfulPing() {
// int count = 0;
// double total = 0d;
// for(Datum datum : data) {
// if(datum.isSuccessful()) {
// count++;
// total += datum.getLatencySecs();
// }
// }
// return total / count;
// }
//
// public double getPacketLossRatio() {
// return data.stream().filter(datum -> !datum.isSuccessful()).count() / (double) data.size();
// }
//
// @RequiredArgsConstructor
// @AllArgsConstructor
// @Getter
// public static class Datum {
// private final long sendTime;
// private double latencySecs = POSITIVE_INFINITY;
//
// public boolean isSuccessful() {
// return latencySecs != POSITIVE_INFINITY;
// }
// }
// }
//
// Path: src/main/java/org/projectnyx/player/Player.java
// public class Player {
// private List<Client> connectedClients;
//
// /**
// * Attach a client to this player
// *
// * @param client the client to attach
// */
// public void attachClient(Client client) {
// connectedClients.add(client); // TODO checks
// }
//
// /**
// * Detach a client from this player, i.e. a client disconnect
// *
// * @param client the client to detach
// */
// public void detachClient(Client client) {
// connectedClients.remove(client); // TODO checks
// }
// }
// Path: src/main/java/org/projectnyx/network/Client.java
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import lombok.Getter;
import org.projectnyx.network.ext.SessionHandler;
import org.projectnyx.network.mcpe.PingStats;
import org.projectnyx.player.Player;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network;
/**
* An object
*/
public abstract class Client {
@Getter private Player assignedPlayer; | @Getter private PingStats pingStats; |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/Client.java | // Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
// @RequiredArgsConstructor
// public abstract class SessionHandler {
// @Getter private final InetSocketAddress address;
// @Getter private final SharedServerSocket socket;
//
// public abstract void onReceive(PacketWithAddress pk);
//
// public abstract void send(ByteBuffer buffer);
//
// public abstract void close();
//
// public abstract Protocol getProtocol();
//
// public void tick() {
//
// }
//
// /**
// * <p>Returns whether this session an orphan.</p>
// *
// * <p>An orphan session is a session that has not been recognized by any sessions yet.</p>
// *
// * @return whether this session is an orphan.
// */
// public abstract boolean isOrphan();
// }
//
// Path: src/main/java/org/projectnyx/network/mcpe/PingStats.java
// public class PingStats {
// @Getter private List<Datum> data = new LinkedList<>();
//
// public void addDatum(long sendTime, boolean success) {
// Datum datum = success ? new Datum(sendTime, (System.nanoTime() - sendTime) * 1e-9d) : new Datum(sendTime);
// while(data.size() > 20) {
// data.remove(0);
// }
// data.add(datum);
// }
//
// public double getAverageSuccessfulPing() {
// int count = 0;
// double total = 0d;
// for(Datum datum : data) {
// if(datum.isSuccessful()) {
// count++;
// total += datum.getLatencySecs();
// }
// }
// return total / count;
// }
//
// public double getPacketLossRatio() {
// return data.stream().filter(datum -> !datum.isSuccessful()).count() / (double) data.size();
// }
//
// @RequiredArgsConstructor
// @AllArgsConstructor
// @Getter
// public static class Datum {
// private final long sendTime;
// private double latencySecs = POSITIVE_INFINITY;
//
// public boolean isSuccessful() {
// return latencySecs != POSITIVE_INFINITY;
// }
// }
// }
//
// Path: src/main/java/org/projectnyx/player/Player.java
// public class Player {
// private List<Client> connectedClients;
//
// /**
// * Attach a client to this player
// *
// * @param client the client to attach
// */
// public void attachClient(Client client) {
// connectedClients.add(client); // TODO checks
// }
//
// /**
// * Detach a client from this player, i.e. a client disconnect
// *
// * @param client the client to detach
// */
// public void detachClient(Client client) {
// connectedClients.remove(client); // TODO checks
// }
// }
| import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import lombok.Getter;
import org.projectnyx.network.ext.SessionHandler;
import org.projectnyx.network.mcpe.PingStats;
import org.projectnyx.player.Player; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network;
/**
* An object
*/
public abstract class Client {
@Getter private Player assignedPlayer;
@Getter private PingStats pingStats;
@Getter private long lastAlive;
protected Client() {
refreshActive();
}
public abstract Protocol getSourceProtocol();
| // Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
// @RequiredArgsConstructor
// public abstract class SessionHandler {
// @Getter private final InetSocketAddress address;
// @Getter private final SharedServerSocket socket;
//
// public abstract void onReceive(PacketWithAddress pk);
//
// public abstract void send(ByteBuffer buffer);
//
// public abstract void close();
//
// public abstract Protocol getProtocol();
//
// public void tick() {
//
// }
//
// /**
// * <p>Returns whether this session an orphan.</p>
// *
// * <p>An orphan session is a session that has not been recognized by any sessions yet.</p>
// *
// * @return whether this session is an orphan.
// */
// public abstract boolean isOrphan();
// }
//
// Path: src/main/java/org/projectnyx/network/mcpe/PingStats.java
// public class PingStats {
// @Getter private List<Datum> data = new LinkedList<>();
//
// public void addDatum(long sendTime, boolean success) {
// Datum datum = success ? new Datum(sendTime, (System.nanoTime() - sendTime) * 1e-9d) : new Datum(sendTime);
// while(data.size() > 20) {
// data.remove(0);
// }
// data.add(datum);
// }
//
// public double getAverageSuccessfulPing() {
// int count = 0;
// double total = 0d;
// for(Datum datum : data) {
// if(datum.isSuccessful()) {
// count++;
// total += datum.getLatencySecs();
// }
// }
// return total / count;
// }
//
// public double getPacketLossRatio() {
// return data.stream().filter(datum -> !datum.isSuccessful()).count() / (double) data.size();
// }
//
// @RequiredArgsConstructor
// @AllArgsConstructor
// @Getter
// public static class Datum {
// private final long sendTime;
// private double latencySecs = POSITIVE_INFINITY;
//
// public boolean isSuccessful() {
// return latencySecs != POSITIVE_INFINITY;
// }
// }
// }
//
// Path: src/main/java/org/projectnyx/player/Player.java
// public class Player {
// private List<Client> connectedClients;
//
// /**
// * Attach a client to this player
// *
// * @param client the client to attach
// */
// public void attachClient(Client client) {
// connectedClients.add(client); // TODO checks
// }
//
// /**
// * Detach a client from this player, i.e. a client disconnect
// *
// * @param client the client to detach
// */
// public void detachClient(Client client) {
// connectedClients.remove(client); // TODO checks
// }
// }
// Path: src/main/java/org/projectnyx/network/Client.java
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import lombok.Getter;
import org.projectnyx.network.ext.SessionHandler;
import org.projectnyx.network.mcpe.PingStats;
import org.projectnyx.player.Player;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network;
/**
* An object
*/
public abstract class Client {
@Getter private Player assignedPlayer;
@Getter private PingStats pingStats;
@Getter private long lastAlive;
protected Client() {
refreshActive();
}
public abstract Protocol getSourceProtocol();
| public abstract SessionHandler getSessionHandler(); |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/mcpe/raknet/raknet/ReceivedDataPacketGroup.java | // Path: src/main/java/org/projectnyx/network/mcpe/ReceivedPacket.java
// public abstract class ReceivedPacket extends ByteBufferReader implements Cloneable {
// public void parse(ByteBuffer buffer) {
// this.buffer = buffer;
// buffer.order(ByteOrder.BIG_ENDIAN);
//
// decode();
// }
//
// public abstract byte getId();
//
// protected abstract void decode();
//
// @SneakyThrows(CloneNotSupportedException.class)
// public ReceivedPacket getClone() {
// return (ReceivedPacket) clone();
// }
// }
//
// Path: src/main/java/org/projectnyx/network/mcpe/raknet/RawDataPacket.java
// public class RawDataPacket {
// public final static byte RELIABILITY_UNRELIABLE = (byte) 0x00;
// public final static byte RELIABILITY_UNRELIABLE_SEQUENCED = (byte) 0x01;
// public final static byte RELIABILITY_RELIABLE = (byte) 0x02;
// public final static byte RELIABILITY_RELIABLE_ORDERED = (byte) 0x03;
// public final static byte RELIABILITY_RELIABLE_SEQUENCED = (byte) 0x04;
// public final static byte RELIABILITY_UNRELIABLE_WITH_ACK_RECEIPT = (byte) 0x05;
// public final static byte RELIABILITY_UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT = (byte) 0x06;
// public final static byte RELIABILITY_RELIABLE_WITH_ACK_RECEIPT = (byte) 0x07;
// public final static byte RELIABILITY_RELIABLE_ORDERED_WITH_ACK_RECEIPT = (byte) 0x08;
// public final static byte RELIABILITY_RELIABLE_SEQUENCED_WITH_ACK_RECEIPT = (byte) 0x09;
//
// public byte[] buffer;
// public byte reliability;
// public boolean hasSplit;
// public int orderIndex;
// public int messageIndex;
// public byte orderChannel;
// public int splitCount;
// public short splitId;
// public int splitIndex;
//
// public static RawDataPacket read(ReceivedPacket packet) {
// RawDataPacket instance = new RawDataPacket();
// byte flags = packet.getByte();
// instance.reliability = (byte) ((flags & 0b11100000) >>> 5);
// instance.hasSplit = (flags & 0b00010000) > 0;
// instance.buffer = new byte[(int) Math.ceil(packet.getShort() / 8d)];
//
// switch(instance.reliability) {
// case 1:
// instance.orderIndex = packet.getLTriad();
// instance.orderChannel = packet.getByte();
// break;
// case 2:
// instance.messageIndex = packet.getLTriad();
// break;
// case 3:
// case 4:
// instance.messageIndex = packet.getLTriad();
// instance.orderIndex = packet.getLTriad();
// instance.orderChannel = packet.getByte();
// break;
// case 6:
// case 7:
// instance.messageIndex = packet.getLTriad();
// break;
// }
//
// if(instance.hasSplit) {
// instance.splitCount = packet.getInt();
// instance.splitId = packet.getShort();
// instance.splitIndex = packet.getInt();
// }
//
// packet.getBuffer().get(instance.buffer);
//
// return instance;
// }
//
// public byte[] write() {
// ByteBuffer bb = ByteBuffer.allocate(binaryLength());
// bb.put((byte) ((reliability << 5) | (hasSplit ? 0b00010000 : 0))).putShort((short) (buffer.length << 3));
// switch(reliability) {
// case 1:
// putLTriad(bb, orderIndex);
// bb.put(orderChannel);
// break;
// case 2:
// putLTriad(bb, messageIndex);
// break;
// case 3:
// case 4:
// putLTriad(bb, messageIndex);
// putLTriad(bb, orderIndex);
// bb.put(orderChannel);
// break;
// case 6:
// case 7:
// putLTriad(bb, messageIndex);
// break;
// }
// if(hasSplit) {
// bb.putInt(splitCount).putShort(splitId).putInt(splitIndex);
// }
// bb.put(buffer);
//
// return bb.array();
// }
//
// public int binaryLength() {
// int relLen = 0;
// switch(reliability) {
// case 1:
// case 2:
// case 6:
// case 7:
// relLen = 3;
// break;
// case 3:
// case 4:
// relLen = 6;
// break;
// }
// return 3 + buffer.length + (hasSplit ? 10 : 0) + relLen;
// }
//
// public static ByteBuffer putLTriad(ByteBuffer buffer, int triad) {
// buffer.put((byte) (triad & 0xFF));
// buffer.put((byte) ((triad >> 8) & 0xFF));
// buffer.put((byte) ((triad >> 16) & 0xFF));
// return buffer;
// }
// }
| import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.projectnyx.network.mcpe.ReceivedPacket;
import org.projectnyx.network.mcpe.raknet.RawDataPacket; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.mcpe.raknet.raknet;
@RequiredArgsConstructor
public class ReceivedDataPacketGroup extends ReceivedPacket {
private final byte id;
public int seqNumber; | // Path: src/main/java/org/projectnyx/network/mcpe/ReceivedPacket.java
// public abstract class ReceivedPacket extends ByteBufferReader implements Cloneable {
// public void parse(ByteBuffer buffer) {
// this.buffer = buffer;
// buffer.order(ByteOrder.BIG_ENDIAN);
//
// decode();
// }
//
// public abstract byte getId();
//
// protected abstract void decode();
//
// @SneakyThrows(CloneNotSupportedException.class)
// public ReceivedPacket getClone() {
// return (ReceivedPacket) clone();
// }
// }
//
// Path: src/main/java/org/projectnyx/network/mcpe/raknet/RawDataPacket.java
// public class RawDataPacket {
// public final static byte RELIABILITY_UNRELIABLE = (byte) 0x00;
// public final static byte RELIABILITY_UNRELIABLE_SEQUENCED = (byte) 0x01;
// public final static byte RELIABILITY_RELIABLE = (byte) 0x02;
// public final static byte RELIABILITY_RELIABLE_ORDERED = (byte) 0x03;
// public final static byte RELIABILITY_RELIABLE_SEQUENCED = (byte) 0x04;
// public final static byte RELIABILITY_UNRELIABLE_WITH_ACK_RECEIPT = (byte) 0x05;
// public final static byte RELIABILITY_UNRELIABLE_SEQUENCED_WITH_ACK_RECEIPT = (byte) 0x06;
// public final static byte RELIABILITY_RELIABLE_WITH_ACK_RECEIPT = (byte) 0x07;
// public final static byte RELIABILITY_RELIABLE_ORDERED_WITH_ACK_RECEIPT = (byte) 0x08;
// public final static byte RELIABILITY_RELIABLE_SEQUENCED_WITH_ACK_RECEIPT = (byte) 0x09;
//
// public byte[] buffer;
// public byte reliability;
// public boolean hasSplit;
// public int orderIndex;
// public int messageIndex;
// public byte orderChannel;
// public int splitCount;
// public short splitId;
// public int splitIndex;
//
// public static RawDataPacket read(ReceivedPacket packet) {
// RawDataPacket instance = new RawDataPacket();
// byte flags = packet.getByte();
// instance.reliability = (byte) ((flags & 0b11100000) >>> 5);
// instance.hasSplit = (flags & 0b00010000) > 0;
// instance.buffer = new byte[(int) Math.ceil(packet.getShort() / 8d)];
//
// switch(instance.reliability) {
// case 1:
// instance.orderIndex = packet.getLTriad();
// instance.orderChannel = packet.getByte();
// break;
// case 2:
// instance.messageIndex = packet.getLTriad();
// break;
// case 3:
// case 4:
// instance.messageIndex = packet.getLTriad();
// instance.orderIndex = packet.getLTriad();
// instance.orderChannel = packet.getByte();
// break;
// case 6:
// case 7:
// instance.messageIndex = packet.getLTriad();
// break;
// }
//
// if(instance.hasSplit) {
// instance.splitCount = packet.getInt();
// instance.splitId = packet.getShort();
// instance.splitIndex = packet.getInt();
// }
//
// packet.getBuffer().get(instance.buffer);
//
// return instance;
// }
//
// public byte[] write() {
// ByteBuffer bb = ByteBuffer.allocate(binaryLength());
// bb.put((byte) ((reliability << 5) | (hasSplit ? 0b00010000 : 0))).putShort((short) (buffer.length << 3));
// switch(reliability) {
// case 1:
// putLTriad(bb, orderIndex);
// bb.put(orderChannel);
// break;
// case 2:
// putLTriad(bb, messageIndex);
// break;
// case 3:
// case 4:
// putLTriad(bb, messageIndex);
// putLTriad(bb, orderIndex);
// bb.put(orderChannel);
// break;
// case 6:
// case 7:
// putLTriad(bb, messageIndex);
// break;
// }
// if(hasSplit) {
// bb.putInt(splitCount).putShort(splitId).putInt(splitIndex);
// }
// bb.put(buffer);
//
// return bb.array();
// }
//
// public int binaryLength() {
// int relLen = 0;
// switch(reliability) {
// case 1:
// case 2:
// case 6:
// case 7:
// relLen = 3;
// break;
// case 3:
// case 4:
// relLen = 6;
// break;
// }
// return 3 + buffer.length + (hasSplit ? 10 : 0) + relLen;
// }
//
// public static ByteBuffer putLTriad(ByteBuffer buffer, int triad) {
// buffer.put((byte) (triad & 0xFF));
// buffer.put((byte) ((triad >> 8) & 0xFF));
// buffer.put((byte) ((triad >> 16) & 0xFF));
// return buffer;
// }
// }
// Path: src/main/java/org/projectnyx/network/mcpe/raknet/raknet/ReceivedDataPacketGroup.java
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.projectnyx.network.mcpe.ReceivedPacket;
import org.projectnyx.network.mcpe.raknet.RawDataPacket;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.mcpe.raknet.raknet;
@RequiredArgsConstructor
public class ReceivedDataPacketGroup extends ReceivedPacket {
private final byte id;
public int seqNumber; | public List<RawDataPacket> packets = new ArrayList<>(); |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/ext/udp/UdpBufferThread.java | // Path: src/main/java/org/projectnyx/network/ext/PacketWithAddress.java
// public class PacketWithAddress {
// @Getter private final ByteBuffer buffer;
// @Getter private final InetSocketAddress address;
//
// /**
// * The buffer will be automatically flipped if the position is not at 0
// *
// * @param buffer the buffer of data to send, from 0 to limit if position is 0, or from 0 to position if position is
// * not 0
// * @param address the target address of the client. can be null in some network implementations.
// */
// public PacketWithAddress(ByteBuffer buffer, InetSocketAddress address) {
// this(buffer, address, buffer.position() != 0);
// }
//
// public PacketWithAddress(ByteBuffer buffer, InetSocketAddress address, boolean flip) {
// if(flip) {
// if(buffer.position() == 0) {
// Nyx.getLog().warn("Attempt to flip buffer with zero length", new Throwable("Backtrace"));
// }
// if(buffer.array().length >= (buffer.position() << 3)) { // save some memory
// buffer = ByteBuffer.wrap(ArrayUtils.subarray(buffer.array(), 0, buffer.position()));
// } else {
// buffer.flip();
// }
// }
// this.buffer = buffer;
// this.address = address;
// }
//
// @Override
// public String toString() {
// return "Data from address " + address.toString() + ": " + Hex.encodeHexString(buffer.array());
// }
// }
| import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.LinkedList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.projectnyx.network.ext.PacketWithAddress; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.ext.udp;
@RequiredArgsConstructor
public class UdpBufferThread extends Thread {
private final SharedUdpServerSocket owner;
private final InetSocketAddress address;
private DatagramChannel channel;
private DatagramSocket socket;
| // Path: src/main/java/org/projectnyx/network/ext/PacketWithAddress.java
// public class PacketWithAddress {
// @Getter private final ByteBuffer buffer;
// @Getter private final InetSocketAddress address;
//
// /**
// * The buffer will be automatically flipped if the position is not at 0
// *
// * @param buffer the buffer of data to send, from 0 to limit if position is 0, or from 0 to position if position is
// * not 0
// * @param address the target address of the client. can be null in some network implementations.
// */
// public PacketWithAddress(ByteBuffer buffer, InetSocketAddress address) {
// this(buffer, address, buffer.position() != 0);
// }
//
// public PacketWithAddress(ByteBuffer buffer, InetSocketAddress address, boolean flip) {
// if(flip) {
// if(buffer.position() == 0) {
// Nyx.getLog().warn("Attempt to flip buffer with zero length", new Throwable("Backtrace"));
// }
// if(buffer.array().length >= (buffer.position() << 3)) { // save some memory
// buffer = ByteBuffer.wrap(ArrayUtils.subarray(buffer.array(), 0, buffer.position()));
// } else {
// buffer.flip();
// }
// }
// this.buffer = buffer;
// this.address = address;
// }
//
// @Override
// public String toString() {
// return "Data from address " + address.toString() + ": " + Hex.encodeHexString(buffer.array());
// }
// }
// Path: src/main/java/org/projectnyx/network/ext/udp/UdpBufferThread.java
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.LinkedList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.projectnyx.network.ext.PacketWithAddress;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.ext.udp;
@RequiredArgsConstructor
public class UdpBufferThread extends Thread {
private final SharedUdpServerSocket owner;
private final InetSocketAddress address;
private DatagramChannel channel;
private DatagramSocket socket;
| private final List<PacketWithAddress> receive = new LinkedList<>(); |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/ext/SharedSocketPool.java | // Path: src/main/java/org/projectnyx/network/ext/SharedServerSocket.java
// @Value
// public static class Identifier {
// String type;
// InetAddress address;
// int port;
//
// public SharedServerSocket create() {
// switch(type) {
// case SharedUdpServerSocket.TYPE:
// return new SharedUdpServerSocket(new InetSocketAddress(address, port));
// }
// throw new UnsupportedOperationException("Unknown socket type " + type);
// }
// }
| import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import lombok.NonNull;
import org.projectnyx.network.ext.SharedServerSocket.Identifier; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.ext;
public class SharedSocketPool {
@Getter private static SharedSocketPool instance;
| // Path: src/main/java/org/projectnyx/network/ext/SharedServerSocket.java
// @Value
// public static class Identifier {
// String type;
// InetAddress address;
// int port;
//
// public SharedServerSocket create() {
// switch(type) {
// case SharedUdpServerSocket.TYPE:
// return new SharedUdpServerSocket(new InetSocketAddress(address, port));
// }
// throw new UnsupportedOperationException("Unknown socket type " + type);
// }
// }
// Path: src/main/java/org/projectnyx/network/ext/SharedSocketPool.java
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import lombok.NonNull;
import org.projectnyx.network.ext.SharedServerSocket.Identifier;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.ext;
public class SharedSocketPool {
@Getter private static SharedSocketPool instance;
| private Map<Identifier, SharedServerSocket> sockets = new HashMap<>(); |
Project-Nyx/Nyx | src/main/java/org/projectnyx/command/CommandManager.java | // Path: src/main/java/org/projectnyx/command/impl/StopCommand.java
// public class StopCommand extends Command {
// public StopCommand() {
// super("stop");
// }
//
// @Override
// protected void run() {
// Nyx.getInstance().shutdown();
// }
// }
| import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import org.projectnyx.command.impl.StopCommand; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.command;
public class CommandManager {
@Getter private Map<String, Command> commands = new HashMap<>();
public CommandManager() {
registerDefaults();
}
private void registerDefaults() { | // Path: src/main/java/org/projectnyx/command/impl/StopCommand.java
// public class StopCommand extends Command {
// public StopCommand() {
// super("stop");
// }
//
// @Override
// protected void run() {
// Nyx.getInstance().shutdown();
// }
// }
// Path: src/main/java/org/projectnyx/command/CommandManager.java
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import org.projectnyx.command.impl.StopCommand;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.command;
public class CommandManager {
@Getter private Map<String, Command> commands = new HashMap<>();
public CommandManager() {
registerDefaults();
}
private void registerDefaults() { | registerCommand(new StopCommand()); |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/NetworkManager.java | // Path: src/main/java/org/projectnyx/module/ModuleManager.java
// public abstract class ModuleManager<T> {
// private final Class<T> myClass;
// @Getter(lazy = true) private final String moduleTypeName = moduleType();
// @Getter private Map<String, T> modules = new HashMap<>();
//
// protected abstract String moduleType();
//
// protected ModuleManager(Class<T> myClass) {
// this.myClass = myClass;
// Nyx.getInstance().getModuleManagers().put(getModuleTypeName(), this);
// }
//
// public void loadForClass(String name, String className) throws Exception {
// Class<? extends T> aClass = Class.forName(className).asSubclass(myClass);
// T instance = aClass.newInstance();
// modules.put(name, instance);
// }
// }
//
// Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
// @RequiredArgsConstructor
// public abstract class SessionHandler {
// @Getter private final InetSocketAddress address;
// @Getter private final SharedServerSocket socket;
//
// public abstract void onReceive(PacketWithAddress pk);
//
// public abstract void send(ByteBuffer buffer);
//
// public abstract void close();
//
// public abstract Protocol getProtocol();
//
// public void tick() {
//
// }
//
// /**
// * <p>Returns whether this session an orphan.</p>
// *
// * <p>An orphan session is a session that has not been recognized by any sessions yet.</p>
// *
// * @return whether this session is an orphan.
// */
// public abstract boolean isOrphan();
// }
//
// Path: src/main/java/org/projectnyx/network/ext/SharedSocketPool.java
// public class SharedSocketPool {
// @Getter private static SharedSocketPool instance;
//
// private Map<Identifier, SharedServerSocket> sockets = new HashMap<>();
//
// public SharedSocketPool() {
// instance = this;
// }
//
// @NonNull
// public SharedServerSocket getOrCreate(Identifier identifier) {
// if(!sockets.containsKey(identifier)) {
// addSocket(identifier.create());
// }
// return sockets.get(identifier);
// }
//
// void addSocket(SharedServerSocket socket) {
// sockets.put(socket.getIdentifier(), socket);
// }
//
// void removeSocket(SharedServerSocket socket) {
// sockets.remove(socket.getIdentifier(), socket);
// }
//
// public void tick() {
// sockets.values().forEach(SharedServerSocket::tick);
// }
// }
| import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.projectnyx.module.ModuleManager;
import org.projectnyx.network.ext.SessionHandler;
import org.projectnyx.network.ext.SharedSocketPool; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network;
public class NetworkManager extends ModuleManager<Protocol> {
@Getter private static NetworkManager instance;
@Getter @Setter @NotNull private QueryResponse queryResponse; | // Path: src/main/java/org/projectnyx/module/ModuleManager.java
// public abstract class ModuleManager<T> {
// private final Class<T> myClass;
// @Getter(lazy = true) private final String moduleTypeName = moduleType();
// @Getter private Map<String, T> modules = new HashMap<>();
//
// protected abstract String moduleType();
//
// protected ModuleManager(Class<T> myClass) {
// this.myClass = myClass;
// Nyx.getInstance().getModuleManagers().put(getModuleTypeName(), this);
// }
//
// public void loadForClass(String name, String className) throws Exception {
// Class<? extends T> aClass = Class.forName(className).asSubclass(myClass);
// T instance = aClass.newInstance();
// modules.put(name, instance);
// }
// }
//
// Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
// @RequiredArgsConstructor
// public abstract class SessionHandler {
// @Getter private final InetSocketAddress address;
// @Getter private final SharedServerSocket socket;
//
// public abstract void onReceive(PacketWithAddress pk);
//
// public abstract void send(ByteBuffer buffer);
//
// public abstract void close();
//
// public abstract Protocol getProtocol();
//
// public void tick() {
//
// }
//
// /**
// * <p>Returns whether this session an orphan.</p>
// *
// * <p>An orphan session is a session that has not been recognized by any sessions yet.</p>
// *
// * @return whether this session is an orphan.
// */
// public abstract boolean isOrphan();
// }
//
// Path: src/main/java/org/projectnyx/network/ext/SharedSocketPool.java
// public class SharedSocketPool {
// @Getter private static SharedSocketPool instance;
//
// private Map<Identifier, SharedServerSocket> sockets = new HashMap<>();
//
// public SharedSocketPool() {
// instance = this;
// }
//
// @NonNull
// public SharedServerSocket getOrCreate(Identifier identifier) {
// if(!sockets.containsKey(identifier)) {
// addSocket(identifier.create());
// }
// return sockets.get(identifier);
// }
//
// void addSocket(SharedServerSocket socket) {
// sockets.put(socket.getIdentifier(), socket);
// }
//
// void removeSocket(SharedServerSocket socket) {
// sockets.remove(socket.getIdentifier(), socket);
// }
//
// public void tick() {
// sockets.values().forEach(SharedServerSocket::tick);
// }
// }
// Path: src/main/java/org/projectnyx/network/NetworkManager.java
import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.projectnyx.module.ModuleManager;
import org.projectnyx.network.ext.SessionHandler;
import org.projectnyx.network.ext.SharedSocketPool;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network;
public class NetworkManager extends ModuleManager<Protocol> {
@Getter private static NetworkManager instance;
@Getter @Setter @NotNull private QueryResponse queryResponse; | private final SharedSocketPool sockets = new SharedSocketPool(); |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/NetworkManager.java | // Path: src/main/java/org/projectnyx/module/ModuleManager.java
// public abstract class ModuleManager<T> {
// private final Class<T> myClass;
// @Getter(lazy = true) private final String moduleTypeName = moduleType();
// @Getter private Map<String, T> modules = new HashMap<>();
//
// protected abstract String moduleType();
//
// protected ModuleManager(Class<T> myClass) {
// this.myClass = myClass;
// Nyx.getInstance().getModuleManagers().put(getModuleTypeName(), this);
// }
//
// public void loadForClass(String name, String className) throws Exception {
// Class<? extends T> aClass = Class.forName(className).asSubclass(myClass);
// T instance = aClass.newInstance();
// modules.put(name, instance);
// }
// }
//
// Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
// @RequiredArgsConstructor
// public abstract class SessionHandler {
// @Getter private final InetSocketAddress address;
// @Getter private final SharedServerSocket socket;
//
// public abstract void onReceive(PacketWithAddress pk);
//
// public abstract void send(ByteBuffer buffer);
//
// public abstract void close();
//
// public abstract Protocol getProtocol();
//
// public void tick() {
//
// }
//
// /**
// * <p>Returns whether this session an orphan.</p>
// *
// * <p>An orphan session is a session that has not been recognized by any sessions yet.</p>
// *
// * @return whether this session is an orphan.
// */
// public abstract boolean isOrphan();
// }
//
// Path: src/main/java/org/projectnyx/network/ext/SharedSocketPool.java
// public class SharedSocketPool {
// @Getter private static SharedSocketPool instance;
//
// private Map<Identifier, SharedServerSocket> sockets = new HashMap<>();
//
// public SharedSocketPool() {
// instance = this;
// }
//
// @NonNull
// public SharedServerSocket getOrCreate(Identifier identifier) {
// if(!sockets.containsKey(identifier)) {
// addSocket(identifier.create());
// }
// return sockets.get(identifier);
// }
//
// void addSocket(SharedServerSocket socket) {
// sockets.put(socket.getIdentifier(), socket);
// }
//
// void removeSocket(SharedServerSocket socket) {
// sockets.remove(socket.getIdentifier(), socket);
// }
//
// public void tick() {
// sockets.values().forEach(SharedServerSocket::tick);
// }
// }
| import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.projectnyx.module.ModuleManager;
import org.projectnyx.network.ext.SessionHandler;
import org.projectnyx.network.ext.SharedSocketPool; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network;
public class NetworkManager extends ModuleManager<Protocol> {
@Getter private static NetworkManager instance;
@Getter @Setter @NotNull private QueryResponse queryResponse;
private final SharedSocketPool sockets = new SharedSocketPool();
private boolean running = true;
public NetworkManager() {
super(Protocol.class);
instance = this;
queryResponse = new QueryResponse();
queryResponse.setName("Nyx rised.");
queryResponse.setCountPlayers(1);
queryResponse.setMaxPlayers(10);
}
public void start() {
new Thread(() -> {
while(running) {
sockets.tick();
}
}).start();
}
@Override
protected String moduleType() {
return "Protocol";
}
/**
* Requires a protocol to adopt this session.
*
* @param session
* @return
*/ | // Path: src/main/java/org/projectnyx/module/ModuleManager.java
// public abstract class ModuleManager<T> {
// private final Class<T> myClass;
// @Getter(lazy = true) private final String moduleTypeName = moduleType();
// @Getter private Map<String, T> modules = new HashMap<>();
//
// protected abstract String moduleType();
//
// protected ModuleManager(Class<T> myClass) {
// this.myClass = myClass;
// Nyx.getInstance().getModuleManagers().put(getModuleTypeName(), this);
// }
//
// public void loadForClass(String name, String className) throws Exception {
// Class<? extends T> aClass = Class.forName(className).asSubclass(myClass);
// T instance = aClass.newInstance();
// modules.put(name, instance);
// }
// }
//
// Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
// @RequiredArgsConstructor
// public abstract class SessionHandler {
// @Getter private final InetSocketAddress address;
// @Getter private final SharedServerSocket socket;
//
// public abstract void onReceive(PacketWithAddress pk);
//
// public abstract void send(ByteBuffer buffer);
//
// public abstract void close();
//
// public abstract Protocol getProtocol();
//
// public void tick() {
//
// }
//
// /**
// * <p>Returns whether this session an orphan.</p>
// *
// * <p>An orphan session is a session that has not been recognized by any sessions yet.</p>
// *
// * @return whether this session is an orphan.
// */
// public abstract boolean isOrphan();
// }
//
// Path: src/main/java/org/projectnyx/network/ext/SharedSocketPool.java
// public class SharedSocketPool {
// @Getter private static SharedSocketPool instance;
//
// private Map<Identifier, SharedServerSocket> sockets = new HashMap<>();
//
// public SharedSocketPool() {
// instance = this;
// }
//
// @NonNull
// public SharedServerSocket getOrCreate(Identifier identifier) {
// if(!sockets.containsKey(identifier)) {
// addSocket(identifier.create());
// }
// return sockets.get(identifier);
// }
//
// void addSocket(SharedServerSocket socket) {
// sockets.put(socket.getIdentifier(), socket);
// }
//
// void removeSocket(SharedServerSocket socket) {
// sockets.remove(socket.getIdentifier(), socket);
// }
//
// public void tick() {
// sockets.values().forEach(SharedServerSocket::tick);
// }
// }
// Path: src/main/java/org/projectnyx/network/NetworkManager.java
import javax.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.projectnyx.module.ModuleManager;
import org.projectnyx.network.ext.SessionHandler;
import org.projectnyx.network.ext.SharedSocketPool;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network;
public class NetworkManager extends ModuleManager<Protocol> {
@Getter private static NetworkManager instance;
@Getter @Setter @NotNull private QueryResponse queryResponse;
private final SharedSocketPool sockets = new SharedSocketPool();
private boolean running = true;
public NetworkManager() {
super(Protocol.class);
instance = this;
queryResponse = new QueryResponse();
queryResponse.setName("Nyx rised.");
queryResponse.setCountPlayers(1);
queryResponse.setMaxPlayers(10);
}
public void start() {
new Thread(() -> {
while(running) {
sockets.tick();
}
}).start();
}
@Override
protected String moduleType() {
return "Protocol";
}
/**
* Requires a protocol to adopt this session.
*
* @param session
* @return
*/ | public Client adoptSession(SessionHandler session) { |
Project-Nyx/Nyx | src/main/java/org/projectnyx/network/ext/SessionHandler.java | // Path: src/main/java/org/projectnyx/network/Protocol.java
// public abstract class Protocol {
// protected Protocol() {
// init();
// }
//
// public abstract void init();
//
// public abstract Client acceptSession(SessionHandler session);
//
// public abstract String getName();
// }
| import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.projectnyx.network.Protocol; | /*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.ext;
@RequiredArgsConstructor
public abstract class SessionHandler {
@Getter private final InetSocketAddress address;
@Getter private final SharedServerSocket socket;
public abstract void onReceive(PacketWithAddress pk);
public abstract void send(ByteBuffer buffer);
public abstract void close();
| // Path: src/main/java/org/projectnyx/network/Protocol.java
// public abstract class Protocol {
// protected Protocol() {
// init();
// }
//
// public abstract void init();
//
// public abstract Client acceptSession(SessionHandler session);
//
// public abstract String getName();
// }
// Path: src/main/java/org/projectnyx/network/ext/SessionHandler.java
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.projectnyx.network.Protocol;
/*
* Nyx - Server software for Minecraft: PE and more
* Copyright © boredphoton 2016
*
* 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 org.projectnyx.network.ext;
@RequiredArgsConstructor
public abstract class SessionHandler {
@Getter private final InetSocketAddress address;
@Getter private final SharedServerSocket socket;
public abstract void onReceive(PacketWithAddress pk);
public abstract void send(ByteBuffer buffer);
public abstract void close();
| public abstract Protocol getProtocol(); |
rolandkrueger/user-microservice | service/src/test/java/info/rolandkrueger/userservice/service/UserDetailServiceImplTest.java | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/StaticEndpointProvider.java
// @Service
// public class StaticEndpointProvider implements UserMicroserviceEndpointProvider {
//
// private String endpoint;
//
// protected StaticEndpointProvider() {
// }
//
// /**
// * Creates a new StaticEndpointProvider for the given static endpoint URL.
// *
// * @param endpoint static endpoint address for the user micro-service
// */
// public StaticEndpointProvider(String endpoint) {
// this.endpoint = endpoint;
// }
//
// /**
// * Returns the fixed user service endpoint address passed in through the constructor.
// */
// @Override
// public String getUserMicroserviceEndpoint() {
// return endpoint;
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/UserDetailServiceImpl.java
// @Service
// public class UserDetailServiceImpl implements UserDetailsService {
//
// private UserMicroserviceEndpointProvider endpointProvider;
//
// /**
// * Constructor which is autowired with an instance of {@link UserMicroserviceEndpointProvider}.
// */
// @Autowired
// public UserDetailServiceImpl(UserMicroserviceEndpointProvider endpointProvider) {
// Preconditions.checkNotNull(endpointProvider);
// this.endpointProvider = endpointProvider;
// }
//
// /**
// * Load a {@link UserDetails} object from the user micro-service for the specified username. Note that this method
// * in addition to a {@link UsernameNotFoundException} throws an unchecked {@link RestClientException} to indicate
// * errors that occurred during the communication process with the remote user micro-service.
// *
// * @param username name of the user to be loaded
// * @return a {@link UserDetails} object
// * @throws UsernameNotFoundException when the given username is not known to the service
// * @throws RestClientException when some error occurred while calling the REST service
// */
// @Override
// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, RestClientException {
// UserService userService = UserServiceAPI.init(endpointProvider.getUserMicroserviceEndpoint());
// Optional<UserApiData> loadedUser = userService.users().search().findByUsername(username).getData().stream().findFirst();
// if (!loadedUser.isPresent()) {
// throw new UsernameNotFoundException("User " + username + " not found");
// }
// return loadedUser.get().getResource().useProjection(UserProjections.FULL_DATA).read();
// }
// }
//
// Path: service/src/test/java/info/rolandkrueger/userservice/testsupport/AbstractRestControllerTest.java
// public abstract class AbstractRestControllerTest {
//
// private final static String CONTEXT_PATH = "http://localhost:";
//
// private static UserService service;
// private static int port = 8080;
//
// protected static void setPort(int port) {
// AbstractRestControllerTest.port = port;
// }
//
// protected static UserService service() {
// if (service == null) {
// service = UserServiceAPI.init(CONTEXT_PATH + port);
// }
// return service;
// }
//
// @After
// public void tearDown(){
// deleteAllUsers();
// deleteAllAuthorities();
// }
//
// protected static void deleteAllUsers() {
// UsersResource users;
// do {
// users = service().users();
// users.getData().stream().forEach(user -> user.getResource().delete());
// } while (users.hasNext());
// }
//
// protected static void deleteAllAuthorities() {
// AuthoritiesResource authorities;
// do {
// authorities = service().authorities();
// authorities.getData().stream().forEach(authority -> authority.getResource().delete());
// } while (authorities.hasNext());
// }
//
// protected static AuthorityApiData createAuthority(String authority) {
// AuthorityApiData authorityApiData = new AuthorityApiData();
// authorityApiData.setAuthority(authority);
// authorityApiData.setDescription("The " + authority + " role");
// return service().authorities().create(authorityApiData).getBody();
// }
//
// protected static UserApiData registerUser(String username, String password, String email) {
// ResponseEntity<UserRegistrationApiData> registrationResponse =
// service()
// .userRegistrations()
// .create(username, password, email);
//
// service()
// .userRegistrations()
// .findByToken(registrationResponse.getBody().getRegistrationConfirmationToken())
// .confirmRegistration();
//
// return service()
// .users()
// .search()
// .findByUsername(username).getData().stream().findFirst().get();
// }
//
// }
| import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.api.service.StaticEndpointProvider;
import info.rolandkrueger.userservice.api.service.UserDetailServiceImpl;
import info.rolandkrueger.userservice.testsupport.AbstractRestControllerTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue; | package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@WebIntegrationTest(randomPort = true) | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/StaticEndpointProvider.java
// @Service
// public class StaticEndpointProvider implements UserMicroserviceEndpointProvider {
//
// private String endpoint;
//
// protected StaticEndpointProvider() {
// }
//
// /**
// * Creates a new StaticEndpointProvider for the given static endpoint URL.
// *
// * @param endpoint static endpoint address for the user micro-service
// */
// public StaticEndpointProvider(String endpoint) {
// this.endpoint = endpoint;
// }
//
// /**
// * Returns the fixed user service endpoint address passed in through the constructor.
// */
// @Override
// public String getUserMicroserviceEndpoint() {
// return endpoint;
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/UserDetailServiceImpl.java
// @Service
// public class UserDetailServiceImpl implements UserDetailsService {
//
// private UserMicroserviceEndpointProvider endpointProvider;
//
// /**
// * Constructor which is autowired with an instance of {@link UserMicroserviceEndpointProvider}.
// */
// @Autowired
// public UserDetailServiceImpl(UserMicroserviceEndpointProvider endpointProvider) {
// Preconditions.checkNotNull(endpointProvider);
// this.endpointProvider = endpointProvider;
// }
//
// /**
// * Load a {@link UserDetails} object from the user micro-service for the specified username. Note that this method
// * in addition to a {@link UsernameNotFoundException} throws an unchecked {@link RestClientException} to indicate
// * errors that occurred during the communication process with the remote user micro-service.
// *
// * @param username name of the user to be loaded
// * @return a {@link UserDetails} object
// * @throws UsernameNotFoundException when the given username is not known to the service
// * @throws RestClientException when some error occurred while calling the REST service
// */
// @Override
// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, RestClientException {
// UserService userService = UserServiceAPI.init(endpointProvider.getUserMicroserviceEndpoint());
// Optional<UserApiData> loadedUser = userService.users().search().findByUsername(username).getData().stream().findFirst();
// if (!loadedUser.isPresent()) {
// throw new UsernameNotFoundException("User " + username + " not found");
// }
// return loadedUser.get().getResource().useProjection(UserProjections.FULL_DATA).read();
// }
// }
//
// Path: service/src/test/java/info/rolandkrueger/userservice/testsupport/AbstractRestControllerTest.java
// public abstract class AbstractRestControllerTest {
//
// private final static String CONTEXT_PATH = "http://localhost:";
//
// private static UserService service;
// private static int port = 8080;
//
// protected static void setPort(int port) {
// AbstractRestControllerTest.port = port;
// }
//
// protected static UserService service() {
// if (service == null) {
// service = UserServiceAPI.init(CONTEXT_PATH + port);
// }
// return service;
// }
//
// @After
// public void tearDown(){
// deleteAllUsers();
// deleteAllAuthorities();
// }
//
// protected static void deleteAllUsers() {
// UsersResource users;
// do {
// users = service().users();
// users.getData().stream().forEach(user -> user.getResource().delete());
// } while (users.hasNext());
// }
//
// protected static void deleteAllAuthorities() {
// AuthoritiesResource authorities;
// do {
// authorities = service().authorities();
// authorities.getData().stream().forEach(authority -> authority.getResource().delete());
// } while (authorities.hasNext());
// }
//
// protected static AuthorityApiData createAuthority(String authority) {
// AuthorityApiData authorityApiData = new AuthorityApiData();
// authorityApiData.setAuthority(authority);
// authorityApiData.setDescription("The " + authority + " role");
// return service().authorities().create(authorityApiData).getBody();
// }
//
// protected static UserApiData registerUser(String username, String password, String email) {
// ResponseEntity<UserRegistrationApiData> registrationResponse =
// service()
// .userRegistrations()
// .create(username, password, email);
//
// service()
// .userRegistrations()
// .findByToken(registrationResponse.getBody().getRegistrationConfirmationToken())
// .confirmRegistration();
//
// return service()
// .users()
// .search()
// .findByUsername(username).getData().stream().findFirst().get();
// }
//
// }
// Path: service/src/test/java/info/rolandkrueger/userservice/service/UserDetailServiceImplTest.java
import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.api.service.StaticEndpointProvider;
import info.rolandkrueger.userservice.api.service.UserDetailServiceImpl;
import info.rolandkrueger.userservice.testsupport.AbstractRestControllerTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue;
package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@WebIntegrationTest(randomPort = true) | public class UserDetailServiceImplTest extends AbstractRestControllerTest { |
rolandkrueger/user-microservice | service/src/test/java/info/rolandkrueger/userservice/service/UserDetailServiceImplTest.java | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/StaticEndpointProvider.java
// @Service
// public class StaticEndpointProvider implements UserMicroserviceEndpointProvider {
//
// private String endpoint;
//
// protected StaticEndpointProvider() {
// }
//
// /**
// * Creates a new StaticEndpointProvider for the given static endpoint URL.
// *
// * @param endpoint static endpoint address for the user micro-service
// */
// public StaticEndpointProvider(String endpoint) {
// this.endpoint = endpoint;
// }
//
// /**
// * Returns the fixed user service endpoint address passed in through the constructor.
// */
// @Override
// public String getUserMicroserviceEndpoint() {
// return endpoint;
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/UserDetailServiceImpl.java
// @Service
// public class UserDetailServiceImpl implements UserDetailsService {
//
// private UserMicroserviceEndpointProvider endpointProvider;
//
// /**
// * Constructor which is autowired with an instance of {@link UserMicroserviceEndpointProvider}.
// */
// @Autowired
// public UserDetailServiceImpl(UserMicroserviceEndpointProvider endpointProvider) {
// Preconditions.checkNotNull(endpointProvider);
// this.endpointProvider = endpointProvider;
// }
//
// /**
// * Load a {@link UserDetails} object from the user micro-service for the specified username. Note that this method
// * in addition to a {@link UsernameNotFoundException} throws an unchecked {@link RestClientException} to indicate
// * errors that occurred during the communication process with the remote user micro-service.
// *
// * @param username name of the user to be loaded
// * @return a {@link UserDetails} object
// * @throws UsernameNotFoundException when the given username is not known to the service
// * @throws RestClientException when some error occurred while calling the REST service
// */
// @Override
// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, RestClientException {
// UserService userService = UserServiceAPI.init(endpointProvider.getUserMicroserviceEndpoint());
// Optional<UserApiData> loadedUser = userService.users().search().findByUsername(username).getData().stream().findFirst();
// if (!loadedUser.isPresent()) {
// throw new UsernameNotFoundException("User " + username + " not found");
// }
// return loadedUser.get().getResource().useProjection(UserProjections.FULL_DATA).read();
// }
// }
//
// Path: service/src/test/java/info/rolandkrueger/userservice/testsupport/AbstractRestControllerTest.java
// public abstract class AbstractRestControllerTest {
//
// private final static String CONTEXT_PATH = "http://localhost:";
//
// private static UserService service;
// private static int port = 8080;
//
// protected static void setPort(int port) {
// AbstractRestControllerTest.port = port;
// }
//
// protected static UserService service() {
// if (service == null) {
// service = UserServiceAPI.init(CONTEXT_PATH + port);
// }
// return service;
// }
//
// @After
// public void tearDown(){
// deleteAllUsers();
// deleteAllAuthorities();
// }
//
// protected static void deleteAllUsers() {
// UsersResource users;
// do {
// users = service().users();
// users.getData().stream().forEach(user -> user.getResource().delete());
// } while (users.hasNext());
// }
//
// protected static void deleteAllAuthorities() {
// AuthoritiesResource authorities;
// do {
// authorities = service().authorities();
// authorities.getData().stream().forEach(authority -> authority.getResource().delete());
// } while (authorities.hasNext());
// }
//
// protected static AuthorityApiData createAuthority(String authority) {
// AuthorityApiData authorityApiData = new AuthorityApiData();
// authorityApiData.setAuthority(authority);
// authorityApiData.setDescription("The " + authority + " role");
// return service().authorities().create(authorityApiData).getBody();
// }
//
// protected static UserApiData registerUser(String username, String password, String email) {
// ResponseEntity<UserRegistrationApiData> registrationResponse =
// service()
// .userRegistrations()
// .create(username, password, email);
//
// service()
// .userRegistrations()
// .findByToken(registrationResponse.getBody().getRegistrationConfirmationToken())
// .confirmRegistration();
//
// return service()
// .users()
// .search()
// .findByUsername(username).getData().stream().findFirst().get();
// }
//
// }
| import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.api.service.StaticEndpointProvider;
import info.rolandkrueger.userservice.api.service.UserDetailServiceImpl;
import info.rolandkrueger.userservice.testsupport.AbstractRestControllerTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue; | package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@WebIntegrationTest(randomPort = true)
public class UserDetailServiceImplTest extends AbstractRestControllerTest {
| // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/StaticEndpointProvider.java
// @Service
// public class StaticEndpointProvider implements UserMicroserviceEndpointProvider {
//
// private String endpoint;
//
// protected StaticEndpointProvider() {
// }
//
// /**
// * Creates a new StaticEndpointProvider for the given static endpoint URL.
// *
// * @param endpoint static endpoint address for the user micro-service
// */
// public StaticEndpointProvider(String endpoint) {
// this.endpoint = endpoint;
// }
//
// /**
// * Returns the fixed user service endpoint address passed in through the constructor.
// */
// @Override
// public String getUserMicroserviceEndpoint() {
// return endpoint;
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/UserDetailServiceImpl.java
// @Service
// public class UserDetailServiceImpl implements UserDetailsService {
//
// private UserMicroserviceEndpointProvider endpointProvider;
//
// /**
// * Constructor which is autowired with an instance of {@link UserMicroserviceEndpointProvider}.
// */
// @Autowired
// public UserDetailServiceImpl(UserMicroserviceEndpointProvider endpointProvider) {
// Preconditions.checkNotNull(endpointProvider);
// this.endpointProvider = endpointProvider;
// }
//
// /**
// * Load a {@link UserDetails} object from the user micro-service for the specified username. Note that this method
// * in addition to a {@link UsernameNotFoundException} throws an unchecked {@link RestClientException} to indicate
// * errors that occurred during the communication process with the remote user micro-service.
// *
// * @param username name of the user to be loaded
// * @return a {@link UserDetails} object
// * @throws UsernameNotFoundException when the given username is not known to the service
// * @throws RestClientException when some error occurred while calling the REST service
// */
// @Override
// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, RestClientException {
// UserService userService = UserServiceAPI.init(endpointProvider.getUserMicroserviceEndpoint());
// Optional<UserApiData> loadedUser = userService.users().search().findByUsername(username).getData().stream().findFirst();
// if (!loadedUser.isPresent()) {
// throw new UsernameNotFoundException("User " + username + " not found");
// }
// return loadedUser.get().getResource().useProjection(UserProjections.FULL_DATA).read();
// }
// }
//
// Path: service/src/test/java/info/rolandkrueger/userservice/testsupport/AbstractRestControllerTest.java
// public abstract class AbstractRestControllerTest {
//
// private final static String CONTEXT_PATH = "http://localhost:";
//
// private static UserService service;
// private static int port = 8080;
//
// protected static void setPort(int port) {
// AbstractRestControllerTest.port = port;
// }
//
// protected static UserService service() {
// if (service == null) {
// service = UserServiceAPI.init(CONTEXT_PATH + port);
// }
// return service;
// }
//
// @After
// public void tearDown(){
// deleteAllUsers();
// deleteAllAuthorities();
// }
//
// protected static void deleteAllUsers() {
// UsersResource users;
// do {
// users = service().users();
// users.getData().stream().forEach(user -> user.getResource().delete());
// } while (users.hasNext());
// }
//
// protected static void deleteAllAuthorities() {
// AuthoritiesResource authorities;
// do {
// authorities = service().authorities();
// authorities.getData().stream().forEach(authority -> authority.getResource().delete());
// } while (authorities.hasNext());
// }
//
// protected static AuthorityApiData createAuthority(String authority) {
// AuthorityApiData authorityApiData = new AuthorityApiData();
// authorityApiData.setAuthority(authority);
// authorityApiData.setDescription("The " + authority + " role");
// return service().authorities().create(authorityApiData).getBody();
// }
//
// protected static UserApiData registerUser(String username, String password, String email) {
// ResponseEntity<UserRegistrationApiData> registrationResponse =
// service()
// .userRegistrations()
// .create(username, password, email);
//
// service()
// .userRegistrations()
// .findByToken(registrationResponse.getBody().getRegistrationConfirmationToken())
// .confirmRegistration();
//
// return service()
// .users()
// .search()
// .findByUsername(username).getData().stream().findFirst().get();
// }
//
// }
// Path: service/src/test/java/info/rolandkrueger/userservice/service/UserDetailServiceImplTest.java
import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.api.service.StaticEndpointProvider;
import info.rolandkrueger.userservice.api.service.UserDetailServiceImpl;
import info.rolandkrueger.userservice.testsupport.AbstractRestControllerTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue;
package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@WebIntegrationTest(randomPort = true)
public class UserDetailServiceImplTest extends AbstractRestControllerTest {
| private UserDetailServiceImpl userDetailService; |
rolandkrueger/user-microservice | service/src/test/java/info/rolandkrueger/userservice/service/UserDetailServiceImplTest.java | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/StaticEndpointProvider.java
// @Service
// public class StaticEndpointProvider implements UserMicroserviceEndpointProvider {
//
// private String endpoint;
//
// protected StaticEndpointProvider() {
// }
//
// /**
// * Creates a new StaticEndpointProvider for the given static endpoint URL.
// *
// * @param endpoint static endpoint address for the user micro-service
// */
// public StaticEndpointProvider(String endpoint) {
// this.endpoint = endpoint;
// }
//
// /**
// * Returns the fixed user service endpoint address passed in through the constructor.
// */
// @Override
// public String getUserMicroserviceEndpoint() {
// return endpoint;
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/UserDetailServiceImpl.java
// @Service
// public class UserDetailServiceImpl implements UserDetailsService {
//
// private UserMicroserviceEndpointProvider endpointProvider;
//
// /**
// * Constructor which is autowired with an instance of {@link UserMicroserviceEndpointProvider}.
// */
// @Autowired
// public UserDetailServiceImpl(UserMicroserviceEndpointProvider endpointProvider) {
// Preconditions.checkNotNull(endpointProvider);
// this.endpointProvider = endpointProvider;
// }
//
// /**
// * Load a {@link UserDetails} object from the user micro-service for the specified username. Note that this method
// * in addition to a {@link UsernameNotFoundException} throws an unchecked {@link RestClientException} to indicate
// * errors that occurred during the communication process with the remote user micro-service.
// *
// * @param username name of the user to be loaded
// * @return a {@link UserDetails} object
// * @throws UsernameNotFoundException when the given username is not known to the service
// * @throws RestClientException when some error occurred while calling the REST service
// */
// @Override
// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, RestClientException {
// UserService userService = UserServiceAPI.init(endpointProvider.getUserMicroserviceEndpoint());
// Optional<UserApiData> loadedUser = userService.users().search().findByUsername(username).getData().stream().findFirst();
// if (!loadedUser.isPresent()) {
// throw new UsernameNotFoundException("User " + username + " not found");
// }
// return loadedUser.get().getResource().useProjection(UserProjections.FULL_DATA).read();
// }
// }
//
// Path: service/src/test/java/info/rolandkrueger/userservice/testsupport/AbstractRestControllerTest.java
// public abstract class AbstractRestControllerTest {
//
// private final static String CONTEXT_PATH = "http://localhost:";
//
// private static UserService service;
// private static int port = 8080;
//
// protected static void setPort(int port) {
// AbstractRestControllerTest.port = port;
// }
//
// protected static UserService service() {
// if (service == null) {
// service = UserServiceAPI.init(CONTEXT_PATH + port);
// }
// return service;
// }
//
// @After
// public void tearDown(){
// deleteAllUsers();
// deleteAllAuthorities();
// }
//
// protected static void deleteAllUsers() {
// UsersResource users;
// do {
// users = service().users();
// users.getData().stream().forEach(user -> user.getResource().delete());
// } while (users.hasNext());
// }
//
// protected static void deleteAllAuthorities() {
// AuthoritiesResource authorities;
// do {
// authorities = service().authorities();
// authorities.getData().stream().forEach(authority -> authority.getResource().delete());
// } while (authorities.hasNext());
// }
//
// protected static AuthorityApiData createAuthority(String authority) {
// AuthorityApiData authorityApiData = new AuthorityApiData();
// authorityApiData.setAuthority(authority);
// authorityApiData.setDescription("The " + authority + " role");
// return service().authorities().create(authorityApiData).getBody();
// }
//
// protected static UserApiData registerUser(String username, String password, String email) {
// ResponseEntity<UserRegistrationApiData> registrationResponse =
// service()
// .userRegistrations()
// .create(username, password, email);
//
// service()
// .userRegistrations()
// .findByToken(registrationResponse.getBody().getRegistrationConfirmationToken())
// .confirmRegistration();
//
// return service()
// .users()
// .search()
// .findByUsername(username).getData().stream().findFirst().get();
// }
//
// }
| import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.api.service.StaticEndpointProvider;
import info.rolandkrueger.userservice.api.service.UserDetailServiceImpl;
import info.rolandkrueger.userservice.testsupport.AbstractRestControllerTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue; | package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@WebIntegrationTest(randomPort = true)
public class UserDetailServiceImplTest extends AbstractRestControllerTest {
private UserDetailServiceImpl userDetailService; | // Path: service/src/main/java/info/rolandkrueger/userservice/UserMicroserviceApplication.java
// @SpringBootApplication
// @PropertySource("userservice.properties")
// public class UserMicroserviceApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(
// new Object[]{
// UserMicroserviceApplication.class,
// DevelopmentProfileConfiguration.class}
// , args);
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/StaticEndpointProvider.java
// @Service
// public class StaticEndpointProvider implements UserMicroserviceEndpointProvider {
//
// private String endpoint;
//
// protected StaticEndpointProvider() {
// }
//
// /**
// * Creates a new StaticEndpointProvider for the given static endpoint URL.
// *
// * @param endpoint static endpoint address for the user micro-service
// */
// public StaticEndpointProvider(String endpoint) {
// this.endpoint = endpoint;
// }
//
// /**
// * Returns the fixed user service endpoint address passed in through the constructor.
// */
// @Override
// public String getUserMicroserviceEndpoint() {
// return endpoint;
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/service/UserDetailServiceImpl.java
// @Service
// public class UserDetailServiceImpl implements UserDetailsService {
//
// private UserMicroserviceEndpointProvider endpointProvider;
//
// /**
// * Constructor which is autowired with an instance of {@link UserMicroserviceEndpointProvider}.
// */
// @Autowired
// public UserDetailServiceImpl(UserMicroserviceEndpointProvider endpointProvider) {
// Preconditions.checkNotNull(endpointProvider);
// this.endpointProvider = endpointProvider;
// }
//
// /**
// * Load a {@link UserDetails} object from the user micro-service for the specified username. Note that this method
// * in addition to a {@link UsernameNotFoundException} throws an unchecked {@link RestClientException} to indicate
// * errors that occurred during the communication process with the remote user micro-service.
// *
// * @param username name of the user to be loaded
// * @return a {@link UserDetails} object
// * @throws UsernameNotFoundException when the given username is not known to the service
// * @throws RestClientException when some error occurred while calling the REST service
// */
// @Override
// public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, RestClientException {
// UserService userService = UserServiceAPI.init(endpointProvider.getUserMicroserviceEndpoint());
// Optional<UserApiData> loadedUser = userService.users().search().findByUsername(username).getData().stream().findFirst();
// if (!loadedUser.isPresent()) {
// throw new UsernameNotFoundException("User " + username + " not found");
// }
// return loadedUser.get().getResource().useProjection(UserProjections.FULL_DATA).read();
// }
// }
//
// Path: service/src/test/java/info/rolandkrueger/userservice/testsupport/AbstractRestControllerTest.java
// public abstract class AbstractRestControllerTest {
//
// private final static String CONTEXT_PATH = "http://localhost:";
//
// private static UserService service;
// private static int port = 8080;
//
// protected static void setPort(int port) {
// AbstractRestControllerTest.port = port;
// }
//
// protected static UserService service() {
// if (service == null) {
// service = UserServiceAPI.init(CONTEXT_PATH + port);
// }
// return service;
// }
//
// @After
// public void tearDown(){
// deleteAllUsers();
// deleteAllAuthorities();
// }
//
// protected static void deleteAllUsers() {
// UsersResource users;
// do {
// users = service().users();
// users.getData().stream().forEach(user -> user.getResource().delete());
// } while (users.hasNext());
// }
//
// protected static void deleteAllAuthorities() {
// AuthoritiesResource authorities;
// do {
// authorities = service().authorities();
// authorities.getData().stream().forEach(authority -> authority.getResource().delete());
// } while (authorities.hasNext());
// }
//
// protected static AuthorityApiData createAuthority(String authority) {
// AuthorityApiData authorityApiData = new AuthorityApiData();
// authorityApiData.setAuthority(authority);
// authorityApiData.setDescription("The " + authority + " role");
// return service().authorities().create(authorityApiData).getBody();
// }
//
// protected static UserApiData registerUser(String username, String password, String email) {
// ResponseEntity<UserRegistrationApiData> registrationResponse =
// service()
// .userRegistrations()
// .create(username, password, email);
//
// service()
// .userRegistrations()
// .findByToken(registrationResponse.getBody().getRegistrationConfirmationToken())
// .confirmRegistration();
//
// return service()
// .users()
// .search()
// .findByUsername(username).getData().stream().findFirst().get();
// }
//
// }
// Path: service/src/test/java/info/rolandkrueger/userservice/service/UserDetailServiceImplTest.java
import info.rolandkrueger.userservice.UserMicroserviceApplication;
import info.rolandkrueger.userservice.api.service.StaticEndpointProvider;
import info.rolandkrueger.userservice.api.service.UserDetailServiceImpl;
import info.rolandkrueger.userservice.testsupport.AbstractRestControllerTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue;
package info.rolandkrueger.userservice.service;
/**
* @author Roland Krüger
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = UserMicroserviceApplication.class)
@WebIntegrationTest(randomPort = true)
public class UserDetailServiceImplTest extends AbstractRestControllerTest {
private UserDetailServiceImpl userDetailService; | private StaticEndpointProvider endpointProvider; |
rolandkrueger/user-microservice | public-api/src/main/java/info/rolandkrueger/userservice/api/UserServiceAPI.java | // Path: public-api/src/main/java/info/rolandkrueger/userservice/api/resources/UserService.java
// public class UserService extends EmptyResource {
//
// private Link authoritiesLink;
// private Link usersLink;
// private Link registrationsLink;
//
// public UserService(Link self) {
// super(self);
// }
//
// /**
// * Initializes the user service: reads all resource links from the resource document obtained from the server.
// */
// public void init() {
// authoritiesLink = getLinkFor(getResponseEntity(), RestApiConstants.AUTHORITIES_RESOURCE);
// usersLink = getLinkFor(getResponseEntity(), RestApiConstants.USERS_RESOURCE);
// registrationsLink = getLinkFor(getResponseEntity(), RestApiConstants.REGISTRATIONS_RESOURCE);
// }
//
// /**
// * Provides the paged {@link AuthoritiesResource} with the given page parameters.
// *
// * @param page the required page number
// * @param size the required page size
// * @return paged resource for authorities
// * @see AbstractPagedResource#getMetadata()
// */
// public AuthoritiesResource authorities(Integer page, Integer size) {
// return authorities().goToPage(page, size);
// }
//
// /**
// * Provides the paged {@link AuthoritiesResource} with default paging parameters applied. These are configured by the user service.
// */
// public AuthoritiesResource authorities() {
// return new AuthoritiesResource(authoritiesLink);
// }
//
// /**
// * Provides the paged {@link UsersResource} with default paging parameters applied. These are configured by the user service.
// */
// public UsersResource users() {
// return new UsersResource(usersLink);
// }
//
// /**
// * Provides the paged {@link UsersResource} with the given page parameters.
// *
// * @param page the required page number
// * @param size the required page size
// * @return paged resource for users
// * @see AbstractPagedResource#getMetadata()
// */
// public UsersResource users(Integer page, Integer size) {
// return users().goToPage(page, size);
// }
//
// /**
// * Provides the {@link UserRegistrationsResource}.
// */
// public UserRegistrationsResource userRegistrations() {
// return new UserRegistrationsResource(registrationsLink);
// }
// }
| import info.rolandkrueger.userservice.api.resources.UserService;
import org.springframework.hateoas.Link; | package info.rolandkrueger.userservice.api;
/**
* Main class for the user service public API. Use this class to get a handle on the service's root resource
* represented by class {@link UserService}. Using this handle, you can navigate through the whole service through
* a fluent API.
*
* @author Roland Krüger
*/
public final class UserServiceAPI {
private UserServiceAPI() {
}
/**
* Initialize the client with the user service's URL. Only this base URL needs to be known to be able to use the
* service. All of the service's resources can be reached through the fluent API provided by the returned
* {@link UserService} object.
* <p/>
* The service's base URL can also be dynamically provided by a
* {@link info.rolandkrueger.userservice.api.service.UserMicroserviceEndpointProvider}.
*
* @param targetURI base URL of the user micro-service
* @return a {@link UserService} object that provides access to the service's resources
* @see info.rolandkrueger.userservice.api.service.UserMicroserviceEndpointProvider
*/ | // Path: public-api/src/main/java/info/rolandkrueger/userservice/api/resources/UserService.java
// public class UserService extends EmptyResource {
//
// private Link authoritiesLink;
// private Link usersLink;
// private Link registrationsLink;
//
// public UserService(Link self) {
// super(self);
// }
//
// /**
// * Initializes the user service: reads all resource links from the resource document obtained from the server.
// */
// public void init() {
// authoritiesLink = getLinkFor(getResponseEntity(), RestApiConstants.AUTHORITIES_RESOURCE);
// usersLink = getLinkFor(getResponseEntity(), RestApiConstants.USERS_RESOURCE);
// registrationsLink = getLinkFor(getResponseEntity(), RestApiConstants.REGISTRATIONS_RESOURCE);
// }
//
// /**
// * Provides the paged {@link AuthoritiesResource} with the given page parameters.
// *
// * @param page the required page number
// * @param size the required page size
// * @return paged resource for authorities
// * @see AbstractPagedResource#getMetadata()
// */
// public AuthoritiesResource authorities(Integer page, Integer size) {
// return authorities().goToPage(page, size);
// }
//
// /**
// * Provides the paged {@link AuthoritiesResource} with default paging parameters applied. These are configured by the user service.
// */
// public AuthoritiesResource authorities() {
// return new AuthoritiesResource(authoritiesLink);
// }
//
// /**
// * Provides the paged {@link UsersResource} with default paging parameters applied. These are configured by the user service.
// */
// public UsersResource users() {
// return new UsersResource(usersLink);
// }
//
// /**
// * Provides the paged {@link UsersResource} with the given page parameters.
// *
// * @param page the required page number
// * @param size the required page size
// * @return paged resource for users
// * @see AbstractPagedResource#getMetadata()
// */
// public UsersResource users(Integer page, Integer size) {
// return users().goToPage(page, size);
// }
//
// /**
// * Provides the {@link UserRegistrationsResource}.
// */
// public UserRegistrationsResource userRegistrations() {
// return new UserRegistrationsResource(registrationsLink);
// }
// }
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/UserServiceAPI.java
import info.rolandkrueger.userservice.api.resources.UserService;
import org.springframework.hateoas.Link;
package info.rolandkrueger.userservice.api;
/**
* Main class for the user service public API. Use this class to get a handle on the service's root resource
* represented by class {@link UserService}. Using this handle, you can navigate through the whole service through
* a fluent API.
*
* @author Roland Krüger
*/
public final class UserServiceAPI {
private UserServiceAPI() {
}
/**
* Initialize the client with the user service's URL. Only this base URL needs to be known to be able to use the
* service. All of the service's resources can be reached through the fluent API provided by the returned
* {@link UserService} object.
* <p/>
* The service's base URL can also be dynamically provided by a
* {@link info.rolandkrueger.userservice.api.service.UserMicroserviceEndpointProvider}.
*
* @param targetURI base URL of the user micro-service
* @return a {@link UserService} object that provides access to the service's resources
* @see info.rolandkrueger.userservice.api.service.UserMicroserviceEndpointProvider
*/ | public static UserService init(String targetURI) { |
rolandkrueger/user-microservice | public-api/src/main/java/info/rolandkrueger/userservice/api/_internal/AbstractPagedResource.java | // Path: public-api/src/main/java/info/rolandkrueger/userservice/api/_internal/model/AbstractBaseApiData.java
// public abstract class AbstractBaseApiData<R extends AbstractResource> {
// private Collection<Link> links;
//
// /**
// * Creates a new resource object for this data type. The method uses the self link to create the resource.
// *
// * @param self link to the resource
// * @return a new resource object that represents this data type on the server side
// * @see #getSelf()
// */
// protected abstract R createNewResource(Link self);
//
// /**
// * Provides a collection of all resource links that could be read from the resource. These links lead to related
// * resources and can be used to create new instances of subclasses of {@link AbstractResource} or
// * {@link info.rolandkrueger.userservice.api._internal.AbstractPagedResource}.
// *
// * @return the collection of resource links
// */
// public final Collection<Link> getLinks() {
// return links;
// }
//
// /**
// * Sets the list of the available links to related resources. Will be called by the JSON unmarshaller.
// *
// * @param links collection of resource links
// */
// public final void setLinks(Collection<Link> links) {
// this.links = links;
// }
//
// /**
// * Provides the link to self.
// *
// * @return the self link
// */
// public final Link getSelf() {
// return links == null ? null : links.iterator().next();
// }
//
// /**
// * Provides the resource object that corresponds to this data type.
// * <p/>
// * Creates a new instance of {@link <R>} on every invocation. Is ignored by the JSON processor when transferring an
// * {@link AbstractBaseApiData} to the server.
// *
// * @return a new instance of a corresponding sub-class of {@link AbstractResource} for this data type.
// */
// @JsonIgnore
// public final R getResource() {
// R resource = createNewResource(getSelf());
// return resource;
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/enums/SortDirection.java
// public enum SortDirection {
// ASC, DESC;
// }
| import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import info.rolandkrueger.userservice.api._internal.model.AbstractBaseApiData;
import info.rolandkrueger.userservice.api.enums.SortDirection;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resources;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;
import java.util.Collection;
import java.util.HashMap; | package info.rolandkrueger.userservice.api._internal;
/**
* A REST collection resource that allows to page through the list of entities. This class adds methods to the general
* {@link AbstractResource} interface supporting paging and sorting the collection resource's data.
* <p/>
* When you create a sub-class for this paged resource then parameter T denotes the data type represented by the resource,
* and parameter R is the subclass itself. E. g., if you have a domain type <code>Person</code> and a corresponding
* client-side data type <code>PersonApiData</code> then a paged <code>Person</code> paged resource could have the following
* signature:
* <p/>
* <code>
* public class PersonsResource extends AbstractPagedResource<PersonApiData, PersonPagedResource> {...}
* </code>
*
* @param <T> type of the data object represented by this collection resource
* @param <R> type of the sub-class inheriting from this resource
* @author Roland Krüger
* @see AbstractBaseApiData
*/
public abstract class AbstractPagedResource<T extends AbstractBaseApiData<?>, R extends AbstractPagedResource> extends AbstractResource<T> {
/**
* Response entity object for this collection resource.
*/
private ResponseEntity<PagedResources<T>> responseEntity;
/**
* {@inheritDoc}
*/
protected AbstractPagedResource(Link templatedSelfLink, Link self) {
super(templatedSelfLink, self);
}
/**
* Factory method for creating a new instance of this resource. Has to be implemented by sub-classes in such a way
* that this implementation returns a new instance of the implementing class for the given self link.
*
* @param self link to self to be used by the created resource object
* @return a new instance of the implementing sub-class
*/
protected abstract R createResourceInstance(Link self);
/**
* Sets the templated link to self for this resource.
*/
protected final void setTemplatedSelfLink(Link templatedSelfLink) {
this.templatedSelfLink = templatedSelfLink;
}
/**
* Configures this resource to return its data as a sorted list for a given page with a given size. This method
* returns a new paged resource object with its self link parameterized to sort by the specified property and to
* return the specified page. This method will only create a parameterized resource object and will not yet call
* the service to fetch the data.
*
* @param page requested page number
* @param size requested page size
* @param sortByProperty sort property, has to be a valid property name of the resource's data type
* @param direction sort direction: ascending or descending
* @return a new paged resource object with its self link parameterized to sort by the specified parameters limited by
* the specified page
*/ | // Path: public-api/src/main/java/info/rolandkrueger/userservice/api/_internal/model/AbstractBaseApiData.java
// public abstract class AbstractBaseApiData<R extends AbstractResource> {
// private Collection<Link> links;
//
// /**
// * Creates a new resource object for this data type. The method uses the self link to create the resource.
// *
// * @param self link to the resource
// * @return a new resource object that represents this data type on the server side
// * @see #getSelf()
// */
// protected abstract R createNewResource(Link self);
//
// /**
// * Provides a collection of all resource links that could be read from the resource. These links lead to related
// * resources and can be used to create new instances of subclasses of {@link AbstractResource} or
// * {@link info.rolandkrueger.userservice.api._internal.AbstractPagedResource}.
// *
// * @return the collection of resource links
// */
// public final Collection<Link> getLinks() {
// return links;
// }
//
// /**
// * Sets the list of the available links to related resources. Will be called by the JSON unmarshaller.
// *
// * @param links collection of resource links
// */
// public final void setLinks(Collection<Link> links) {
// this.links = links;
// }
//
// /**
// * Provides the link to self.
// *
// * @return the self link
// */
// public final Link getSelf() {
// return links == null ? null : links.iterator().next();
// }
//
// /**
// * Provides the resource object that corresponds to this data type.
// * <p/>
// * Creates a new instance of {@link <R>} on every invocation. Is ignored by the JSON processor when transferring an
// * {@link AbstractBaseApiData} to the server.
// *
// * @return a new instance of a corresponding sub-class of {@link AbstractResource} for this data type.
// */
// @JsonIgnore
// public final R getResource() {
// R resource = createNewResource(getSelf());
// return resource;
// }
// }
//
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/enums/SortDirection.java
// public enum SortDirection {
// ASC, DESC;
// }
// Path: public-api/src/main/java/info/rolandkrueger/userservice/api/_internal/AbstractPagedResource.java
import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import info.rolandkrueger.userservice.api._internal.model.AbstractBaseApiData;
import info.rolandkrueger.userservice.api.enums.SortDirection;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.PagedResources;
import org.springframework.hateoas.Resources;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestClientException;
import java.util.Collection;
import java.util.HashMap;
package info.rolandkrueger.userservice.api._internal;
/**
* A REST collection resource that allows to page through the list of entities. This class adds methods to the general
* {@link AbstractResource} interface supporting paging and sorting the collection resource's data.
* <p/>
* When you create a sub-class for this paged resource then parameter T denotes the data type represented by the resource,
* and parameter R is the subclass itself. E. g., if you have a domain type <code>Person</code> and a corresponding
* client-side data type <code>PersonApiData</code> then a paged <code>Person</code> paged resource could have the following
* signature:
* <p/>
* <code>
* public class PersonsResource extends AbstractPagedResource<PersonApiData, PersonPagedResource> {...}
* </code>
*
* @param <T> type of the data object represented by this collection resource
* @param <R> type of the sub-class inheriting from this resource
* @author Roland Krüger
* @see AbstractBaseApiData
*/
public abstract class AbstractPagedResource<T extends AbstractBaseApiData<?>, R extends AbstractPagedResource> extends AbstractResource<T> {
/**
* Response entity object for this collection resource.
*/
private ResponseEntity<PagedResources<T>> responseEntity;
/**
* {@inheritDoc}
*/
protected AbstractPagedResource(Link templatedSelfLink, Link self) {
super(templatedSelfLink, self);
}
/**
* Factory method for creating a new instance of this resource. Has to be implemented by sub-classes in such a way
* that this implementation returns a new instance of the implementing class for the given self link.
*
* @param self link to self to be used by the created resource object
* @return a new instance of the implementing sub-class
*/
protected abstract R createResourceInstance(Link self);
/**
* Sets the templated link to self for this resource.
*/
protected final void setTemplatedSelfLink(Link templatedSelfLink) {
this.templatedSelfLink = templatedSelfLink;
}
/**
* Configures this resource to return its data as a sorted list for a given page with a given size. This method
* returns a new paged resource object with its self link parameterized to sort by the specified property and to
* return the specified page. This method will only create a parameterized resource object and will not yet call
* the service to fetch the data.
*
* @param page requested page number
* @param size requested page size
* @param sortByProperty sort property, has to be a valid property name of the resource's data type
* @param direction sort direction: ascending or descending
* @return a new paged resource object with its self link parameterized to sort by the specified parameters limited by
* the specified page
*/ | public final R goToPageSorted(Integer page, Integer size, String sortByProperty, SortDirection direction) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.