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 |
|---|---|---|---|---|---|---|
liuyanggithub/Hi | src/com/ly/hi/im/view/MyLetterView.java | // Path: src/com/ly/hi/im/util/PixelUtil.java
// public class PixelUtil {
//
// /**
// * The context.
// */
// private static Context mContext = CustomApplication.getInstance();
//
// /**
// * dpת px.
// *
// * @param value the value
// * @return the int
// */
// public static int dp2px(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().densityDpi;
// return (int) (value * (scale / 160) + 0.5f);
// }
//
// /**
// * dpת px.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int dp2px(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().densityDpi;
// return (int) (value * (scale / 160) + 0.5f);
// }
//
// /**
// * pxתdp.
// *
// * @param value the value
// * @return the int
// */
// public static int px2dp(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().densityDpi;
// return (int) ((value * 160) / scale + 0.5f);
// }
//
// /**
// * pxתdp.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int px2dp(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().densityDpi;
// return (int) ((value * 160) / scale + 0.5f);
// }
//
// /**
// * spתpx.
// *
// * @param value the value
// * @return the int
// */
// public static int sp2px(float value) {
// Resources r;
// if (mContext == null) {
// r = Resources.getSystem();
// } else {
// r = mContext.getResources();
// }
// float spvalue = value * r.getDisplayMetrics().scaledDensity;
// return (int) (spvalue + 0.5f);
// }
//
// /**
// * spתpx.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int sp2px(float value, Context context) {
// Resources r;
// if (context == null) {
// r = Resources.getSystem();
// } else {
// r = context.getResources();
// }
// float spvalue = value * r.getDisplayMetrics().scaledDensity;
// return (int) (spvalue + 0.5f);
// }
//
// /**
// * pxתsp.
// *
// * @param value the value
// * @return the int
// */
// public static int px2sp(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().scaledDensity;
// return (int) (value / scale + 0.5f);
// }
//
// /**
// * pxתsp.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int px2sp(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().scaledDensity;
// return (int) (value / scale + 0.5f);
// }
//
// }
| import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.ly.hi.R;
import com.ly.hi.im.util.PixelUtil; | package com.ly.hi.im.view;
/** ͨѶ¼ÓÒ²à¿ìËÙ¹ö¶¯À¸
* @ClassName: MyLetterView
* @Description: TODO
* @author smile
* @date 2014-6-7 ÏÂÎç1:20:33
*/
public class MyLetterView extends View {
// ´¥Ãþʼþ
private OnTouchingLetterChangedListener onTouchingLetterChangedListener;
// 26¸ö×Öĸ
public static String[] b = { "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z", "#" };
private int choose = -1;// Ñ¡ÖÐ
private Paint paint = new Paint();
private TextView mTextDialog;
public void setTextView(TextView mTextDialog) {
this.mTextDialog = mTextDialog;
}
public MyLetterView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyLetterView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyLetterView(Context context) {
super(context);
}
/**
* ÖØÐ´Õâ¸ö·½·¨
*/
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// »ñÈ¡½¹µã¸Ä±ä±³¾°ÑÕÉ«.
int height = getHeight();// »ñÈ¡¶ÔÓ¦¸ß¶È
int width = getWidth(); // »ñÈ¡¶ÔÓ¦¿í¶È
int singleHeight = height / b.length;// »ñȡÿһ¸ö×ÖĸµÄ¸ß¶È
for (int i = 0; i < b.length; i++) {
paint.setColor(getResources().getColor(R.color.color_bottom_text_normal));
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setAntiAlias(true); | // Path: src/com/ly/hi/im/util/PixelUtil.java
// public class PixelUtil {
//
// /**
// * The context.
// */
// private static Context mContext = CustomApplication.getInstance();
//
// /**
// * dpת px.
// *
// * @param value the value
// * @return the int
// */
// public static int dp2px(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().densityDpi;
// return (int) (value * (scale / 160) + 0.5f);
// }
//
// /**
// * dpת px.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int dp2px(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().densityDpi;
// return (int) (value * (scale / 160) + 0.5f);
// }
//
// /**
// * pxתdp.
// *
// * @param value the value
// * @return the int
// */
// public static int px2dp(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().densityDpi;
// return (int) ((value * 160) / scale + 0.5f);
// }
//
// /**
// * pxתdp.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int px2dp(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().densityDpi;
// return (int) ((value * 160) / scale + 0.5f);
// }
//
// /**
// * spתpx.
// *
// * @param value the value
// * @return the int
// */
// public static int sp2px(float value) {
// Resources r;
// if (mContext == null) {
// r = Resources.getSystem();
// } else {
// r = mContext.getResources();
// }
// float spvalue = value * r.getDisplayMetrics().scaledDensity;
// return (int) (spvalue + 0.5f);
// }
//
// /**
// * spתpx.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int sp2px(float value, Context context) {
// Resources r;
// if (context == null) {
// r = Resources.getSystem();
// } else {
// r = context.getResources();
// }
// float spvalue = value * r.getDisplayMetrics().scaledDensity;
// return (int) (spvalue + 0.5f);
// }
//
// /**
// * pxתsp.
// *
// * @param value the value
// * @return the int
// */
// public static int px2sp(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().scaledDensity;
// return (int) (value / scale + 0.5f);
// }
//
// /**
// * pxתsp.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int px2sp(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().scaledDensity;
// return (int) (value / scale + 0.5f);
// }
//
// }
// Path: src/com/ly/hi/im/view/MyLetterView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import com.ly.hi.R;
import com.ly.hi.im.util.PixelUtil;
package com.ly.hi.im.view;
/** ͨѶ¼ÓÒ²à¿ìËÙ¹ö¶¯À¸
* @ClassName: MyLetterView
* @Description: TODO
* @author smile
* @date 2014-6-7 ÏÂÎç1:20:33
*/
public class MyLetterView extends View {
// ´¥Ãþʼþ
private OnTouchingLetterChangedListener onTouchingLetterChangedListener;
// 26¸ö×Öĸ
public static String[] b = { "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z", "#" };
private int choose = -1;// Ñ¡ÖÐ
private Paint paint = new Paint();
private TextView mTextDialog;
public void setTextView(TextView mTextDialog) {
this.mTextDialog = mTextDialog;
}
public MyLetterView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyLetterView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyLetterView(Context context) {
super(context);
}
/**
* ÖØÐ´Õâ¸ö·½·¨
*/
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// »ñÈ¡½¹µã¸Ä±ä±³¾°ÑÕÉ«.
int height = getHeight();// »ñÈ¡¶ÔÓ¦¸ß¶È
int width = getWidth(); // »ñÈ¡¶ÔÓ¦¿í¶È
int singleHeight = height / b.length;// »ñȡÿһ¸ö×ÖĸµÄ¸ß¶È
for (int i = 0; i < b.length; i++) {
paint.setColor(getResources().getColor(R.color.color_bottom_text_normal));
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setAntiAlias(true); | paint.setTextSize(PixelUtil.sp2px(12)); |
liuyanggithub/Hi | src/com/ly/hi/im/ui/LocationActivity.java | // Path: src/com/ly/hi/im/view/HeaderLayout.java
// public interface onRightImageButtonClickListener {
// void onClick();
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import cn.bmob.im.util.BmobLog;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.ly.hi.R;
import com.ly.hi.im.view.HeaderLayout.onRightImageButtonClickListener; | GeoCoder mSearch = null; // ËÑË÷Ä£¿é£¬ÒòΪ°Ù¶È¶¨Î»sdkÄܹ»µÃµ½¾Î³¶È£¬µ«ÊÇÈ´ÎÞ·¨µÃµ½¾ßÌåµÄÏêϸµØÖ·£¬Òò´ËÐèÒª²ÉÈ¡·´±àÂ뷽ʽȥËÑË÷´Ë¾Î³¶È´ú±íµÄµØÖ·
static BDLocation lastLocation = null;
BitmapDescriptor bdgeo = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
initBaiduMap();
}
private void initBaiduMap() {
// µØÍ¼³õʼ»¯
mMapView = (MapView) findViewById(R.id.bmapView);
mBaiduMap = mMapView.getMap();
//ÉèÖÃËõ·Å¼¶±ð
mBaiduMap.setMaxAndMinZoomLevel(18, 13);
// ×¢²á SDK ¹ã²¥¼àÌýÕß
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
mReceiver = new BaiduReceiver();
registerReceiver(mReceiver, iFilter);
Intent intent = getIntent();
String type = intent.getStringExtra("type");
if (type.equals("select")) {// Ñ¡Ôñ·¢ËÍλÖÃ
initTopBarForBoth("λÖÃ", R.drawable.btn_login_selector, "·¢ËÍ", | // Path: src/com/ly/hi/im/view/HeaderLayout.java
// public interface onRightImageButtonClickListener {
// void onClick();
// }
// Path: src/com/ly/hi/im/ui/LocationActivity.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import cn.bmob.im.util.BmobLog;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.ly.hi.R;
import com.ly.hi.im.view.HeaderLayout.onRightImageButtonClickListener;
GeoCoder mSearch = null; // ËÑË÷Ä£¿é£¬ÒòΪ°Ù¶È¶¨Î»sdkÄܹ»µÃµ½¾Î³¶È£¬µ«ÊÇÈ´ÎÞ·¨µÃµ½¾ßÌåµÄÏêϸµØÖ·£¬Òò´ËÐèÒª²ÉÈ¡·´±àÂ뷽ʽȥËÑË÷´Ë¾Î³¶È´ú±íµÄµØÖ·
static BDLocation lastLocation = null;
BitmapDescriptor bdgeo = BitmapDescriptorFactory.fromResource(R.drawable.icon_geo);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
initBaiduMap();
}
private void initBaiduMap() {
// µØÍ¼³õʼ»¯
mMapView = (MapView) findViewById(R.id.bmapView);
mBaiduMap = mMapView.getMap();
//ÉèÖÃËõ·Å¼¶±ð
mBaiduMap.setMaxAndMinZoomLevel(18, 13);
// ×¢²á SDK ¹ã²¥¼àÌýÕß
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
mReceiver = new BaiduReceiver();
registerReceiver(mReceiver, iFilter);
Intent intent = getIntent();
String type = intent.getStringExtra("type");
if (type.equals("select")) {// Ñ¡Ôñ·¢ËÍλÖÃ
initTopBarForBoth("λÖÃ", R.drawable.btn_login_selector, "·¢ËÍ", | new onRightImageButtonClickListener() { |
liuyanggithub/Hi | src/com/ly/hi/im/adapter/base/BaseArrayListAdapter.java | // Path: src/com/ly/hi/im/im/bean/FaceText.java
// public class FaceText {
// public String text;
//
// public FaceText(String text) {
// super();
// this.text = text;
// }
//
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.ly.hi.im.im.bean.FaceText; | package com.ly.hi.im.adapter.base;
public class BaseArrayListAdapter extends BaseAdapter {
protected Context mContext;
protected LayoutInflater mInflater; | // Path: src/com/ly/hi/im/im/bean/FaceText.java
// public class FaceText {
// public String text;
//
// public FaceText(String text) {
// super();
// this.text = text;
// }
//
// }
// Path: src/com/ly/hi/im/adapter/base/BaseArrayListAdapter.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.ly.hi.im.im.bean.FaceText;
package com.ly.hi.im.adapter.base;
public class BaseArrayListAdapter extends BaseAdapter {
protected Context mContext;
protected LayoutInflater mInflater; | protected List<FaceText> mDatas = new ArrayList<FaceText>(); |
liuyanggithub/Hi | src/com/ly/hi/lbs/http/params/BaseRequestParams.java | // Path: src/com/ly/hi/lbs/common/BizInterface.java
// public interface BizInterface {
// String BAIDU_LBS_GEOTABLE_ID = "98950";
// String BAIDU_LBS_GEOTABLE_TYPE = "1";
// String BAIDU_LBS_AK = "ouKiQX83oFa3GevQH58hBRWY";
//
//
// String CREATE_GEOTABLE = "http://api.map.baidu.com/geodata/v3/geotable/create";
//
// /**
// * ´´½¨×ø±êµã
// */
// String CREATE_POI = "http://api.map.baidu.com/geodata/v3/poi/create";
//
// /**
// * ¸üÐÂ×ø±êµã
// */
// String UPDATE_POI = "http://api.map.baidu.com/geodata/v3/poi/update";
// /**
// * ɾ³ý×ø±êµã
// */
// String DELETE_POI = "http://api.map.baidu.com/geodata/v3/poi/delete";
// /**
// * ²éѯ±íÏêϸÊý¾Ý
// */
// String DETAIL_GEOTABLE = new StringBuffer("http://api.map.baidu.com/geodata/v3/poi/list?geotable_id="
// ).append(BAIDU_LBS_GEOTABLE_ID).append("&ak=").append(BAIDU_LBS_AK).append("&title=").toString();
//
// }
| import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import com.ly.hi.lbs.common.BizInterface; | package com.ly.hi.lbs.http.params;
/**
* ÇëÇóµÄ»ù´¡²ÎÊý
*/
public class BaseRequestParams {
//½Ó¿Ú°æ±¾ºÅ
protected String ak; //ÃÜÔ¿
public BaseRequestParams() { | // Path: src/com/ly/hi/lbs/common/BizInterface.java
// public interface BizInterface {
// String BAIDU_LBS_GEOTABLE_ID = "98950";
// String BAIDU_LBS_GEOTABLE_TYPE = "1";
// String BAIDU_LBS_AK = "ouKiQX83oFa3GevQH58hBRWY";
//
//
// String CREATE_GEOTABLE = "http://api.map.baidu.com/geodata/v3/geotable/create";
//
// /**
// * ´´½¨×ø±êµã
// */
// String CREATE_POI = "http://api.map.baidu.com/geodata/v3/poi/create";
//
// /**
// * ¸üÐÂ×ø±êµã
// */
// String UPDATE_POI = "http://api.map.baidu.com/geodata/v3/poi/update";
// /**
// * ɾ³ý×ø±êµã
// */
// String DELETE_POI = "http://api.map.baidu.com/geodata/v3/poi/delete";
// /**
// * ²éѯ±íÏêϸÊý¾Ý
// */
// String DETAIL_GEOTABLE = new StringBuffer("http://api.map.baidu.com/geodata/v3/poi/list?geotable_id="
// ).append(BAIDU_LBS_GEOTABLE_ID).append("&ak=").append(BAIDU_LBS_AK).append("&title=").toString();
//
// }
// Path: src/com/ly/hi/lbs/http/params/BaseRequestParams.java
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import com.ly.hi.lbs.common.BizInterface;
package com.ly.hi.lbs.http.params;
/**
* ÇëÇóµÄ»ù´¡²ÎÊý
*/
public class BaseRequestParams {
//½Ó¿Ú°æ±¾ºÅ
protected String ak; //ÃÜÔ¿
public BaseRequestParams() { | this.ak = BizInterface.BAIDU_LBS_AK; |
liuyanggithub/Hi | src/com/ly/hi/im/ui/UpdateInfoActivity.java | // Path: src/com/ly/hi/im/im/bean/User.java
// public class User extends BmobChatUser {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * ·¢²¼µÄ²©¿ÍÁбí
// */
// private BmobRelation blogs;
//
// /**
// * //ÏÔʾÊý¾ÝÆ´ÒôµÄÊ××Öĸ
// */
// private String sortLetters;
//
// /**
// * //ÐÔ±ð-true-ÄÐ
// */
// private Boolean sex;
//
// private Blog blog;
//
// /**
// * µØÀí×ø±ê
// */
// private BmobGeoPoint location;//
//
// private Integer hight;
//
//
// public Blog getBlog() {
// return blog;
// }
// public void setBlog(Blog blog) {
// this.blog = blog;
// }
// public Integer getHight() {
// return hight;
// }
// public void setHight(Integer hight) {
// this.hight = hight;
// }
// public BmobRelation getBlogs() {
// return blogs;
// }
// public void setBlogs(BmobRelation blogs) {
// this.blogs = blogs;
// }
// public BmobGeoPoint getLocation() {
// return location;
// }
// public void setLocation(BmobGeoPoint location) {
// this.location = location;
// }
// public Boolean getSex() {
// return sex;
// }
// public void setSex(Boolean sex) {
// this.sex = sex;
// }
// public String getSortLetters() {
// return sortLetters;
// }
// public void setSortLetters(String sortLetters) {
// this.sortLetters = sortLetters;
// }
//
// }
//
// Path: src/com/ly/hi/im/view/HeaderLayout.java
// public interface onRightImageButtonClickListener {
// void onClick();
// }
| import android.os.Bundle;
import android.widget.EditText;
import cn.bmob.v3.listener.UpdateListener;
import com.ly.hi.R;
import com.ly.hi.im.im.bean.User;
import com.ly.hi.im.view.HeaderLayout.onRightImageButtonClickListener; | package com.ly.hi.im.ui;
/**
* ÉèÖÃêdzƺÍÐÔ±ð
*
* @ClassName: SetNickAndSexActivity
* @Description: TODO
* @author liuy
*/
public class UpdateInfoActivity extends ActivityBase {
EditText edit_nick;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_updateinfo);
initView();
}
private void initView() {
initTopBarForBoth("ÐÞ¸ÄêdzÆ", R.drawable.base_action_bar_true_bg_selector, | // Path: src/com/ly/hi/im/im/bean/User.java
// public class User extends BmobChatUser {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * ·¢²¼µÄ²©¿ÍÁбí
// */
// private BmobRelation blogs;
//
// /**
// * //ÏÔʾÊý¾ÝÆ´ÒôµÄÊ××Öĸ
// */
// private String sortLetters;
//
// /**
// * //ÐÔ±ð-true-ÄÐ
// */
// private Boolean sex;
//
// private Blog blog;
//
// /**
// * µØÀí×ø±ê
// */
// private BmobGeoPoint location;//
//
// private Integer hight;
//
//
// public Blog getBlog() {
// return blog;
// }
// public void setBlog(Blog blog) {
// this.blog = blog;
// }
// public Integer getHight() {
// return hight;
// }
// public void setHight(Integer hight) {
// this.hight = hight;
// }
// public BmobRelation getBlogs() {
// return blogs;
// }
// public void setBlogs(BmobRelation blogs) {
// this.blogs = blogs;
// }
// public BmobGeoPoint getLocation() {
// return location;
// }
// public void setLocation(BmobGeoPoint location) {
// this.location = location;
// }
// public Boolean getSex() {
// return sex;
// }
// public void setSex(Boolean sex) {
// this.sex = sex;
// }
// public String getSortLetters() {
// return sortLetters;
// }
// public void setSortLetters(String sortLetters) {
// this.sortLetters = sortLetters;
// }
//
// }
//
// Path: src/com/ly/hi/im/view/HeaderLayout.java
// public interface onRightImageButtonClickListener {
// void onClick();
// }
// Path: src/com/ly/hi/im/ui/UpdateInfoActivity.java
import android.os.Bundle;
import android.widget.EditText;
import cn.bmob.v3.listener.UpdateListener;
import com.ly.hi.R;
import com.ly.hi.im.im.bean.User;
import com.ly.hi.im.view.HeaderLayout.onRightImageButtonClickListener;
package com.ly.hi.im.ui;
/**
* ÉèÖÃêdzƺÍÐÔ±ð
*
* @ClassName: SetNickAndSexActivity
* @Description: TODO
* @author liuy
*/
public class UpdateInfoActivity extends ActivityBase {
EditText edit_nick;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_updateinfo);
initView();
}
private void initView() {
initTopBarForBoth("ÐÞ¸ÄêdzÆ", R.drawable.base_action_bar_true_bg_selector, | new onRightImageButtonClickListener() { |
liuyanggithub/Hi | src/com/ly/hi/im/ui/UpdateInfoActivity.java | // Path: src/com/ly/hi/im/im/bean/User.java
// public class User extends BmobChatUser {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * ·¢²¼µÄ²©¿ÍÁбí
// */
// private BmobRelation blogs;
//
// /**
// * //ÏÔʾÊý¾ÝÆ´ÒôµÄÊ××Öĸ
// */
// private String sortLetters;
//
// /**
// * //ÐÔ±ð-true-ÄÐ
// */
// private Boolean sex;
//
// private Blog blog;
//
// /**
// * µØÀí×ø±ê
// */
// private BmobGeoPoint location;//
//
// private Integer hight;
//
//
// public Blog getBlog() {
// return blog;
// }
// public void setBlog(Blog blog) {
// this.blog = blog;
// }
// public Integer getHight() {
// return hight;
// }
// public void setHight(Integer hight) {
// this.hight = hight;
// }
// public BmobRelation getBlogs() {
// return blogs;
// }
// public void setBlogs(BmobRelation blogs) {
// this.blogs = blogs;
// }
// public BmobGeoPoint getLocation() {
// return location;
// }
// public void setLocation(BmobGeoPoint location) {
// this.location = location;
// }
// public Boolean getSex() {
// return sex;
// }
// public void setSex(Boolean sex) {
// this.sex = sex;
// }
// public String getSortLetters() {
// return sortLetters;
// }
// public void setSortLetters(String sortLetters) {
// this.sortLetters = sortLetters;
// }
//
// }
//
// Path: src/com/ly/hi/im/view/HeaderLayout.java
// public interface onRightImageButtonClickListener {
// void onClick();
// }
| import android.os.Bundle;
import android.widget.EditText;
import cn.bmob.v3.listener.UpdateListener;
import com.ly.hi.R;
import com.ly.hi.im.im.bean.User;
import com.ly.hi.im.view.HeaderLayout.onRightImageButtonClickListener; | package com.ly.hi.im.ui;
/**
* ÉèÖÃêdzƺÍÐÔ±ð
*
* @ClassName: SetNickAndSexActivity
* @Description: TODO
* @author liuy
*/
public class UpdateInfoActivity extends ActivityBase {
EditText edit_nick;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_updateinfo);
initView();
}
private void initView() {
initTopBarForBoth("ÐÞ¸ÄêdzÆ", R.drawable.base_action_bar_true_bg_selector,
new onRightImageButtonClickListener() {
@Override
public void onClick() {
// TODO Auto-generated method stub
String nick = edit_nick.getText().toString();
if (nick.equals("")) {
ShowToast("ÇëÌîдêdzÆ!");
return;
}
updateInfo(nick);
}
});
edit_nick = (EditText) findViewById(R.id.edit_nick);
}
/** ÐÞ¸Ä×ÊÁÏ
* updateInfo
* @Title: updateInfo
* @return void
* @throws
*/
private void updateInfo(String nick) { | // Path: src/com/ly/hi/im/im/bean/User.java
// public class User extends BmobChatUser {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// /**
// * ·¢²¼µÄ²©¿ÍÁбí
// */
// private BmobRelation blogs;
//
// /**
// * //ÏÔʾÊý¾ÝÆ´ÒôµÄÊ××Öĸ
// */
// private String sortLetters;
//
// /**
// * //ÐÔ±ð-true-ÄÐ
// */
// private Boolean sex;
//
// private Blog blog;
//
// /**
// * µØÀí×ø±ê
// */
// private BmobGeoPoint location;//
//
// private Integer hight;
//
//
// public Blog getBlog() {
// return blog;
// }
// public void setBlog(Blog blog) {
// this.blog = blog;
// }
// public Integer getHight() {
// return hight;
// }
// public void setHight(Integer hight) {
// this.hight = hight;
// }
// public BmobRelation getBlogs() {
// return blogs;
// }
// public void setBlogs(BmobRelation blogs) {
// this.blogs = blogs;
// }
// public BmobGeoPoint getLocation() {
// return location;
// }
// public void setLocation(BmobGeoPoint location) {
// this.location = location;
// }
// public Boolean getSex() {
// return sex;
// }
// public void setSex(Boolean sex) {
// this.sex = sex;
// }
// public String getSortLetters() {
// return sortLetters;
// }
// public void setSortLetters(String sortLetters) {
// this.sortLetters = sortLetters;
// }
//
// }
//
// Path: src/com/ly/hi/im/view/HeaderLayout.java
// public interface onRightImageButtonClickListener {
// void onClick();
// }
// Path: src/com/ly/hi/im/ui/UpdateInfoActivity.java
import android.os.Bundle;
import android.widget.EditText;
import cn.bmob.v3.listener.UpdateListener;
import com.ly.hi.R;
import com.ly.hi.im.im.bean.User;
import com.ly.hi.im.view.HeaderLayout.onRightImageButtonClickListener;
package com.ly.hi.im.ui;
/**
* ÉèÖÃêdzƺÍÐÔ±ð
*
* @ClassName: SetNickAndSexActivity
* @Description: TODO
* @author liuy
*/
public class UpdateInfoActivity extends ActivityBase {
EditText edit_nick;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_updateinfo);
initView();
}
private void initView() {
initTopBarForBoth("ÐÞ¸ÄêdzÆ", R.drawable.base_action_bar_true_bg_selector,
new onRightImageButtonClickListener() {
@Override
public void onClick() {
// TODO Auto-generated method stub
String nick = edit_nick.getText().toString();
if (nick.equals("")) {
ShowToast("ÇëÌîдêdzÆ!");
return;
}
updateInfo(nick);
}
});
edit_nick = (EditText) findViewById(R.id.edit_nick);
}
/** ÐÞ¸Ä×ÊÁÏ
* updateInfo
* @Title: updateInfo
* @return void
* @throws
*/
private void updateInfo(String nick) { | final User user = userManager.getCurrentUser(User.class); |
liuyanggithub/Hi | src/com/android/volley/toolbox/NetworkImageView.java | // Path: src/com/android/volley/toolbox/ImageLoader.java
// public class ImageContainer {
// /**
// * The most relevant bitmap for the container. If the image was in cache, the
// * Holder to use for the final bitmap (the one that pairs to the requested URL).
// */
// private Bitmap mBitmap;
//
// private final ImageListener mListener;
//
// /** The cache key that was associated with the request */
// private final String mCacheKey;
//
// /** The request URL that was specified */
// private final String mRequestUrl;
//
// /**
// * Constructs a BitmapContainer object.
// * @param bitmap The final bitmap (if it exists).
// * @param requestUrl The requested URL for this container.
// * @param cacheKey The cache key that identifies the requested URL for this container.
// */
// public ImageContainer(Bitmap bitmap, String requestUrl,
// String cacheKey, ImageListener listener) {
// mBitmap = bitmap;
// mRequestUrl = requestUrl;
// mCacheKey = cacheKey;
// mListener = listener;
// }
//
// /**
// * Releases interest in the in-flight request (and cancels it if no one else is listening).
// */
// public void cancelRequest() {
// if (mListener == null) {
// return;
// }
//
// BatchedImageRequest request = mInFlightRequests.get(mCacheKey);
// if (request != null) {
// boolean canceled = request.removeContainerAndCancelIfNecessary(this);
// if (canceled) {
// mInFlightRequests.remove(mCacheKey);
// }
// } else {
// // check to see if it is already batched for delivery.
// request = mBatchedResponses.get(mCacheKey);
// if (request != null) {
// request.removeContainerAndCancelIfNecessary(this);
// if (request.mContainers.size() == 0) {
// mBatchedResponses.remove(mCacheKey);
// }
// }
// }
// }
//
// /**
// * Returns the bitmap associated with the request URL if it has been loaded, null otherwise.
// */
// public Bitmap getBitmap() {
// return mBitmap;
// }
//
// /**
// * Returns the requested URL for this container.
// */
// public String getRequestUrl() {
// return mRequestUrl;
// }
// }
//
// Path: src/com/android/volley/toolbox/ImageLoader.java
// public interface ImageListener extends ErrorListener {
// /**
// * Listens for non-error changes to the loading of the image request.
// *
// * @param response Holds all information pertaining to the request, as well
// * as the bitmap (if it is loaded).
// * @param isImmediate True if this was called during ImageLoader.get() variants.
// * This can be used to differentiate between a cached image loading and a network
// * image loading in order to, for example, run an animation to fade in network loaded
// * images.
// */
// public void onResponse(ImageContainer response, boolean isImmediate);
// }
| import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener; | /**
* Copyright (C) 2013 The Android Open Source Project
*
* 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.android.volley.toolbox;
/**
* Handles fetching an image from a URL as well as the life-cycle of the
* associated request.
*/
public class NetworkImageView extends ImageView {
/** The URL of the network image to load */
private String mUrl;
/**
* Resource ID of the image to be used as a placeholder until the network image is loaded.
*/
private int mDefaultImageId;
/**
* Resource ID of the image to be used if the network response fails.
*/
private int mErrorImageId;
/** Local copy of the ImageLoader. */
private ImageLoader mImageLoader;
/** Current ImageContainer. (either in-flight or finished) */ | // Path: src/com/android/volley/toolbox/ImageLoader.java
// public class ImageContainer {
// /**
// * The most relevant bitmap for the container. If the image was in cache, the
// * Holder to use for the final bitmap (the one that pairs to the requested URL).
// */
// private Bitmap mBitmap;
//
// private final ImageListener mListener;
//
// /** The cache key that was associated with the request */
// private final String mCacheKey;
//
// /** The request URL that was specified */
// private final String mRequestUrl;
//
// /**
// * Constructs a BitmapContainer object.
// * @param bitmap The final bitmap (if it exists).
// * @param requestUrl The requested URL for this container.
// * @param cacheKey The cache key that identifies the requested URL for this container.
// */
// public ImageContainer(Bitmap bitmap, String requestUrl,
// String cacheKey, ImageListener listener) {
// mBitmap = bitmap;
// mRequestUrl = requestUrl;
// mCacheKey = cacheKey;
// mListener = listener;
// }
//
// /**
// * Releases interest in the in-flight request (and cancels it if no one else is listening).
// */
// public void cancelRequest() {
// if (mListener == null) {
// return;
// }
//
// BatchedImageRequest request = mInFlightRequests.get(mCacheKey);
// if (request != null) {
// boolean canceled = request.removeContainerAndCancelIfNecessary(this);
// if (canceled) {
// mInFlightRequests.remove(mCacheKey);
// }
// } else {
// // check to see if it is already batched for delivery.
// request = mBatchedResponses.get(mCacheKey);
// if (request != null) {
// request.removeContainerAndCancelIfNecessary(this);
// if (request.mContainers.size() == 0) {
// mBatchedResponses.remove(mCacheKey);
// }
// }
// }
// }
//
// /**
// * Returns the bitmap associated with the request URL if it has been loaded, null otherwise.
// */
// public Bitmap getBitmap() {
// return mBitmap;
// }
//
// /**
// * Returns the requested URL for this container.
// */
// public String getRequestUrl() {
// return mRequestUrl;
// }
// }
//
// Path: src/com/android/volley/toolbox/ImageLoader.java
// public interface ImageListener extends ErrorListener {
// /**
// * Listens for non-error changes to the loading of the image request.
// *
// * @param response Holds all information pertaining to the request, as well
// * as the bitmap (if it is loaded).
// * @param isImmediate True if this was called during ImageLoader.get() variants.
// * This can be used to differentiate between a cached image loading and a network
// * image loading in order to, for example, run an animation to fade in network loaded
// * images.
// */
// public void onResponse(ImageContainer response, boolean isImmediate);
// }
// Path: src/com/android/volley/toolbox/NetworkImageView.java
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
/**
* Copyright (C) 2013 The Android Open Source Project
*
* 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.android.volley.toolbox;
/**
* Handles fetching an image from a URL as well as the life-cycle of the
* associated request.
*/
public class NetworkImageView extends ImageView {
/** The URL of the network image to load */
private String mUrl;
/**
* Resource ID of the image to be used as a placeholder until the network image is loaded.
*/
private int mDefaultImageId;
/**
* Resource ID of the image to be used if the network response fails.
*/
private int mErrorImageId;
/** Local copy of the ImageLoader. */
private ImageLoader mImageLoader;
/** Current ImageContainer. (either in-flight or finished) */ | private ImageContainer mImageContainer; |
liuyanggithub/Hi | src/com/android/volley/toolbox/NetworkImageView.java | // Path: src/com/android/volley/toolbox/ImageLoader.java
// public class ImageContainer {
// /**
// * The most relevant bitmap for the container. If the image was in cache, the
// * Holder to use for the final bitmap (the one that pairs to the requested URL).
// */
// private Bitmap mBitmap;
//
// private final ImageListener mListener;
//
// /** The cache key that was associated with the request */
// private final String mCacheKey;
//
// /** The request URL that was specified */
// private final String mRequestUrl;
//
// /**
// * Constructs a BitmapContainer object.
// * @param bitmap The final bitmap (if it exists).
// * @param requestUrl The requested URL for this container.
// * @param cacheKey The cache key that identifies the requested URL for this container.
// */
// public ImageContainer(Bitmap bitmap, String requestUrl,
// String cacheKey, ImageListener listener) {
// mBitmap = bitmap;
// mRequestUrl = requestUrl;
// mCacheKey = cacheKey;
// mListener = listener;
// }
//
// /**
// * Releases interest in the in-flight request (and cancels it if no one else is listening).
// */
// public void cancelRequest() {
// if (mListener == null) {
// return;
// }
//
// BatchedImageRequest request = mInFlightRequests.get(mCacheKey);
// if (request != null) {
// boolean canceled = request.removeContainerAndCancelIfNecessary(this);
// if (canceled) {
// mInFlightRequests.remove(mCacheKey);
// }
// } else {
// // check to see if it is already batched for delivery.
// request = mBatchedResponses.get(mCacheKey);
// if (request != null) {
// request.removeContainerAndCancelIfNecessary(this);
// if (request.mContainers.size() == 0) {
// mBatchedResponses.remove(mCacheKey);
// }
// }
// }
// }
//
// /**
// * Returns the bitmap associated with the request URL if it has been loaded, null otherwise.
// */
// public Bitmap getBitmap() {
// return mBitmap;
// }
//
// /**
// * Returns the requested URL for this container.
// */
// public String getRequestUrl() {
// return mRequestUrl;
// }
// }
//
// Path: src/com/android/volley/toolbox/ImageLoader.java
// public interface ImageListener extends ErrorListener {
// /**
// * Listens for non-error changes to the loading of the image request.
// *
// * @param response Holds all information pertaining to the request, as well
// * as the bitmap (if it is loaded).
// * @param isImmediate True if this was called during ImageLoader.get() variants.
// * This can be used to differentiate between a cached image loading and a network
// * image loading in order to, for example, run an animation to fade in network loaded
// * images.
// */
// public void onResponse(ImageContainer response, boolean isImmediate);
// }
| import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener; | // if the URL to be loaded in this view is empty, cancel any old requests and clear the
// currently loaded image.
if (TextUtils.isEmpty(mUrl)) {
if (mImageContainer != null) {
mImageContainer.cancelRequest();
mImageContainer = null;
}
setDefaultImageOrNull();
return;
}
// if there was an old request in this view, check if it needs to be canceled.
if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {
if (mImageContainer.getRequestUrl().equals(mUrl)) {
// if the request is from the same URL, return.
return;
} else {
// if there is a pre-existing request, cancel it if it's fetching a different URL.
mImageContainer.cancelRequest();
setDefaultImageOrNull();
}
}
// Calculate the max image width / height to use while ignoring WRAP_CONTENT dimens.
int maxWidth = wrapWidth ? 0 : width;
int maxHeight = wrapHeight ? 0 : height;
// The pre-existing content of this view didn't match the current URL. Load the new image
// from the network.
ImageContainer newContainer = mImageLoader.get(mUrl, | // Path: src/com/android/volley/toolbox/ImageLoader.java
// public class ImageContainer {
// /**
// * The most relevant bitmap for the container. If the image was in cache, the
// * Holder to use for the final bitmap (the one that pairs to the requested URL).
// */
// private Bitmap mBitmap;
//
// private final ImageListener mListener;
//
// /** The cache key that was associated with the request */
// private final String mCacheKey;
//
// /** The request URL that was specified */
// private final String mRequestUrl;
//
// /**
// * Constructs a BitmapContainer object.
// * @param bitmap The final bitmap (if it exists).
// * @param requestUrl The requested URL for this container.
// * @param cacheKey The cache key that identifies the requested URL for this container.
// */
// public ImageContainer(Bitmap bitmap, String requestUrl,
// String cacheKey, ImageListener listener) {
// mBitmap = bitmap;
// mRequestUrl = requestUrl;
// mCacheKey = cacheKey;
// mListener = listener;
// }
//
// /**
// * Releases interest in the in-flight request (and cancels it if no one else is listening).
// */
// public void cancelRequest() {
// if (mListener == null) {
// return;
// }
//
// BatchedImageRequest request = mInFlightRequests.get(mCacheKey);
// if (request != null) {
// boolean canceled = request.removeContainerAndCancelIfNecessary(this);
// if (canceled) {
// mInFlightRequests.remove(mCacheKey);
// }
// } else {
// // check to see if it is already batched for delivery.
// request = mBatchedResponses.get(mCacheKey);
// if (request != null) {
// request.removeContainerAndCancelIfNecessary(this);
// if (request.mContainers.size() == 0) {
// mBatchedResponses.remove(mCacheKey);
// }
// }
// }
// }
//
// /**
// * Returns the bitmap associated with the request URL if it has been loaded, null otherwise.
// */
// public Bitmap getBitmap() {
// return mBitmap;
// }
//
// /**
// * Returns the requested URL for this container.
// */
// public String getRequestUrl() {
// return mRequestUrl;
// }
// }
//
// Path: src/com/android/volley/toolbox/ImageLoader.java
// public interface ImageListener extends ErrorListener {
// /**
// * Listens for non-error changes to the loading of the image request.
// *
// * @param response Holds all information pertaining to the request, as well
// * as the bitmap (if it is loaded).
// * @param isImmediate True if this was called during ImageLoader.get() variants.
// * This can be used to differentiate between a cached image loading and a network
// * image loading in order to, for example, run an animation to fade in network loaded
// * images.
// */
// public void onResponse(ImageContainer response, boolean isImmediate);
// }
// Path: src/com/android/volley/toolbox/NetworkImageView.java
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
// if the URL to be loaded in this view is empty, cancel any old requests and clear the
// currently loaded image.
if (TextUtils.isEmpty(mUrl)) {
if (mImageContainer != null) {
mImageContainer.cancelRequest();
mImageContainer = null;
}
setDefaultImageOrNull();
return;
}
// if there was an old request in this view, check if it needs to be canceled.
if (mImageContainer != null && mImageContainer.getRequestUrl() != null) {
if (mImageContainer.getRequestUrl().equals(mUrl)) {
// if the request is from the same URL, return.
return;
} else {
// if there is a pre-existing request, cancel it if it's fetching a different URL.
mImageContainer.cancelRequest();
setDefaultImageOrNull();
}
}
// Calculate the max image width / height to use while ignoring WRAP_CONTENT dimens.
int maxWidth = wrapWidth ? 0 : width;
int maxHeight = wrapHeight ? 0 : height;
// The pre-existing content of this view didn't match the current URL. Load the new image
// from the network.
ImageContainer newContainer = mImageLoader.get(mUrl, | new ImageListener() { |
liuyanggithub/Hi | src/com/ly/hi/im/view/HeaderLayout.java | // Path: src/com/ly/hi/im/util/PixelUtil.java
// public class PixelUtil {
//
// /**
// * The context.
// */
// private static Context mContext = CustomApplication.getInstance();
//
// /**
// * dpת px.
// *
// * @param value the value
// * @return the int
// */
// public static int dp2px(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().densityDpi;
// return (int) (value * (scale / 160) + 0.5f);
// }
//
// /**
// * dpת px.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int dp2px(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().densityDpi;
// return (int) (value * (scale / 160) + 0.5f);
// }
//
// /**
// * pxתdp.
// *
// * @param value the value
// * @return the int
// */
// public static int px2dp(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().densityDpi;
// return (int) ((value * 160) / scale + 0.5f);
// }
//
// /**
// * pxתdp.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int px2dp(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().densityDpi;
// return (int) ((value * 160) / scale + 0.5f);
// }
//
// /**
// * spתpx.
// *
// * @param value the value
// * @return the int
// */
// public static int sp2px(float value) {
// Resources r;
// if (mContext == null) {
// r = Resources.getSystem();
// } else {
// r = mContext.getResources();
// }
// float spvalue = value * r.getDisplayMetrics().scaledDensity;
// return (int) (spvalue + 0.5f);
// }
//
// /**
// * spתpx.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int sp2px(float value, Context context) {
// Resources r;
// if (context == null) {
// r = Resources.getSystem();
// } else {
// r = context.getResources();
// }
// float spvalue = value * r.getDisplayMetrics().scaledDensity;
// return (int) (spvalue + 0.5f);
// }
//
// /**
// * pxתsp.
// *
// * @param value the value
// * @return the int
// */
// public static int px2sp(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().scaledDensity;
// return (int) (value / scale + 0.5f);
// }
//
// /**
// * pxתsp.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int px2sp(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().scaledDensity;
// return (int) (value / scale + 0.5f);
// }
//
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ly.hi.R;
import com.ly.hi.im.util.PixelUtil; | return null;
}
/**
* »ñÈ¡ÓÒ±ßÎÄ×Ö
*
* @Title: getRightImageButton
* @Description: TODO
* @param @return
* @return TextView
* @throws
*/
public TextView getRightTextView() {
if (mRightTextView != null) {
return mRightTextView;
}
return null;
}
public void setDefaultTitle(CharSequence title) {
if (title != null) {
mHtvSubTitle.setText(title);
} else {
mHtvSubTitle.setVisibility(View.GONE);
}
}
public void setTitleAndRightButton(CharSequence title, int backid, String text, onRightImageButtonClickListener onRightImageButtonClickListener) {
setDefaultTitle(title);
mLayoutRightContainer.setVisibility(View.VISIBLE);
if (mRightImageButton != null && backid > 0) { | // Path: src/com/ly/hi/im/util/PixelUtil.java
// public class PixelUtil {
//
// /**
// * The context.
// */
// private static Context mContext = CustomApplication.getInstance();
//
// /**
// * dpת px.
// *
// * @param value the value
// * @return the int
// */
// public static int dp2px(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().densityDpi;
// return (int) (value * (scale / 160) + 0.5f);
// }
//
// /**
// * dpת px.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int dp2px(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().densityDpi;
// return (int) (value * (scale / 160) + 0.5f);
// }
//
// /**
// * pxתdp.
// *
// * @param value the value
// * @return the int
// */
// public static int px2dp(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().densityDpi;
// return (int) ((value * 160) / scale + 0.5f);
// }
//
// /**
// * pxתdp.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int px2dp(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().densityDpi;
// return (int) ((value * 160) / scale + 0.5f);
// }
//
// /**
// * spתpx.
// *
// * @param value the value
// * @return the int
// */
// public static int sp2px(float value) {
// Resources r;
// if (mContext == null) {
// r = Resources.getSystem();
// } else {
// r = mContext.getResources();
// }
// float spvalue = value * r.getDisplayMetrics().scaledDensity;
// return (int) (spvalue + 0.5f);
// }
//
// /**
// * spתpx.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int sp2px(float value, Context context) {
// Resources r;
// if (context == null) {
// r = Resources.getSystem();
// } else {
// r = context.getResources();
// }
// float spvalue = value * r.getDisplayMetrics().scaledDensity;
// return (int) (spvalue + 0.5f);
// }
//
// /**
// * pxתsp.
// *
// * @param value the value
// * @return the int
// */
// public static int px2sp(float value) {
// final float scale = mContext.getResources().getDisplayMetrics().scaledDensity;
// return (int) (value / scale + 0.5f);
// }
//
// /**
// * pxתsp.
// *
// * @param value the value
// * @param context the context
// * @return the int
// */
// public static int px2sp(float value, Context context) {
// final float scale = context.getResources().getDisplayMetrics().scaledDensity;
// return (int) (value / scale + 0.5f);
// }
//
// }
// Path: src/com/ly/hi/im/view/HeaderLayout.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ly.hi.R;
import com.ly.hi.im.util.PixelUtil;
return null;
}
/**
* »ñÈ¡ÓÒ±ßÎÄ×Ö
*
* @Title: getRightImageButton
* @Description: TODO
* @param @return
* @return TextView
* @throws
*/
public TextView getRightTextView() {
if (mRightTextView != null) {
return mRightTextView;
}
return null;
}
public void setDefaultTitle(CharSequence title) {
if (title != null) {
mHtvSubTitle.setText(title);
} else {
mHtvSubTitle.setVisibility(View.GONE);
}
}
public void setTitleAndRightButton(CharSequence title, int backid, String text, onRightImageButtonClickListener onRightImageButtonClickListener) {
setDefaultTitle(title);
mLayoutRightContainer.setVisibility(View.VISIBLE);
if (mRightImageButton != null && backid > 0) { | mRightImageButton.setWidth(PixelUtil.dp2px(45)); |
Sinrel/SinrelLauncherEngine-Dev | src/org/sinrel/engine/library/PatchManager.java | // Path: src/org/sinrel/engine/util/VirtualZipModifer.java
// public class VirtualZipModifer {
// private File file;
// private ZipFile zipFile;
// private Map<String, byte[]> virtualEntries;
//
// public VirtualZipModifer(File file) throws ZipException, IOException {
// this.file = file;
// virtualEntries = new HashMap<String, byte[]>();
// }
//
// public File getFile() {
// return file;
// }
//
// public byte[] getBytes(String key) {
// return virtualEntries.get(key);
// }
//
// public Map<String, byte[]> getEntriesMap() {
// synchronized (this) {
// return virtualEntries;
// }
// }
//
// public void putEntry(String key, byte[] value) {
// synchronized (this) {
// virtualEntries.put(key, value);
// }
// }
//
// public void putClass(CtClass clazz) throws IOException, CannotCompileException {
// synchronized (this) {
// virtualEntries.put(clazz.getName().replace('.', '/') + ".class", clazz.toBytecode());
// }
// }
//
// public void write() throws IOException, InterruptedException {
// write(false);
// }
//
// public void write(boolean ignoreMetaInf) throws IOException, InterruptedException {
// synchronized (this) {
// Map<String, byte[]> newEntries = new HashMap<String, byte[]>();
//
// zipFile = new ZipFile(file);
// Enumeration<? extends ZipEntry> numer = zipFile.entries();
// while (numer.hasMoreElements()) {
// ZipEntry entry = numer.nextElement();
// String name = entry.getName();
// if (!(ignoreMetaInf && name.startsWith("META-INF"))) {
// if (!virtualEntries.containsKey(name))
// newEntries.put(name, toByteArray(zipFile.getInputStream(entry)));
// }
// }
// zipFile.close();
//
// Set<Entry<String, byte[]>> entrySet1 = virtualEntries.entrySet();
// for (Entry<String, byte[]> entry : entrySet1) {
// String name = entry.getKey();
// if (!(ignoreMetaInf && name.startsWith("META-INF"))) {
// newEntries.put(name, entry.getValue());
// }
// }
//
// ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
// try {
// Set<Entry<String, byte[]>> entrySet2 = newEntries.entrySet();
// for (Entry<String, byte[]> entry : entrySet2) {
// zos.putNextEntry(new ZipEntry(entry.getKey()));
// zos.write(entry.getValue());
// zos.closeEntry();
// }
// Thread.sleep(0, 1);
// } finally {
// zos.flush();
// zos.close();
// }
//
// virtualEntries.clear();
// }
// }
//
// private byte[] toByteArray(InputStream input) throws IOException {
// ByteArrayOutputStream output = new ByteArrayOutputStream();
//
// byte[] buffer = new byte[1024 * 4];
// int n = 0;
// while (-1 != (n = input.read(buffer)))
// output.write(buffer, 0, n);
// return output.toByteArray();
// }
// }
| import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.NewExpr;
import org.sinrel.engine.util.VirtualZipModifer; | package org.sinrel.engine.library;
public final class PatchManager {
protected static String class_joinserver = "ayh", class_checkserver = "iu";
protected static String methodname_joinserver, methodsign_joinserver;
protected static String methodname_checkserver, methodsign_checkserver;
| // Path: src/org/sinrel/engine/util/VirtualZipModifer.java
// public class VirtualZipModifer {
// private File file;
// private ZipFile zipFile;
// private Map<String, byte[]> virtualEntries;
//
// public VirtualZipModifer(File file) throws ZipException, IOException {
// this.file = file;
// virtualEntries = new HashMap<String, byte[]>();
// }
//
// public File getFile() {
// return file;
// }
//
// public byte[] getBytes(String key) {
// return virtualEntries.get(key);
// }
//
// public Map<String, byte[]> getEntriesMap() {
// synchronized (this) {
// return virtualEntries;
// }
// }
//
// public void putEntry(String key, byte[] value) {
// synchronized (this) {
// virtualEntries.put(key, value);
// }
// }
//
// public void putClass(CtClass clazz) throws IOException, CannotCompileException {
// synchronized (this) {
// virtualEntries.put(clazz.getName().replace('.', '/') + ".class", clazz.toBytecode());
// }
// }
//
// public void write() throws IOException, InterruptedException {
// write(false);
// }
//
// public void write(boolean ignoreMetaInf) throws IOException, InterruptedException {
// synchronized (this) {
// Map<String, byte[]> newEntries = new HashMap<String, byte[]>();
//
// zipFile = new ZipFile(file);
// Enumeration<? extends ZipEntry> numer = zipFile.entries();
// while (numer.hasMoreElements()) {
// ZipEntry entry = numer.nextElement();
// String name = entry.getName();
// if (!(ignoreMetaInf && name.startsWith("META-INF"))) {
// if (!virtualEntries.containsKey(name))
// newEntries.put(name, toByteArray(zipFile.getInputStream(entry)));
// }
// }
// zipFile.close();
//
// Set<Entry<String, byte[]>> entrySet1 = virtualEntries.entrySet();
// for (Entry<String, byte[]> entry : entrySet1) {
// String name = entry.getKey();
// if (!(ignoreMetaInf && name.startsWith("META-INF"))) {
// newEntries.put(name, entry.getValue());
// }
// }
//
// ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
// try {
// Set<Entry<String, byte[]>> entrySet2 = newEntries.entrySet();
// for (Entry<String, byte[]> entry : entrySet2) {
// zos.putNextEntry(new ZipEntry(entry.getKey()));
// zos.write(entry.getValue());
// zos.closeEntry();
// }
// Thread.sleep(0, 1);
// } finally {
// zos.flush();
// zos.close();
// }
//
// virtualEntries.clear();
// }
// }
//
// private byte[] toByteArray(InputStream input) throws IOException {
// ByteArrayOutputStream output = new ByteArrayOutputStream();
//
// byte[] buffer = new byte[1024 * 4];
// int n = 0;
// while (-1 != (n = input.read(buffer)))
// output.write(buffer, 0, n);
// return output.toByteArray();
// }
// }
// Path: src/org/sinrel/engine/library/PatchManager.java
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.expr.ExprEditor;
import javassist.expr.FieldAccess;
import javassist.expr.NewExpr;
import org.sinrel.engine.util.VirtualZipModifer;
package org.sinrel.engine.library;
public final class PatchManager {
protected static String class_joinserver = "ayh", class_checkserver = "iu";
protected static String methodname_joinserver, methodsign_joinserver;
protected static String methodname_checkserver, methodsign_checkserver;
| public static void patchWorkDir(final VirtualZipModifer virtualJar, final ClassPool pool, final String workDir) throws Exception { |
Sinrel/SinrelLauncherEngine-Dev | src/org/sinrel/engine/library/NetManager.java | // Path: src/org/sinrel/engine/Engine.java
// public class Engine {
//
// private EngineSettings settings;
//
// private Intent intent;
// private Config config;
//
// private Downloader downloader;
// private Checker checker;
// private AuthBehavior auth;
// private MinecraftStarter starter;
//
// private boolean debug = false;
//
// public Engine( EngineSettings settings ) {
// try {
// intent = new Intent(this);
// setSettings(settings);
// config = new DefaultConfig(this);
// downloader = new DefaultDownloader();
// checker = new DefaultChecker();
// auth = new DefaultAuthBehavior();
// starter = new MinecraftAppletStarter();
// }catch( Exception e ) {
// FatalError.showErrorWindow(e);
// }
// }
//
// public EngineSettings getSettings() {
// return settings;
// }
//
// public Downloader getDownloader() {
// return downloader;
// }
//
// public Checker getChecker() {
// return checker;
// }
//
// public AuthBehavior getAuth() {
// return auth;
// }
//
// public Intent getIntent(){
// return intent;
// }
//
// public Config getConfig() {
// return config;
// }
//
// public MinecraftStarter getStarter(){
// return starter;
// }
//
// public void setSettings(EngineSettings settings){
// if( settings == null ) throw new NullPointerException();
// this.settings = settings;
// }
//
// public void setDownloader(Downloader downloader) {
// if( downloader == null ) throw new NullPointerException();
// this.downloader = downloader;
// }
//
// public void setChecker( Checker checker ) {
// if( checker == null ) throw new NullPointerException();
// this.checker = checker;
// }
//
// public void setAuth(AuthBehavior auth) {
// if( auth == null ) throw new NullPointerException();
// this.auth = auth;
// }
//
// public void setConfig( Config config ) {
// if( config == null ) throw new NullPointerException();
// this.config = config;
// }
//
// public void setMinecraftStarter( MinecraftStarter starter ){
// if( starter == null ) throw new NullPointerException();
// this.starter = starter;
// }
//
// public void useDebug( boolean debug ) {
// this.debug = debug;
// }
//
// public boolean isDebug(){
// return debug;
// }
//
// }
| import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import org.apache.commons.codec.binary.StringUtils;
import org.sinrel.engine.Engine; | conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
OutputStream wr = conn.getOutputStream();
wr.write(bytes);
wr.flush();
wr.close();
StringBuffer s = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
s.append(line);
}
reader.close();
return s.toString();
}
/**
* @param engine Экземпляр класса {@link Engine}
* @return Возвращает ссылку на engine.php
* @throws MalformedURLException
*/ | // Path: src/org/sinrel/engine/Engine.java
// public class Engine {
//
// private EngineSettings settings;
//
// private Intent intent;
// private Config config;
//
// private Downloader downloader;
// private Checker checker;
// private AuthBehavior auth;
// private MinecraftStarter starter;
//
// private boolean debug = false;
//
// public Engine( EngineSettings settings ) {
// try {
// intent = new Intent(this);
// setSettings(settings);
// config = new DefaultConfig(this);
// downloader = new DefaultDownloader();
// checker = new DefaultChecker();
// auth = new DefaultAuthBehavior();
// starter = new MinecraftAppletStarter();
// }catch( Exception e ) {
// FatalError.showErrorWindow(e);
// }
// }
//
// public EngineSettings getSettings() {
// return settings;
// }
//
// public Downloader getDownloader() {
// return downloader;
// }
//
// public Checker getChecker() {
// return checker;
// }
//
// public AuthBehavior getAuth() {
// return auth;
// }
//
// public Intent getIntent(){
// return intent;
// }
//
// public Config getConfig() {
// return config;
// }
//
// public MinecraftStarter getStarter(){
// return starter;
// }
//
// public void setSettings(EngineSettings settings){
// if( settings == null ) throw new NullPointerException();
// this.settings = settings;
// }
//
// public void setDownloader(Downloader downloader) {
// if( downloader == null ) throw new NullPointerException();
// this.downloader = downloader;
// }
//
// public void setChecker( Checker checker ) {
// if( checker == null ) throw new NullPointerException();
// this.checker = checker;
// }
//
// public void setAuth(AuthBehavior auth) {
// if( auth == null ) throw new NullPointerException();
// this.auth = auth;
// }
//
// public void setConfig( Config config ) {
// if( config == null ) throw new NullPointerException();
// this.config = config;
// }
//
// public void setMinecraftStarter( MinecraftStarter starter ){
// if( starter == null ) throw new NullPointerException();
// this.starter = starter;
// }
//
// public void useDebug( boolean debug ) {
// this.debug = debug;
// }
//
// public boolean isDebug(){
// return debug;
// }
//
// }
// Path: src/org/sinrel/engine/library/NetManager.java
import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.UnknownHostException;
import org.apache.commons.codec.binary.StringUtils;
import org.sinrel.engine.Engine;
conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
OutputStream wr = conn.getOutputStream();
wr.write(bytes);
wr.flush();
wr.close();
StringBuffer s = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
s.append(line);
}
reader.close();
return s.toString();
}
/**
* @param engine Экземпляр класса {@link Engine}
* @return Возвращает ссылку на engine.php
* @throws MalformedURLException
*/ | public static final String getEngineLink( Engine engine ) throws MalformedURLException { |
Sinrel/SinrelLauncherEngine-Dev | src/net/minecraft/Launcher.java | // Path: src/org/sinrel/engine/actions/AuthData.java
// public class AuthData {
// private String session;
// private String login;
// private String token;
// private AuthResult result;
//
// public String getToken() {
// return token;
// }
//
// public String getSession() {
// return session;
// }
//
// public String getLogin() {
// return login;
// }
//
// public AuthResult getResult() {
// return result;
// }
//
// void setToken( String token ) {
// this.token = token;
// }
//
// void setSession( String session ) {
// this.session = session;
// }
//
// void setLogin( String login ) {
// this.login = login;
// }
//
// void setResult( AuthResult result ) {
// this.result = result;
// }
//
// public AuthData() {
// this(null, null, AuthResult.BAD_CONNECTION);
// }
//
// public AuthData( String login, String session, AuthResult result ){
// setLogin(login);
// setSession(session);
// setResult(result);
// }
// }
| import java.applet.Applet;
import java.applet.AppletStub;
import java.awt.BorderLayout;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import org.sinrel.engine.actions.AuthData; | package net.minecraft;
public class Launcher extends Applet implements AppletStub {
private static final long serialVersionUID = 1L;
private Applet applet = null;
public Map<String, String> customParameters = new HashMap<String, String>();
private int context = 0;
private boolean active = false;
private URL[] urls;
private String bin; | // Path: src/org/sinrel/engine/actions/AuthData.java
// public class AuthData {
// private String session;
// private String login;
// private String token;
// private AuthResult result;
//
// public String getToken() {
// return token;
// }
//
// public String getSession() {
// return session;
// }
//
// public String getLogin() {
// return login;
// }
//
// public AuthResult getResult() {
// return result;
// }
//
// void setToken( String token ) {
// this.token = token;
// }
//
// void setSession( String session ) {
// this.session = session;
// }
//
// void setLogin( String login ) {
// this.login = login;
// }
//
// void setResult( AuthResult result ) {
// this.result = result;
// }
//
// public AuthData() {
// this(null, null, AuthResult.BAD_CONNECTION);
// }
//
// public AuthData( String login, String session, AuthResult result ){
// setLogin(login);
// setSession(session);
// setResult(result);
// }
// }
// Path: src/net/minecraft/Launcher.java
import java.applet.Applet;
import java.applet.AppletStub;
import java.awt.BorderLayout;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import org.sinrel.engine.actions.AuthData;
package net.minecraft;
public class Launcher extends Applet implements AppletStub {
private static final long serialVersionUID = 1L;
private Applet applet = null;
public Map<String, String> customParameters = new HashMap<String, String>();
private int context = 0;
private boolean active = false;
private URL[] urls;
private String bin; | private AuthData authData; |
Sinrel/SinrelLauncherEngine-Dev | src/org/sinrel/engine/library/OSManager.java | // Path: src/org/sinrel/engine/Engine.java
// public class Engine {
//
// private EngineSettings settings;
//
// private Intent intent;
// private Config config;
//
// private Downloader downloader;
// private Checker checker;
// private AuthBehavior auth;
// private MinecraftStarter starter;
//
// private boolean debug = false;
//
// public Engine( EngineSettings settings ) {
// try {
// intent = new Intent(this);
// setSettings(settings);
// config = new DefaultConfig(this);
// downloader = new DefaultDownloader();
// checker = new DefaultChecker();
// auth = new DefaultAuthBehavior();
// starter = new MinecraftAppletStarter();
// }catch( Exception e ) {
// FatalError.showErrorWindow(e);
// }
// }
//
// public EngineSettings getSettings() {
// return settings;
// }
//
// public Downloader getDownloader() {
// return downloader;
// }
//
// public Checker getChecker() {
// return checker;
// }
//
// public AuthBehavior getAuth() {
// return auth;
// }
//
// public Intent getIntent(){
// return intent;
// }
//
// public Config getConfig() {
// return config;
// }
//
// public MinecraftStarter getStarter(){
// return starter;
// }
//
// public void setSettings(EngineSettings settings){
// if( settings == null ) throw new NullPointerException();
// this.settings = settings;
// }
//
// public void setDownloader(Downloader downloader) {
// if( downloader == null ) throw new NullPointerException();
// this.downloader = downloader;
// }
//
// public void setChecker( Checker checker ) {
// if( checker == null ) throw new NullPointerException();
// this.checker = checker;
// }
//
// public void setAuth(AuthBehavior auth) {
// if( auth == null ) throw new NullPointerException();
// this.auth = auth;
// }
//
// public void setConfig( Config config ) {
// if( config == null ) throw new NullPointerException();
// this.config = config;
// }
//
// public void setMinecraftStarter( MinecraftStarter starter ){
// if( starter == null ) throw new NullPointerException();
// this.starter = starter;
// }
//
// public void useDebug( boolean debug ) {
// this.debug = debug;
// }
//
// public boolean isDebug(){
// return debug;
// }
//
// }
| import java.io.File;
import org.sinrel.engine.Engine;
| package org.sinrel.engine.library;
public final class OSManager {
/**
* @param name Имя рабочей папки
* @param clientName Имя сервера, к которому принадлежит клиент
* @return Возвращает директорию в которой содержатся файлы клиента
* Пример:
* name = sinrel
* clientName = simple
* Будет возвращена директория - C:\Users\%USERNAME%\AppData\Roaming\.sinrel\simple\bin (Для Windows)
*/
public static final File getClientFolder( String workingDirectory, String clientName ) {
return new File( getWorkingDirectory( workingDirectory ).getPath() , clientName + File.separator + "bin" + File.separator );
}
| // Path: src/org/sinrel/engine/Engine.java
// public class Engine {
//
// private EngineSettings settings;
//
// private Intent intent;
// private Config config;
//
// private Downloader downloader;
// private Checker checker;
// private AuthBehavior auth;
// private MinecraftStarter starter;
//
// private boolean debug = false;
//
// public Engine( EngineSettings settings ) {
// try {
// intent = new Intent(this);
// setSettings(settings);
// config = new DefaultConfig(this);
// downloader = new DefaultDownloader();
// checker = new DefaultChecker();
// auth = new DefaultAuthBehavior();
// starter = new MinecraftAppletStarter();
// }catch( Exception e ) {
// FatalError.showErrorWindow(e);
// }
// }
//
// public EngineSettings getSettings() {
// return settings;
// }
//
// public Downloader getDownloader() {
// return downloader;
// }
//
// public Checker getChecker() {
// return checker;
// }
//
// public AuthBehavior getAuth() {
// return auth;
// }
//
// public Intent getIntent(){
// return intent;
// }
//
// public Config getConfig() {
// return config;
// }
//
// public MinecraftStarter getStarter(){
// return starter;
// }
//
// public void setSettings(EngineSettings settings){
// if( settings == null ) throw new NullPointerException();
// this.settings = settings;
// }
//
// public void setDownloader(Downloader downloader) {
// if( downloader == null ) throw new NullPointerException();
// this.downloader = downloader;
// }
//
// public void setChecker( Checker checker ) {
// if( checker == null ) throw new NullPointerException();
// this.checker = checker;
// }
//
// public void setAuth(AuthBehavior auth) {
// if( auth == null ) throw new NullPointerException();
// this.auth = auth;
// }
//
// public void setConfig( Config config ) {
// if( config == null ) throw new NullPointerException();
// this.config = config;
// }
//
// public void setMinecraftStarter( MinecraftStarter starter ){
// if( starter == null ) throw new NullPointerException();
// this.starter = starter;
// }
//
// public void useDebug( boolean debug ) {
// this.debug = debug;
// }
//
// public boolean isDebug(){
// return debug;
// }
//
// }
// Path: src/org/sinrel/engine/library/OSManager.java
import java.io.File;
import org.sinrel.engine.Engine;
package org.sinrel.engine.library;
public final class OSManager {
/**
* @param name Имя рабочей папки
* @param clientName Имя сервера, к которому принадлежит клиент
* @return Возвращает директорию в которой содержатся файлы клиента
* Пример:
* name = sinrel
* clientName = simple
* Будет возвращена директория - C:\Users\%USERNAME%\AppData\Roaming\.sinrel\simple\bin (Для Windows)
*/
public static final File getClientFolder( String workingDirectory, String clientName ) {
return new File( getWorkingDirectory( workingDirectory ).getPath() , clientName + File.separator + "bin" + File.separator );
}
| public static final File getClientFolder( Engine engine, String clientName ) {
|
Sinrel/SinrelLauncherEngine-Dev | src/org/sinrel/engine/actions/Downloader.java | // Path: src/org/sinrel/engine/Engine.java
// public class Engine {
//
// private EngineSettings settings;
//
// private Intent intent;
// private Config config;
//
// private Downloader downloader;
// private Checker checker;
// private AuthBehavior auth;
// private MinecraftStarter starter;
//
// private boolean debug = false;
//
// public Engine( EngineSettings settings ) {
// try {
// intent = new Intent(this);
// setSettings(settings);
// config = new DefaultConfig(this);
// downloader = new DefaultDownloader();
// checker = new DefaultChecker();
// auth = new DefaultAuthBehavior();
// starter = new MinecraftAppletStarter();
// }catch( Exception e ) {
// FatalError.showErrorWindow(e);
// }
// }
//
// public EngineSettings getSettings() {
// return settings;
// }
//
// public Downloader getDownloader() {
// return downloader;
// }
//
// public Checker getChecker() {
// return checker;
// }
//
// public AuthBehavior getAuth() {
// return auth;
// }
//
// public Intent getIntent(){
// return intent;
// }
//
// public Config getConfig() {
// return config;
// }
//
// public MinecraftStarter getStarter(){
// return starter;
// }
//
// public void setSettings(EngineSettings settings){
// if( settings == null ) throw new NullPointerException();
// this.settings = settings;
// }
//
// public void setDownloader(Downloader downloader) {
// if( downloader == null ) throw new NullPointerException();
// this.downloader = downloader;
// }
//
// public void setChecker( Checker checker ) {
// if( checker == null ) throw new NullPointerException();
// this.checker = checker;
// }
//
// public void setAuth(AuthBehavior auth) {
// if( auth == null ) throw new NullPointerException();
// this.auth = auth;
// }
//
// public void setConfig( Config config ) {
// if( config == null ) throw new NullPointerException();
// this.config = config;
// }
//
// public void setMinecraftStarter( MinecraftStarter starter ){
// if( starter == null ) throw new NullPointerException();
// this.starter = starter;
// }
//
// public void useDebug( boolean debug ) {
// this.debug = debug;
// }
//
// public boolean isDebug(){
// return debug;
// }
//
// }
//
// Path: src/org/sinrel/engine/listeners/DownloadListener.java
// public interface DownloadListener {
//
// /**
// * При старте загрузки
// */
// public void onStartDownload( DownloadEvent e );
//
// /**
// * Вызывается при смене загружаемого файла
// * @param e - {@link DownloadEvent}
// */
// public void onFileChange( DownloadEvent e );
//
// /**
// * При подсчёте загруженного
// */
// public void onPercentChange( DownloadEvent e );
//
// }
| import java.util.ArrayList;
import org.sinrel.engine.Engine;
import org.sinrel.engine.listeners.DownloadListener; | additionalFiles.add( filename );
}
public void removeAdditionalFile( String filename ) {
additionalFiles.remove( filename );
}
public void addAdditionalArchive( String filename ) {
additionalArchives.add( filename );
}
public void removeAdditionalArchive( String filename ) {
additionalArchives.remove( filename );
}
protected void onStartDownload( DownloadEvent e ){
for( DownloadListener dl : listeners )
dl.onStartDownload(e);
}
protected void onFileChange( DownloadEvent e ){
for( DownloadListener dl : listeners )
dl.onFileChange(e);
}
protected void onPercentChange( DownloadEvent e ){
for( DownloadListener dl : listeners )
dl.onPercentChange(e);
}
| // Path: src/org/sinrel/engine/Engine.java
// public class Engine {
//
// private EngineSettings settings;
//
// private Intent intent;
// private Config config;
//
// private Downloader downloader;
// private Checker checker;
// private AuthBehavior auth;
// private MinecraftStarter starter;
//
// private boolean debug = false;
//
// public Engine( EngineSettings settings ) {
// try {
// intent = new Intent(this);
// setSettings(settings);
// config = new DefaultConfig(this);
// downloader = new DefaultDownloader();
// checker = new DefaultChecker();
// auth = new DefaultAuthBehavior();
// starter = new MinecraftAppletStarter();
// }catch( Exception e ) {
// FatalError.showErrorWindow(e);
// }
// }
//
// public EngineSettings getSettings() {
// return settings;
// }
//
// public Downloader getDownloader() {
// return downloader;
// }
//
// public Checker getChecker() {
// return checker;
// }
//
// public AuthBehavior getAuth() {
// return auth;
// }
//
// public Intent getIntent(){
// return intent;
// }
//
// public Config getConfig() {
// return config;
// }
//
// public MinecraftStarter getStarter(){
// return starter;
// }
//
// public void setSettings(EngineSettings settings){
// if( settings == null ) throw new NullPointerException();
// this.settings = settings;
// }
//
// public void setDownloader(Downloader downloader) {
// if( downloader == null ) throw new NullPointerException();
// this.downloader = downloader;
// }
//
// public void setChecker( Checker checker ) {
// if( checker == null ) throw new NullPointerException();
// this.checker = checker;
// }
//
// public void setAuth(AuthBehavior auth) {
// if( auth == null ) throw new NullPointerException();
// this.auth = auth;
// }
//
// public void setConfig( Config config ) {
// if( config == null ) throw new NullPointerException();
// this.config = config;
// }
//
// public void setMinecraftStarter( MinecraftStarter starter ){
// if( starter == null ) throw new NullPointerException();
// this.starter = starter;
// }
//
// public void useDebug( boolean debug ) {
// this.debug = debug;
// }
//
// public boolean isDebug(){
// return debug;
// }
//
// }
//
// Path: src/org/sinrel/engine/listeners/DownloadListener.java
// public interface DownloadListener {
//
// /**
// * При старте загрузки
// */
// public void onStartDownload( DownloadEvent e );
//
// /**
// * Вызывается при смене загружаемого файла
// * @param e - {@link DownloadEvent}
// */
// public void onFileChange( DownloadEvent e );
//
// /**
// * При подсчёте загруженного
// */
// public void onPercentChange( DownloadEvent e );
//
// }
// Path: src/org/sinrel/engine/actions/Downloader.java
import java.util.ArrayList;
import org.sinrel.engine.Engine;
import org.sinrel.engine.listeners.DownloadListener;
additionalFiles.add( filename );
}
public void removeAdditionalFile( String filename ) {
additionalFiles.remove( filename );
}
public void addAdditionalArchive( String filename ) {
additionalArchives.add( filename );
}
public void removeAdditionalArchive( String filename ) {
additionalArchives.remove( filename );
}
protected void onStartDownload( DownloadEvent e ){
for( DownloadListener dl : listeners )
dl.onStartDownload(e);
}
protected void onFileChange( DownloadEvent e ){
for( DownloadListener dl : listeners )
dl.onFileChange(e);
}
protected void onPercentChange( DownloadEvent e ){
for( DownloadListener dl : listeners )
dl.onPercentChange(e);
}
| public abstract DownloadResult downloadClient( Engine e , String clientName ); |
JimSeker/service | eclipse/ServiceDemoIPC/src/edu/cs4730/servicedemoipc/MainFragment.java | // Path: ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/RandNumService.java
// public class LocalBinder extends Binder {
// RandNumService getService() {
// // Return this instance of LocalService so clients can call public methods
// return RandNumService.this;
// }
// }
| import edu.cs4730.servicedemoipc.RandNumService.LocalBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Toast; | public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_main, container, false);
//setup the button, so it will call into the service and get a random number.
myView.findViewById(R.id.btn_gn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mBound) {
// Call a method from the RandNumService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
//but getting a random number is really quick, so I'm doing it here instead.
int num = mService.getRandomNumber();
Toast.makeText(getActivity(), "number: " + num, Toast.LENGTH_SHORT).show();
}
}
});
return myView;
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance | // Path: ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/RandNumService.java
// public class LocalBinder extends Binder {
// RandNumService getService() {
// // Return this instance of LocalService so clients can call public methods
// return RandNumService.this;
// }
// }
// Path: eclipse/ServiceDemoIPC/src/edu/cs4730/servicedemoipc/MainFragment.java
import edu.cs4730.servicedemoipc.RandNumService.LocalBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Toast;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_main, container, false);
//setup the button, so it will call into the service and get a random number.
myView.findViewById(R.id.btn_gn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mBound) {
// Call a method from the RandNumService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
//but getting a random number is really quick, so I'm doing it here instead.
int num = mService.getRandomNumber();
Toast.makeText(getActivity(), "number: " + num, Toast.LENGTH_SHORT).show();
}
}
});
return myView;
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance | LocalBinder binder = (LocalBinder) service; |
JimSeker/service | ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/MainFragment.java | // Path: ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/RandNumService.java
// public class LocalBinder extends Binder {
// RandNumService getService() {
// // Return this instance of LocalService so clients can call public methods
// return RandNumService.this;
// }
// }
| import edu.cs4730.servicedemoipc.RandNumService.LocalBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Toast; | // Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_main, container, false);
//setup the button, so it will call into the service and get a random number.
myView.findViewById(R.id.btn_gn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mBound) {
// Call a method from the RandNumService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
//but getting a random number is really quick, so I'm doing it here instead.
int num = mService.getRandomNumber();
Toast.makeText(getActivity(), "number: " + num, Toast.LENGTH_SHORT).show();
}
}
});
return myView;
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance | // Path: ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/RandNumService.java
// public class LocalBinder extends Binder {
// RandNumService getService() {
// // Return this instance of LocalService so clients can call public methods
// return RandNumService.this;
// }
// }
// Path: ServiceDemoIPC/app/src/main/java/edu/cs4730/servicedemoipc/MainFragment.java
import edu.cs4730.servicedemoipc.RandNumService.LocalBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Toast;
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_main, container, false);
//setup the button, so it will call into the service and get a random number.
myView.findViewById(R.id.btn_gn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mBound) {
// Call a method from the RandNumService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
//but getting a random number is really quick, so I'm doing it here instead.
int num = mService.getRandomNumber();
Toast.makeText(getActivity(), "number: " + num, Toast.LENGTH_SHORT).show();
}
}
});
return myView;
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance | LocalBinder binder = (LocalBinder) service; |
jkirsch/jedi | core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/features/detector/FindShortestPathFeatureExtractor.java | // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FoundFeature.java
// public class FoundFeature<T> {
//
// T entity1;
// T entity2;
//
// String pattern;
// String relation;
//
// public FoundFeature(T entity1, T entity2, String pattern) {
// this.entity1 = entity1;
// this.entity2 = entity2;
// this.pattern = pattern;
// }
//
//
// public String getRelation() {
// return relation;
// }
//
// public void setRelation(String relation) {
// this.relation = relation;
// }
//
// public T getEntity1() {
// return entity1;
// }
//
// public void setEntity1(T entity1) {
// this.entity1 = entity1;
// }
//
// public T getEntity2() {
// return entity2;
// }
//
// public void setEntity2(T entity2) {
// this.entity2 = entity2;
// }
//
// public String getPattern() {
// return pattern;
// }
//
// public void setPattern(String pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public String toString() {
// return "FoundFeature{" +
// "entity1=" + transformToString(entity1) +
// ", entity2=" + transformToString(entity2) +
// ", pattern='" + pattern + '\'' +
// ", relation='" + relation + '\'' +
// '}';
// }
//
// private static <T> String transformToString(T input) {
// if(input instanceof Annotation) {
// return ((Annotation) input).getCoveredText();
// } else {
// return input.toString();
// }
// }
// }
//
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/util/StringComparision.java
// public class StringComparision {
//
// public static boolean determineSimilar(String left, String right) {
//
// final String commonPrefix = StringUtils.getCommonPrefix(new String[]{left, right});
// final String commonSuffix = StringUtils.getCommonPrefix(new String[]{StringUtils.reverse(left), StringUtils.reverse(right)});
//
// final int commonLength = commonPrefix.length() + commonSuffix.length();
// final double weightedSimilar = Math.sqrt((commonLength / (float) left.length()) * (commonLength / (float) right.length()));
// int distance = LevenshteinDistance.computeLevenshteinDistance(right, commonPrefix + StringUtils.reverse(commonSuffix));
// return weightedSimilar >= 0.85 || (distance < 3 && (commonPrefix.length() > 0) && (commonSuffix.length() > 0));
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
import com.google.common.primitives.Ints;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceChain;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceLink;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.*;
import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import edu.tuberlin.dima.textmining.jedi.core.model.FoundFeature;
import edu.tuberlin.dima.textmining.jedi.core.util.StringComparision;
import org.apache.commons.lang.StringUtils;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.tcas.Annotation;
import org.jgrapht.DirectedGraph;
import org.jgrapht.GraphPath;
import org.jgrapht.Graphs;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;
import javax.annotation.Nullable;
import java.util.*;
import java.util.regex.Pattern; | package edu.tuberlin.dima.textmining.jedi.core.features.detector;
/**
* A Function that takes a JCas as input and extracts
* its annotations in terms of the shortest path between
* all recognized entities.
*/
public class FindShortestPathFeatureExtractor extends AbstractShortestPathFeatureExtractor {
public FindShortestPathFeatureExtractor(String options) throws UIMAException {
super(options);
}
public FindShortestPathFeatureExtractor(String options, DetectorType detectorType) throws UIMAException {
super(options);
setName(detectorType.name());
}
private static class EntityPair {
private Annotation entity1;
private Annotation entity2;
public Annotation getEntity1() {
return entity1;
}
public Annotation getEntity2() {
return entity2;
}
private EntityPair(Annotation entity1, Annotation entity2) {
this.entity1 = entity1;
this.entity2 = entity2;
}
}
/**
* Extract the shortest paths along the dependency parse
* between every two named entities recognized.
*
* @param graph the dependency graph
* @return list of found features with entity_pair and pattern
* with the shortest path as pattern
*/
@Override | // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FoundFeature.java
// public class FoundFeature<T> {
//
// T entity1;
// T entity2;
//
// String pattern;
// String relation;
//
// public FoundFeature(T entity1, T entity2, String pattern) {
// this.entity1 = entity1;
// this.entity2 = entity2;
// this.pattern = pattern;
// }
//
//
// public String getRelation() {
// return relation;
// }
//
// public void setRelation(String relation) {
// this.relation = relation;
// }
//
// public T getEntity1() {
// return entity1;
// }
//
// public void setEntity1(T entity1) {
// this.entity1 = entity1;
// }
//
// public T getEntity2() {
// return entity2;
// }
//
// public void setEntity2(T entity2) {
// this.entity2 = entity2;
// }
//
// public String getPattern() {
// return pattern;
// }
//
// public void setPattern(String pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public String toString() {
// return "FoundFeature{" +
// "entity1=" + transformToString(entity1) +
// ", entity2=" + transformToString(entity2) +
// ", pattern='" + pattern + '\'' +
// ", relation='" + relation + '\'' +
// '}';
// }
//
// private static <T> String transformToString(T input) {
// if(input instanceof Annotation) {
// return ((Annotation) input).getCoveredText();
// } else {
// return input.toString();
// }
// }
// }
//
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/util/StringComparision.java
// public class StringComparision {
//
// public static boolean determineSimilar(String left, String right) {
//
// final String commonPrefix = StringUtils.getCommonPrefix(new String[]{left, right});
// final String commonSuffix = StringUtils.getCommonPrefix(new String[]{StringUtils.reverse(left), StringUtils.reverse(right)});
//
// final int commonLength = commonPrefix.length() + commonSuffix.length();
// final double weightedSimilar = Math.sqrt((commonLength / (float) left.length()) * (commonLength / (float) right.length()));
// int distance = LevenshteinDistance.computeLevenshteinDistance(right, commonPrefix + StringUtils.reverse(commonSuffix));
// return weightedSimilar >= 0.85 || (distance < 3 && (commonPrefix.length() > 0) && (commonSuffix.length() > 0));
// }
// }
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/features/detector/FindShortestPathFeatureExtractor.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
import com.google.common.primitives.Ints;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceChain;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceLink;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.*;
import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import edu.tuberlin.dima.textmining.jedi.core.model.FoundFeature;
import edu.tuberlin.dima.textmining.jedi.core.util.StringComparision;
import org.apache.commons.lang.StringUtils;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.tcas.Annotation;
import org.jgrapht.DirectedGraph;
import org.jgrapht.GraphPath;
import org.jgrapht.Graphs;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;
import javax.annotation.Nullable;
import java.util.*;
import java.util.regex.Pattern;
package edu.tuberlin.dima.textmining.jedi.core.features.detector;
/**
* A Function that takes a JCas as input and extracts
* its annotations in terms of the shortest path between
* all recognized entities.
*/
public class FindShortestPathFeatureExtractor extends AbstractShortestPathFeatureExtractor {
public FindShortestPathFeatureExtractor(String options) throws UIMAException {
super(options);
}
public FindShortestPathFeatureExtractor(String options, DetectorType detectorType) throws UIMAException {
super(options);
setName(detectorType.name());
}
private static class EntityPair {
private Annotation entity1;
private Annotation entity2;
public Annotation getEntity1() {
return entity1;
}
public Annotation getEntity2() {
return entity2;
}
private EntityPair(Annotation entity1, Annotation entity2) {
this.entity1 = entity1;
this.entity2 = entity2;
}
}
/**
* Extract the shortest paths along the dependency parse
* between every two named entities recognized.
*
* @param graph the dependency graph
* @return list of found features with entity_pair and pattern
* with the shortest path as pattern
*/
@Override | public List<FoundFeature<Annotation>> getShortestPaths(final UndirectedGraph<Token, DependencyEdge> graph) { |
jkirsch/jedi | core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/features/detector/FindShortestPathFeatureExtractor.java | // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FoundFeature.java
// public class FoundFeature<T> {
//
// T entity1;
// T entity2;
//
// String pattern;
// String relation;
//
// public FoundFeature(T entity1, T entity2, String pattern) {
// this.entity1 = entity1;
// this.entity2 = entity2;
// this.pattern = pattern;
// }
//
//
// public String getRelation() {
// return relation;
// }
//
// public void setRelation(String relation) {
// this.relation = relation;
// }
//
// public T getEntity1() {
// return entity1;
// }
//
// public void setEntity1(T entity1) {
// this.entity1 = entity1;
// }
//
// public T getEntity2() {
// return entity2;
// }
//
// public void setEntity2(T entity2) {
// this.entity2 = entity2;
// }
//
// public String getPattern() {
// return pattern;
// }
//
// public void setPattern(String pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public String toString() {
// return "FoundFeature{" +
// "entity1=" + transformToString(entity1) +
// ", entity2=" + transformToString(entity2) +
// ", pattern='" + pattern + '\'' +
// ", relation='" + relation + '\'' +
// '}';
// }
//
// private static <T> String transformToString(T input) {
// if(input instanceof Annotation) {
// return ((Annotation) input).getCoveredText();
// } else {
// return input.toString();
// }
// }
// }
//
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/util/StringComparision.java
// public class StringComparision {
//
// public static boolean determineSimilar(String left, String right) {
//
// final String commonPrefix = StringUtils.getCommonPrefix(new String[]{left, right});
// final String commonSuffix = StringUtils.getCommonPrefix(new String[]{StringUtils.reverse(left), StringUtils.reverse(right)});
//
// final int commonLength = commonPrefix.length() + commonSuffix.length();
// final double weightedSimilar = Math.sqrt((commonLength / (float) left.length()) * (commonLength / (float) right.length()));
// int distance = LevenshteinDistance.computeLevenshteinDistance(right, commonPrefix + StringUtils.reverse(commonSuffix));
// return weightedSimilar >= 0.85 || (distance < 3 && (commonPrefix.length() > 0) && (commonSuffix.length() > 0));
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
import com.google.common.primitives.Ints;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceChain;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceLink;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.*;
import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import edu.tuberlin.dima.textmining.jedi.core.model.FoundFeature;
import edu.tuberlin.dima.textmining.jedi.core.util.StringComparision;
import org.apache.commons.lang.StringUtils;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.tcas.Annotation;
import org.jgrapht.DirectedGraph;
import org.jgrapht.GraphPath;
import org.jgrapht.Graphs;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;
import javax.annotation.Nullable;
import java.util.*;
import java.util.regex.Pattern; |
// sort the named entities based on their appearance on the text
Collections.sort(namedEntities, Ordering.from(new Comparator<Annotation>() {
@Override
public int compare(Annotation o1, Annotation o2) {
return Integer.compare(o1.getBegin(), o2.getBegin());
}
}));
// get all pairs of entities omitting incestuous and duplicate pairs
List<EntityPair> entityPairs = Lists.newArrayList();
for (int i = 0; i < namedEntities.size(); i++) {
for (int j = i + 1; j < namedEntities.size(); j++) {
// check that the entities do not overlap each other
final Annotation annotation = namedEntities.get(i);
final Annotation annotation2 = namedEntities.get(j);
if (annotation2.getBegin() > annotation.getEnd()) {
entityPairs.add(new EntityPair(annotation, annotation2));
}
}
}
if (isCollapseMentions()) {
for (int i = 0; i < namedEntities.size(); i++) {
final Annotation left = namedEntities.get(i);
for (int j = i + 1; j < namedEntities.size(); j++) {
final Annotation right = namedEntities.get(j);
| // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FoundFeature.java
// public class FoundFeature<T> {
//
// T entity1;
// T entity2;
//
// String pattern;
// String relation;
//
// public FoundFeature(T entity1, T entity2, String pattern) {
// this.entity1 = entity1;
// this.entity2 = entity2;
// this.pattern = pattern;
// }
//
//
// public String getRelation() {
// return relation;
// }
//
// public void setRelation(String relation) {
// this.relation = relation;
// }
//
// public T getEntity1() {
// return entity1;
// }
//
// public void setEntity1(T entity1) {
// this.entity1 = entity1;
// }
//
// public T getEntity2() {
// return entity2;
// }
//
// public void setEntity2(T entity2) {
// this.entity2 = entity2;
// }
//
// public String getPattern() {
// return pattern;
// }
//
// public void setPattern(String pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public String toString() {
// return "FoundFeature{" +
// "entity1=" + transformToString(entity1) +
// ", entity2=" + transformToString(entity2) +
// ", pattern='" + pattern + '\'' +
// ", relation='" + relation + '\'' +
// '}';
// }
//
// private static <T> String transformToString(T input) {
// if(input instanceof Annotation) {
// return ((Annotation) input).getCoveredText();
// } else {
// return input.toString();
// }
// }
// }
//
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/util/StringComparision.java
// public class StringComparision {
//
// public static boolean determineSimilar(String left, String right) {
//
// final String commonPrefix = StringUtils.getCommonPrefix(new String[]{left, right});
// final String commonSuffix = StringUtils.getCommonPrefix(new String[]{StringUtils.reverse(left), StringUtils.reverse(right)});
//
// final int commonLength = commonPrefix.length() + commonSuffix.length();
// final double weightedSimilar = Math.sqrt((commonLength / (float) left.length()) * (commonLength / (float) right.length()));
// int distance = LevenshteinDistance.computeLevenshteinDistance(right, commonPrefix + StringUtils.reverse(commonSuffix));
// return weightedSimilar >= 0.85 || (distance < 3 && (commonPrefix.length() > 0) && (commonSuffix.length() > 0));
// }
// }
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/features/detector/FindShortestPathFeatureExtractor.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
import com.google.common.primitives.Ints;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceChain;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceLink;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.*;
import de.tudarmstadt.ukp.dkpro.core.api.ner.type.NamedEntity;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import edu.tuberlin.dima.textmining.jedi.core.model.FoundFeature;
import edu.tuberlin.dima.textmining.jedi.core.util.StringComparision;
import org.apache.commons.lang.StringUtils;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.tcas.Annotation;
import org.jgrapht.DirectedGraph;
import org.jgrapht.GraphPath;
import org.jgrapht.Graphs;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;
import javax.annotation.Nullable;
import java.util.*;
import java.util.regex.Pattern;
// sort the named entities based on their appearance on the text
Collections.sort(namedEntities, Ordering.from(new Comparator<Annotation>() {
@Override
public int compare(Annotation o1, Annotation o2) {
return Integer.compare(o1.getBegin(), o2.getBegin());
}
}));
// get all pairs of entities omitting incestuous and duplicate pairs
List<EntityPair> entityPairs = Lists.newArrayList();
for (int i = 0; i < namedEntities.size(); i++) {
for (int j = i + 1; j < namedEntities.size(); j++) {
// check that the entities do not overlap each other
final Annotation annotation = namedEntities.get(i);
final Annotation annotation2 = namedEntities.get(j);
if (annotation2.getBegin() > annotation.getEnd()) {
entityPairs.add(new EntityPair(annotation, annotation2));
}
}
}
if (isCollapseMentions()) {
for (int i = 0; i < namedEntities.size(); i++) {
final Annotation left = namedEntities.get(i);
for (int j = i + 1; j < namedEntities.size(); j++) {
final Annotation right = namedEntities.get(j);
| if (StringComparision.determineSimilar(left.getCoveredText(), right.getCoveredText())) { |
jkirsch/jedi | core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/freebase/FreebaseHelper.java | // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FreebaseRelation.java
// public class FreebaseRelation {
//
// String domain;
// String range;
//
// List<String> domainTypes;
// List<String> rangeTypes;
//
// public FreebaseRelation(String domain, String range, List<String> rangeTypes, List<String> domainTypes) {
// this.domain = domain;
// this.range = range;
// this.rangeTypes = rangeTypes;
// this.domainTypes = domainTypes;
// }
//
// public String getRange() {
// return range;
// }
//
// public String getDomain() {
// return domain;
// }
//
// public List<String> getRangeTypes() {
// return rangeTypes;
// }
//
// public List<String> getDomainTypes() {
// return domainTypes;
// }
//
// @Override
// public String toString() {
// return "FreebaseRelation{" +
// "domain='" + domain + '\'' +
// ", range='" + range + '\'' +
// ", domainTypes=" + domainTypes +
// ", rangeTypes=" + rangeTypes +
// '}';
// }
// }
| import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import edu.tuberlin.dima.textmining.jedi.core.model.FreebaseRelation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.List; |
JsonNode jsonNode = getURL(metaURL);
if (jsonNode.has("property")) {
final JsonNode property = jsonNode.get("property");
if (property.has("/type/property/reverse_property")) {
return property.get("/type/property/reverse_property").get("values").get(0).get("id").asText();
}
}
return null;
}
private JsonNode getFreebaseTopicForID(String freebaseID) throws IOException {
String ask = "https://www.googleapis.com/freebase/v1/topic/{freebaseID}?key=AIzaSyCyloa8DMxhKvBVdqdk_Drf900rAeeA7QA";
String trimmedR = freebaseID.replaceAll("\\.", "/");
String metaURL = ask.replace("{freebaseID}", trimmedR);
LOG.info("Asking " + trimmedR);
JsonNode parse = getURL(metaURL);
return parse.get("property");
}
| // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FreebaseRelation.java
// public class FreebaseRelation {
//
// String domain;
// String range;
//
// List<String> domainTypes;
// List<String> rangeTypes;
//
// public FreebaseRelation(String domain, String range, List<String> rangeTypes, List<String> domainTypes) {
// this.domain = domain;
// this.range = range;
// this.rangeTypes = rangeTypes;
// this.domainTypes = domainTypes;
// }
//
// public String getRange() {
// return range;
// }
//
// public String getDomain() {
// return domain;
// }
//
// public List<String> getRangeTypes() {
// return rangeTypes;
// }
//
// public List<String> getDomainTypes() {
// return domainTypes;
// }
//
// @Override
// public String toString() {
// return "FreebaseRelation{" +
// "domain='" + domain + '\'' +
// ", range='" + range + '\'' +
// ", domainTypes=" + domainTypes +
// ", rangeTypes=" + rangeTypes +
// '}';
// }
// }
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/freebase/FreebaseHelper.java
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Resources;
import edu.tuberlin.dima.textmining.jedi.core.model.FreebaseRelation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.List;
JsonNode jsonNode = getURL(metaURL);
if (jsonNode.has("property")) {
final JsonNode property = jsonNode.get("property");
if (property.has("/type/property/reverse_property")) {
return property.get("/type/property/reverse_property").get("values").get(0).get("id").asText();
}
}
return null;
}
private JsonNode getFreebaseTopicForID(String freebaseID) throws IOException {
String ask = "https://www.googleapis.com/freebase/v1/topic/{freebaseID}?key=AIzaSyCyloa8DMxhKvBVdqdk_Drf900rAeeA7QA";
String trimmedR = freebaseID.replaceAll("\\.", "/");
String metaURL = ask.replace("{freebaseID}", trimmedR);
LOG.info("Asking " + trimmedR);
JsonNode parse = getURL(metaURL);
return parse.get("property");
}
| public FreebaseRelation getTypesForRelationFromFreebase(String r) throws IOException { |
jkirsch/jedi | core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/features/detector/AbstractShortestPathFeatureExtractor.java | // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FoundFeature.java
// public class FoundFeature<T> {
//
// T entity1;
// T entity2;
//
// String pattern;
// String relation;
//
// public FoundFeature(T entity1, T entity2, String pattern) {
// this.entity1 = entity1;
// this.entity2 = entity2;
// this.pattern = pattern;
// }
//
//
// public String getRelation() {
// return relation;
// }
//
// public void setRelation(String relation) {
// this.relation = relation;
// }
//
// public T getEntity1() {
// return entity1;
// }
//
// public void setEntity1(T entity1) {
// this.entity1 = entity1;
// }
//
// public T getEntity2() {
// return entity2;
// }
//
// public void setEntity2(T entity2) {
// this.entity2 = entity2;
// }
//
// public String getPattern() {
// return pattern;
// }
//
// public void setPattern(String pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public String toString() {
// return "FoundFeature{" +
// "entity1=" + transformToString(entity1) +
// ", entity2=" + transformToString(entity2) +
// ", pattern='" + pattern + '\'' +
// ", relation='" + relation + '\'' +
// '}';
// }
//
// private static <T> String transformToString(T input) {
// if(input instanceof Annotation) {
// return ((Annotation) input).getCoveredText();
// } else {
// return input.toString();
// }
// }
// }
//
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/util/JCommanderClassConverter.java
// public class JCommanderClassConverter extends BaseConverter<Class> {
//
// public JCommanderClassConverter(String optionName) {
// super(optionName);
// }
//
// @Override
// public Class convert(String value) {
// try {
// return Class.forName(value);
// } catch (ClassNotFoundException e) {
// throw new ParameterException(getErrorString(value, "a class"));
// }
// }
// }
| import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.O;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency;
import edu.tuberlin.dima.textmining.jedi.core.model.FoundFeature;
import edu.tuberlin.dima.textmining.jedi.core.util.JCommanderClassConverter;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.graph.SimpleGraph;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package edu.tuberlin.dima.textmining.jedi.core.features.detector;
/**
*/
public abstract class AbstractShortestPathFeatureExtractor {
@Parameter(names = {"-lemmatize"}, description = "Lemmatize the pattern to remove times", required = false)
private boolean lemmatize = false;
@Parameter(names = {"-pickupSimilar"}, description = "If set, the token is expanded left and right with tokens of the same selectionType", required = false)
private boolean pickupSimilar = false;
@Parameter(names = {"-collapseMentions"}, description = "If set, similar mentions are collapsed", required = false)
private boolean collapseMentions = false;
| // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FoundFeature.java
// public class FoundFeature<T> {
//
// T entity1;
// T entity2;
//
// String pattern;
// String relation;
//
// public FoundFeature(T entity1, T entity2, String pattern) {
// this.entity1 = entity1;
// this.entity2 = entity2;
// this.pattern = pattern;
// }
//
//
// public String getRelation() {
// return relation;
// }
//
// public void setRelation(String relation) {
// this.relation = relation;
// }
//
// public T getEntity1() {
// return entity1;
// }
//
// public void setEntity1(T entity1) {
// this.entity1 = entity1;
// }
//
// public T getEntity2() {
// return entity2;
// }
//
// public void setEntity2(T entity2) {
// this.entity2 = entity2;
// }
//
// public String getPattern() {
// return pattern;
// }
//
// public void setPattern(String pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public String toString() {
// return "FoundFeature{" +
// "entity1=" + transformToString(entity1) +
// ", entity2=" + transformToString(entity2) +
// ", pattern='" + pattern + '\'' +
// ", relation='" + relation + '\'' +
// '}';
// }
//
// private static <T> String transformToString(T input) {
// if(input instanceof Annotation) {
// return ((Annotation) input).getCoveredText();
// } else {
// return input.toString();
// }
// }
// }
//
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/util/JCommanderClassConverter.java
// public class JCommanderClassConverter extends BaseConverter<Class> {
//
// public JCommanderClassConverter(String optionName) {
// super(optionName);
// }
//
// @Override
// public Class convert(String value) {
// try {
// return Class.forName(value);
// } catch (ClassNotFoundException e) {
// throw new ParameterException(getErrorString(value, "a class"));
// }
// }
// }
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/features/detector/AbstractShortestPathFeatureExtractor.java
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.O;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency;
import edu.tuberlin.dima.textmining.jedi.core.model.FoundFeature;
import edu.tuberlin.dima.textmining.jedi.core.util.JCommanderClassConverter;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.graph.SimpleGraph;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package edu.tuberlin.dima.textmining.jedi.core.features.detector;
/**
*/
public abstract class AbstractShortestPathFeatureExtractor {
@Parameter(names = {"-lemmatize"}, description = "Lemmatize the pattern to remove times", required = false)
private boolean lemmatize = false;
@Parameter(names = {"-pickupSimilar"}, description = "If set, the token is expanded left and right with tokens of the same selectionType", required = false)
private boolean pickupSimilar = false;
@Parameter(names = {"-collapseMentions"}, description = "If set, similar mentions are collapsed", required = false)
private boolean collapseMentions = false;
| @Parameter(names = {"-selectionType"}, description = "Class of selection Type (e.g. Named Entity)", required = true, converter = JCommanderClassConverter.class) |
jkirsch/jedi | core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/features/detector/AbstractShortestPathFeatureExtractor.java | // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FoundFeature.java
// public class FoundFeature<T> {
//
// T entity1;
// T entity2;
//
// String pattern;
// String relation;
//
// public FoundFeature(T entity1, T entity2, String pattern) {
// this.entity1 = entity1;
// this.entity2 = entity2;
// this.pattern = pattern;
// }
//
//
// public String getRelation() {
// return relation;
// }
//
// public void setRelation(String relation) {
// this.relation = relation;
// }
//
// public T getEntity1() {
// return entity1;
// }
//
// public void setEntity1(T entity1) {
// this.entity1 = entity1;
// }
//
// public T getEntity2() {
// return entity2;
// }
//
// public void setEntity2(T entity2) {
// this.entity2 = entity2;
// }
//
// public String getPattern() {
// return pattern;
// }
//
// public void setPattern(String pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public String toString() {
// return "FoundFeature{" +
// "entity1=" + transformToString(entity1) +
// ", entity2=" + transformToString(entity2) +
// ", pattern='" + pattern + '\'' +
// ", relation='" + relation + '\'' +
// '}';
// }
//
// private static <T> String transformToString(T input) {
// if(input instanceof Annotation) {
// return ((Annotation) input).getCoveredText();
// } else {
// return input.toString();
// }
// }
// }
//
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/util/JCommanderClassConverter.java
// public class JCommanderClassConverter extends BaseConverter<Class> {
//
// public JCommanderClassConverter(String optionName) {
// super(optionName);
// }
//
// @Override
// public Class convert(String value) {
// try {
// return Class.forName(value);
// } catch (ClassNotFoundException e) {
// throw new ParameterException(getErrorString(value, "a class"));
// }
// }
// }
| import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.O;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency;
import edu.tuberlin.dima.textmining.jedi.core.model.FoundFeature;
import edu.tuberlin.dima.textmining.jedi.core.util.JCommanderClassConverter;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.graph.SimpleGraph;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package edu.tuberlin.dima.textmining.jedi.core.features.detector;
/**
*/
public abstract class AbstractShortestPathFeatureExtractor {
@Parameter(names = {"-lemmatize"}, description = "Lemmatize the pattern to remove times", required = false)
private boolean lemmatize = false;
@Parameter(names = {"-pickupSimilar"}, description = "If set, the token is expanded left and right with tokens of the same selectionType", required = false)
private boolean pickupSimilar = false;
@Parameter(names = {"-collapseMentions"}, description = "If set, similar mentions are collapsed", required = false)
private boolean collapseMentions = false;
@Parameter(names = {"-selectionType"}, description = "Class of selection Type (e.g. Named Entity)", required = true, converter = JCommanderClassConverter.class)
private Class<? extends Annotation> selectionType;
@Parameter(names = {"-additionalSelectionType"}, description = "AdditionalClass of selection Type (e.g. Named Entity)", required = false, converter = JCommanderClassConverter.class)
private Class<? extends Annotation> additionalSelectionType;
@Parameter(names = {"-resolveCoreferences"}, description = "Resolve Co-references for a given token", required = false)
private boolean resolveCoreferences = false;
private JCas jCas;
@Parameter(names = {"-name"}, description = "The name of the extractor", required = false)
private String name;
public AbstractShortestPathFeatureExtractor(String options) throws UIMAException {
JCommander jCommander = new JCommander(this);
try {
// parse options
jCommander.parse(options.split(" "));
} catch (ParameterException e) {
StringBuilder out = new StringBuilder();
jCommander.setProgramName(this.getClass().getSimpleName());
jCommander.usage(out);
// We wrap this exception in a Runtime exception so that
// existing loaders that extend PigStorage don't break
throw new RuntimeException(e.getMessage() + "\n" + "In: " + options + "\n" + out.toString());
} catch (Exception e) {
throw new RuntimeException("Error initializing " + this.getClass().getSimpleName(), e);
}
}
| // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FoundFeature.java
// public class FoundFeature<T> {
//
// T entity1;
// T entity2;
//
// String pattern;
// String relation;
//
// public FoundFeature(T entity1, T entity2, String pattern) {
// this.entity1 = entity1;
// this.entity2 = entity2;
// this.pattern = pattern;
// }
//
//
// public String getRelation() {
// return relation;
// }
//
// public void setRelation(String relation) {
// this.relation = relation;
// }
//
// public T getEntity1() {
// return entity1;
// }
//
// public void setEntity1(T entity1) {
// this.entity1 = entity1;
// }
//
// public T getEntity2() {
// return entity2;
// }
//
// public void setEntity2(T entity2) {
// this.entity2 = entity2;
// }
//
// public String getPattern() {
// return pattern;
// }
//
// public void setPattern(String pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public String toString() {
// return "FoundFeature{" +
// "entity1=" + transformToString(entity1) +
// ", entity2=" + transformToString(entity2) +
// ", pattern='" + pattern + '\'' +
// ", relation='" + relation + '\'' +
// '}';
// }
//
// private static <T> String transformToString(T input) {
// if(input instanceof Annotation) {
// return ((Annotation) input).getCoveredText();
// } else {
// return input.toString();
// }
// }
// }
//
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/util/JCommanderClassConverter.java
// public class JCommanderClassConverter extends BaseConverter<Class> {
//
// public JCommanderClassConverter(String optionName) {
// super(optionName);
// }
//
// @Override
// public Class convert(String value) {
// try {
// return Class.forName(value);
// } catch (ClassNotFoundException e) {
// throw new ParameterException(getErrorString(value, "a class"));
// }
// }
// }
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/features/detector/AbstractShortestPathFeatureExtractor.java
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.O;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import de.tudarmstadt.ukp.dkpro.core.api.syntax.type.dependency.Dependency;
import edu.tuberlin.dima.textmining.jedi.core.model.FoundFeature;
import edu.tuberlin.dima.textmining.jedi.core.util.JCommanderClassConverter;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.tcas.Annotation;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.graph.SimpleGraph;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package edu.tuberlin.dima.textmining.jedi.core.features.detector;
/**
*/
public abstract class AbstractShortestPathFeatureExtractor {
@Parameter(names = {"-lemmatize"}, description = "Lemmatize the pattern to remove times", required = false)
private boolean lemmatize = false;
@Parameter(names = {"-pickupSimilar"}, description = "If set, the token is expanded left and right with tokens of the same selectionType", required = false)
private boolean pickupSimilar = false;
@Parameter(names = {"-collapseMentions"}, description = "If set, similar mentions are collapsed", required = false)
private boolean collapseMentions = false;
@Parameter(names = {"-selectionType"}, description = "Class of selection Type (e.g. Named Entity)", required = true, converter = JCommanderClassConverter.class)
private Class<? extends Annotation> selectionType;
@Parameter(names = {"-additionalSelectionType"}, description = "AdditionalClass of selection Type (e.g. Named Entity)", required = false, converter = JCommanderClassConverter.class)
private Class<? extends Annotation> additionalSelectionType;
@Parameter(names = {"-resolveCoreferences"}, description = "Resolve Co-references for a given token", required = false)
private boolean resolveCoreferences = false;
private JCas jCas;
@Parameter(names = {"-name"}, description = "The name of the extractor", required = false)
private String name;
public AbstractShortestPathFeatureExtractor(String options) throws UIMAException {
JCommander jCommander = new JCommander(this);
try {
// parse options
jCommander.parse(options.split(" "));
} catch (ParameterException e) {
StringBuilder out = new StringBuilder();
jCommander.setProgramName(this.getClass().getSimpleName());
jCommander.usage(out);
// We wrap this exception in a Runtime exception so that
// existing loaders that extend PigStorage don't break
throw new RuntimeException(e.getMessage() + "\n" + "In: " + options + "\n" + out.toString());
} catch (Exception e) {
throw new RuntimeException("Error initializing " + this.getClass().getSimpleName(), e);
}
}
| public final List<FoundFeature<Annotation>> exec(JCas xmlDocument) throws IOException { |
jkirsch/jedi | core/src/test/java/edu/tuberlin/dima/textmining/jedi/core/freebase/FreebaseHelperTest.java | // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FreebaseRelation.java
// public class FreebaseRelation {
//
// String domain;
// String range;
//
// List<String> domainTypes;
// List<String> rangeTypes;
//
// public FreebaseRelation(String domain, String range, List<String> rangeTypes, List<String> domainTypes) {
// this.domain = domain;
// this.range = range;
// this.rangeTypes = rangeTypes;
// this.domainTypes = domainTypes;
// }
//
// public String getRange() {
// return range;
// }
//
// public String getDomain() {
// return domain;
// }
//
// public List<String> getRangeTypes() {
// return rangeTypes;
// }
//
// public List<String> getDomainTypes() {
// return domainTypes;
// }
//
// @Override
// public String toString() {
// return "FreebaseRelation{" +
// "domain='" + domain + '\'' +
// ", range='" + range + '\'' +
// ", domainTypes=" + domainTypes +
// ", rangeTypes=" + rangeTypes +
// '}';
// }
// }
| import edu.tuberlin.dima.textmining.jedi.core.model.FreebaseRelation;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is; | package edu.tuberlin.dima.textmining.jedi.core.freebase;
public class FreebaseHelperTest {
@Test
public void testGetTopicForID() throws Exception {
FreebaseHelper freebaseHelper = new FreebaseHelper();
/*
{"pred":"/people/person/education./education/education/degree",
"sub":"/m/0g6g2m",
"obj":"/m/02h4rq6",
"evidences":[{"url":"http://en.wikipedia.org/wiki/Adam_Hecktman","snippet":"Prior to Microsoft, Adam was a consultant with Andersen Consulting for three years. While at Andersen Consulting, Adam worked with clients including those in financial services, government, and utilities. Adam received a ((NAM: Bachelor of Science)) in commerce and business administration from the University of Illinois at Urbana-Champaign. He also holds a Master of Business Administration degree."}],"judgments":[{"rater":"1701217270337547159","judgment":"yes"},{"rater":"16812935633072558077","judgment":"yes"},{"rater":"5521403179797574771","judgment":"yes"},{"rater":"8046943553957200519","judgment":"yes"},{"rater":"9448866739620283545","judgment":"yes"}]}
*/
FreebaseHelper.Entity subject = freebaseHelper.getNameForID("/m/0g6g2m");
System.out.println(subject);
subject = freebaseHelper.getNameForID("/m/047rcpg");
System.out.println(subject);
FreebaseHelper.Entity object = freebaseHelper.getNameForID("/m/02h4rq6");
System.out.println(object);
}
@Test
public void testReplacedTopic() throws Exception {
FreebaseHelper freebaseHelper = new FreebaseHelper();
final FreebaseHelper.Entity nameForID = freebaseHelper.getNameForID("/m/07mt8q3");
System.out.println(nameForID);
}
@Test
public void testErrorID() throws Exception {
FreebaseHelper freebaseHelper = new FreebaseHelper();
final FreebaseHelper.Entity nameForID = freebaseHelper.getNameForID("/m/0h6rm");
System.out.println(nameForID);
}
@Test
public void testGetTypes() throws Exception {
FreebaseHelper freebaseHelper = new FreebaseHelper();
| // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FreebaseRelation.java
// public class FreebaseRelation {
//
// String domain;
// String range;
//
// List<String> domainTypes;
// List<String> rangeTypes;
//
// public FreebaseRelation(String domain, String range, List<String> rangeTypes, List<String> domainTypes) {
// this.domain = domain;
// this.range = range;
// this.rangeTypes = rangeTypes;
// this.domainTypes = domainTypes;
// }
//
// public String getRange() {
// return range;
// }
//
// public String getDomain() {
// return domain;
// }
//
// public List<String> getRangeTypes() {
// return rangeTypes;
// }
//
// public List<String> getDomainTypes() {
// return domainTypes;
// }
//
// @Override
// public String toString() {
// return "FreebaseRelation{" +
// "domain='" + domain + '\'' +
// ", range='" + range + '\'' +
// ", domainTypes=" + domainTypes +
// ", rangeTypes=" + rangeTypes +
// '}';
// }
// }
// Path: core/src/test/java/edu/tuberlin/dima/textmining/jedi/core/freebase/FreebaseHelperTest.java
import edu.tuberlin.dima.textmining.jedi.core.model.FreebaseRelation;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.is;
package edu.tuberlin.dima.textmining.jedi.core.freebase;
public class FreebaseHelperTest {
@Test
public void testGetTopicForID() throws Exception {
FreebaseHelper freebaseHelper = new FreebaseHelper();
/*
{"pred":"/people/person/education./education/education/degree",
"sub":"/m/0g6g2m",
"obj":"/m/02h4rq6",
"evidences":[{"url":"http://en.wikipedia.org/wiki/Adam_Hecktman","snippet":"Prior to Microsoft, Adam was a consultant with Andersen Consulting for three years. While at Andersen Consulting, Adam worked with clients including those in financial services, government, and utilities. Adam received a ((NAM: Bachelor of Science)) in commerce and business administration from the University of Illinois at Urbana-Champaign. He also holds a Master of Business Administration degree."}],"judgments":[{"rater":"1701217270337547159","judgment":"yes"},{"rater":"16812935633072558077","judgment":"yes"},{"rater":"5521403179797574771","judgment":"yes"},{"rater":"8046943553957200519","judgment":"yes"},{"rater":"9448866739620283545","judgment":"yes"}]}
*/
FreebaseHelper.Entity subject = freebaseHelper.getNameForID("/m/0g6g2m");
System.out.println(subject);
subject = freebaseHelper.getNameForID("/m/047rcpg");
System.out.println(subject);
FreebaseHelper.Entity object = freebaseHelper.getNameForID("/m/02h4rq6");
System.out.println(object);
}
@Test
public void testReplacedTopic() throws Exception {
FreebaseHelper freebaseHelper = new FreebaseHelper();
final FreebaseHelper.Entity nameForID = freebaseHelper.getNameForID("/m/07mt8q3");
System.out.println(nameForID);
}
@Test
public void testErrorID() throws Exception {
FreebaseHelper freebaseHelper = new FreebaseHelper();
final FreebaseHelper.Entity nameForID = freebaseHelper.getNameForID("/m/0h6rm");
System.out.println(nameForID);
}
@Test
public void testGetTypes() throws Exception {
FreebaseHelper freebaseHelper = new FreebaseHelper();
| FreebaseRelation typesForRelationFromFreebase = freebaseHelper.getTypesForRelationFromFreebase("ns:people.person.education..education.education.degree"); |
jkirsch/jedi | core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/features/detector/AllPairsShortestPathFeatureExtractor.java | // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FoundFeature.java
// public class FoundFeature<T> {
//
// T entity1;
// T entity2;
//
// String pattern;
// String relation;
//
// public FoundFeature(T entity1, T entity2, String pattern) {
// this.entity1 = entity1;
// this.entity2 = entity2;
// this.pattern = pattern;
// }
//
//
// public String getRelation() {
// return relation;
// }
//
// public void setRelation(String relation) {
// this.relation = relation;
// }
//
// public T getEntity1() {
// return entity1;
// }
//
// public void setEntity1(T entity1) {
// this.entity1 = entity1;
// }
//
// public T getEntity2() {
// return entity2;
// }
//
// public void setEntity2(T entity2) {
// this.entity2 = entity2;
// }
//
// public String getPattern() {
// return pattern;
// }
//
// public void setPattern(String pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public String toString() {
// return "FoundFeature{" +
// "entity1=" + transformToString(entity1) +
// ", entity2=" + transformToString(entity2) +
// ", pattern='" + pattern + '\'' +
// ", relation='" + relation + '\'' +
// '}';
// }
//
// private static <T> String transformToString(T input) {
// if(input instanceof Annotation) {
// return ((Annotation) input).getCoveredText();
// } else {
// return input.toString();
// }
// }
// }
| import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
import com.google.common.primitives.Ints;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceChain;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceLink;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.CARD;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.O;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.PUNC;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import edu.tuberlin.dima.textmining.jedi.core.model.FoundFeature;
import org.apache.commons.lang.StringUtils;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.tcas.Annotation;
import org.jgrapht.DirectedGraph;
import org.jgrapht.GraphPath;
import org.jgrapht.Graphs;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;
import javax.annotation.Nullable;
import java.util.*; | package edu.tuberlin.dima.textmining.jedi.core.features.detector;
/**
*/
public class AllPairsShortestPathFeatureExtractor extends AbstractShortestPathFeatureExtractor {
public AllPairsShortestPathFeatureExtractor(String options) throws UIMAException {
super(options);
}
public AllPairsShortestPathFeatureExtractor(String options, DetectorType detectorType) throws UIMAException {
super(options);
setName(detectorType.name());
}
@Override | // Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/model/FoundFeature.java
// public class FoundFeature<T> {
//
// T entity1;
// T entity2;
//
// String pattern;
// String relation;
//
// public FoundFeature(T entity1, T entity2, String pattern) {
// this.entity1 = entity1;
// this.entity2 = entity2;
// this.pattern = pattern;
// }
//
//
// public String getRelation() {
// return relation;
// }
//
// public void setRelation(String relation) {
// this.relation = relation;
// }
//
// public T getEntity1() {
// return entity1;
// }
//
// public void setEntity1(T entity1) {
// this.entity1 = entity1;
// }
//
// public T getEntity2() {
// return entity2;
// }
//
// public void setEntity2(T entity2) {
// this.entity2 = entity2;
// }
//
// public String getPattern() {
// return pattern;
// }
//
// public void setPattern(String pattern) {
// this.pattern = pattern;
// }
//
// @Override
// public String toString() {
// return "FoundFeature{" +
// "entity1=" + transformToString(entity1) +
// ", entity2=" + transformToString(entity2) +
// ", pattern='" + pattern + '\'' +
// ", relation='" + relation + '\'' +
// '}';
// }
//
// private static <T> String transformToString(T input) {
// if(input instanceof Annotation) {
// return ((Annotation) input).getCoveredText();
// } else {
// return input.toString();
// }
// }
// }
// Path: core/src/main/java/edu/tuberlin/dima/textmining/jedi/core/features/detector/AllPairsShortestPathFeatureExtractor.java
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.*;
import com.google.common.primitives.Ints;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceChain;
import de.tudarmstadt.ukp.dkpro.core.api.coref.type.CoreferenceLink;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.CARD;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.O;
import de.tudarmstadt.ukp.dkpro.core.api.lexmorph.type.pos.PUNC;
import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Token;
import edu.tuberlin.dima.textmining.jedi.core.model.FoundFeature;
import org.apache.commons.lang.StringUtils;
import org.apache.uima.UIMAException;
import org.apache.uima.fit.util.JCasUtil;
import org.apache.uima.jcas.tcas.Annotation;
import org.jgrapht.DirectedGraph;
import org.jgrapht.GraphPath;
import org.jgrapht.Graphs;
import org.jgrapht.UndirectedGraph;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleDirectedGraph;
import javax.annotation.Nullable;
import java.util.*;
package edu.tuberlin.dima.textmining.jedi.core.features.detector;
/**
*/
public class AllPairsShortestPathFeatureExtractor extends AbstractShortestPathFeatureExtractor {
public AllPairsShortestPathFeatureExtractor(String options) throws UIMAException {
super(options);
}
public AllPairsShortestPathFeatureExtractor(String options, DetectorType detectorType) throws UIMAException {
super(options);
setName(detectorType.name());
}
@Override | public List<FoundFeature<Annotation>> getShortestPaths(UndirectedGraph<Token, DependencyEdge> graph) { |
junit-team/junit4 | src/test/java/org/junit/rules/TempFolderRuleTest.java | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertFalse(String message, boolean condition) {
// assertTrue(message, !condition);
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertTrue(String message, boolean condition) {
// if (!condition) {
// fail(message);
// }
// }
| import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.failureCountIs;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.junit.After;
import org.junit.AssumptionViolatedException;
import org.junit.Rule;
import org.junit.Test; | package org.junit.rules;
public class TempFolderRuleTest {
private static File[] createdFiles = new File[20];
public static class HasTempFolder {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
createdFiles[0] = folder.newFile("myfile.txt"); | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertFalse(String message, boolean condition) {
// assertTrue(message, !condition);
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertTrue(String message, boolean condition) {
// if (!condition) {
// fail(message);
// }
// }
// Path: src/test/java/org/junit/rules/TempFolderRuleTest.java
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.failureCountIs;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.junit.After;
import org.junit.AssumptionViolatedException;
import org.junit.Rule;
import org.junit.Test;
package org.junit.rules;
public class TempFolderRuleTest {
private static File[] createdFiles = new File[20];
public static class HasTempFolder {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
createdFiles[0] = folder.newFile("myfile.txt"); | assertTrue(createdFiles[0].exists()); |
junit-team/junit4 | src/test/java/org/junit/rules/TempFolderRuleTest.java | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertFalse(String message, boolean condition) {
// assertTrue(message, !condition);
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertTrue(String message, boolean condition) {
// if (!condition) {
// fail(message);
// }
// }
| import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.failureCountIs;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.junit.After;
import org.junit.AssumptionViolatedException;
import org.junit.Rule;
import org.junit.Test; | package org.junit.rules;
public class TempFolderRuleTest {
private static File[] createdFiles = new File[20];
public static class HasTempFolder {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
createdFiles[0] = folder.newFile("myfile.txt");
assertTrue(createdFiles[0].exists());
}
@Test
public void testTempFolderLocation() throws IOException {
File folderRoot = folder.getRoot();
String tmpRoot = System.getProperty("java.io.tmpdir");
assertTrue(folderRoot.toString().startsWith(tmpRoot));
}
}
@Test
public void tempFolderIsDeleted() {
assertThat(testResult(HasTempFolder.class), isSuccessful()); | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertFalse(String message, boolean condition) {
// assertTrue(message, !condition);
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertTrue(String message, boolean condition) {
// if (!condition) {
// fail(message);
// }
// }
// Path: src/test/java/org/junit/rules/TempFolderRuleTest.java
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.failureCountIs;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.junit.After;
import org.junit.AssumptionViolatedException;
import org.junit.Rule;
import org.junit.Test;
package org.junit.rules;
public class TempFolderRuleTest {
private static File[] createdFiles = new File[20];
public static class HasTempFolder {
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void testUsingTempFolder() throws IOException {
createdFiles[0] = folder.newFile("myfile.txt");
assertTrue(createdFiles[0].exists());
}
@Test
public void testTempFolderLocation() throws IOException {
File folderRoot = folder.getRoot();
String tmpRoot = System.getProperty("java.io.tmpdir");
assertTrue(folderRoot.toString().startsWith(tmpRoot));
}
}
@Test
public void tempFolderIsDeleted() {
assertThat(testResult(HasTempFolder.class), isSuccessful()); | assertFalse(createdFiles[0].exists()); |
junit-team/junit4 | src/test/java/org/junit/rules/TempFolderRuleTest.java | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertFalse(String message, boolean condition) {
// assertTrue(message, !condition);
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertTrue(String message, boolean condition) {
// if (!condition) {
// fail(message);
// }
// }
| import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.failureCountIs;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.junit.After;
import org.junit.AssumptionViolatedException;
import org.junit.Rule;
import org.junit.Test; | folder.delete();
assertFalse(file.exists());
assertFalse(folder.getRoot().exists());
}
@Test
public void recursiveDeleteFolderWithOneRandomElement() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
File file = folder.newFile();
folder.delete();
assertFalse(file.exists());
assertFalse(folder.getRoot().exists());
}
@Test
public void recursiveDeleteFolderWithZeroElements() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
folder.delete();
assertFalse(folder.getRoot().exists());
}
@Test
public void tempFolderIsOnlyAccessibleByOwner() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
Set<String> expectedPermissions = new TreeSet<String>(Arrays.asList("OWNER_READ", "OWNER_WRITE", "OWNER_EXECUTE"));
Set<String> actualPermissions = getPosixFilePermissions(folder.getRoot()); | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertFalse(String message, boolean condition) {
// assertTrue(message, !condition);
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertTrue(String message, boolean condition) {
// if (!condition) {
// fail(message);
// }
// }
// Path: src/test/java/org/junit/rules/TempFolderRuleTest.java
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.failureCountIs;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.junit.After;
import org.junit.AssumptionViolatedException;
import org.junit.Rule;
import org.junit.Test;
folder.delete();
assertFalse(file.exists());
assertFalse(folder.getRoot().exists());
}
@Test
public void recursiveDeleteFolderWithOneRandomElement() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
File file = folder.newFile();
folder.delete();
assertFalse(file.exists());
assertFalse(folder.getRoot().exists());
}
@Test
public void recursiveDeleteFolderWithZeroElements() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
folder.delete();
assertFalse(folder.getRoot().exists());
}
@Test
public void tempFolderIsOnlyAccessibleByOwner() throws IOException {
TemporaryFolder folder = new TemporaryFolder();
folder.create();
Set<String> expectedPermissions = new TreeSet<String>(Arrays.asList("OWNER_READ", "OWNER_WRITE", "OWNER_EXECUTE"));
Set<String> actualPermissions = getPosixFilePermissions(folder.getRoot()); | assertEquals(expectedPermissions, actualPermissions); |
junit-team/junit4 | src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java | // Path: src/main/java/org/junit/runners/model/MultipleFailureException.java
// public class MultipleFailureException extends Exception {
// private static final long serialVersionUID = 1L;
//
// /*
// * We have to use the f prefix until the next major release to ensure
// * serialization compatibility.
// * See https://github.com/junit-team/junit4/issues/976
// */
// private final List<Throwable> fErrors;
//
// public MultipleFailureException(List<Throwable> errors) {
// if (errors.isEmpty()) {
// throw new IllegalArgumentException(
// "List of Throwables must not be empty");
// }
// this.fErrors = new ArrayList<Throwable>(errors.size());
// for (Throwable error : errors) {
// if (error instanceof AssumptionViolatedException) {
// error = new TestCouldNotBeSkippedException((AssumptionViolatedException) error);
// }
// fErrors.add(error);
// }
// }
//
// public List<Throwable> getFailures() {
// return Collections.unmodifiableList(fErrors);
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder(
// String.format("There were %d errors:", fErrors.size()));
// for (Throwable e : fErrors) {
// sb.append(String.format("%n %s(%s)", e.getClass().getName(), e.getMessage()));
// }
// return sb.toString();
// }
//
// @Override
// public void printStackTrace() {
// for (Throwable e: fErrors) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void printStackTrace(PrintStream s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// @Override
// public void printStackTrace(PrintWriter s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// /**
// * Asserts that a list of throwables is empty. If it isn't empty,
// * will throw {@link MultipleFailureException} (if there are
// * multiple throwables in the list) or the first element in the list
// * (if there is only one element).
// *
// * @param errors list to check
// * @throws Exception or Error if the list is not empty
// */
// @SuppressWarnings("deprecation")
// public static void assertEmpty(List<Throwable> errors) throws Exception {
// if (errors.isEmpty()) {
// return;
// }
// if (errors.size() == 1) {
// throw Throwables.rethrowAsException(errors.get(0));
// }
//
// /*
// * Many places in the code are documented to throw
// * org.junit.internal.runners.model.MultipleFailureException.
// * That class now extends this one, so we throw the internal
// * exception in case developers have tests that catch
// * MultipleFailureException.
// */
// throw new org.junit.internal.runners.model.MultipleFailureException(errors);
// }
// }
| import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.internal.management.ManagementFactory;
import org.junit.internal.management.ThreadMXBean;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestTimedOutException; | private Throwable getResult(FutureTask<Throwable> task, Thread thread) {
try {
if (timeout > 0) {
return task.get(timeout, timeUnit);
} else {
return task.get();
}
} catch (InterruptedException e) {
return e; // caller will re-throw; no need to call Thread.interrupt()
} catch (ExecutionException e) {
// test failed; have caller re-throw the exception thrown by the test
return e.getCause();
} catch (TimeoutException e) {
return createTimeoutException(thread);
}
}
private Exception createTimeoutException(Thread thread) {
StackTraceElement[] stackTrace = thread.getStackTrace();
final Thread stuckThread = lookForStuckThread ? getStuckThread(thread) : null;
Exception currThreadException = new TestTimedOutException(timeout, timeUnit);
if (stackTrace != null) {
currThreadException.setStackTrace(stackTrace);
thread.interrupt();
}
if (stuckThread != null) {
Exception stuckThreadException =
new Exception("Appears to be stuck in thread " +
stuckThread.getName());
stuckThreadException.setStackTrace(getStackTrace(stuckThread)); | // Path: src/main/java/org/junit/runners/model/MultipleFailureException.java
// public class MultipleFailureException extends Exception {
// private static final long serialVersionUID = 1L;
//
// /*
// * We have to use the f prefix until the next major release to ensure
// * serialization compatibility.
// * See https://github.com/junit-team/junit4/issues/976
// */
// private final List<Throwable> fErrors;
//
// public MultipleFailureException(List<Throwable> errors) {
// if (errors.isEmpty()) {
// throw new IllegalArgumentException(
// "List of Throwables must not be empty");
// }
// this.fErrors = new ArrayList<Throwable>(errors.size());
// for (Throwable error : errors) {
// if (error instanceof AssumptionViolatedException) {
// error = new TestCouldNotBeSkippedException((AssumptionViolatedException) error);
// }
// fErrors.add(error);
// }
// }
//
// public List<Throwable> getFailures() {
// return Collections.unmodifiableList(fErrors);
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder(
// String.format("There were %d errors:", fErrors.size()));
// for (Throwable e : fErrors) {
// sb.append(String.format("%n %s(%s)", e.getClass().getName(), e.getMessage()));
// }
// return sb.toString();
// }
//
// @Override
// public void printStackTrace() {
// for (Throwable e: fErrors) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void printStackTrace(PrintStream s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// @Override
// public void printStackTrace(PrintWriter s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// /**
// * Asserts that a list of throwables is empty. If it isn't empty,
// * will throw {@link MultipleFailureException} (if there are
// * multiple throwables in the list) or the first element in the list
// * (if there is only one element).
// *
// * @param errors list to check
// * @throws Exception or Error if the list is not empty
// */
// @SuppressWarnings("deprecation")
// public static void assertEmpty(List<Throwable> errors) throws Exception {
// if (errors.isEmpty()) {
// return;
// }
// if (errors.size() == 1) {
// throw Throwables.rethrowAsException(errors.get(0));
// }
//
// /*
// * Many places in the code are documented to throw
// * org.junit.internal.runners.model.MultipleFailureException.
// * That class now extends this one, so we throw the internal
// * exception in case developers have tests that catch
// * MultipleFailureException.
// */
// throw new org.junit.internal.runners.model.MultipleFailureException(errors);
// }
// }
// Path: src/main/java/org/junit/internal/runners/statements/FailOnTimeout.java
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.internal.management.ManagementFactory;
import org.junit.internal.management.ThreadMXBean;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestTimedOutException;
private Throwable getResult(FutureTask<Throwable> task, Thread thread) {
try {
if (timeout > 0) {
return task.get(timeout, timeUnit);
} else {
return task.get();
}
} catch (InterruptedException e) {
return e; // caller will re-throw; no need to call Thread.interrupt()
} catch (ExecutionException e) {
// test failed; have caller re-throw the exception thrown by the test
return e.getCause();
} catch (TimeoutException e) {
return createTimeoutException(thread);
}
}
private Exception createTimeoutException(Thread thread) {
StackTraceElement[] stackTrace = thread.getStackTrace();
final Thread stuckThread = lookForStuckThread ? getStuckThread(thread) : null;
Exception currThreadException = new TestTimedOutException(timeout, timeUnit);
if (stackTrace != null) {
currThreadException.setStackTrace(stackTrace);
thread.interrupt();
}
if (stuckThread != null) {
Exception stuckThreadException =
new Exception("Appears to be stuck in thread " +
stuckThread.getName());
stuckThreadException.setStackTrace(getStackTrace(stuckThread)); | return new MultipleFailureException( |
junit-team/junit4 | src/main/java/org/junit/rules/ErrorCollector.java | // Path: src/main/java/org/junit/Assert.java
// public static <T extends Throwable> T assertThrows(Class<T> expectedThrowable,
// ThrowingRunnable runnable) {
// return assertThrows(null, expectedThrowable, runnable);
// }
//
// Path: src/main/java/org/junit/runners/model/MultipleFailureException.java
// public class MultipleFailureException extends Exception {
// private static final long serialVersionUID = 1L;
//
// /*
// * We have to use the f prefix until the next major release to ensure
// * serialization compatibility.
// * See https://github.com/junit-team/junit4/issues/976
// */
// private final List<Throwable> fErrors;
//
// public MultipleFailureException(List<Throwable> errors) {
// if (errors.isEmpty()) {
// throw new IllegalArgumentException(
// "List of Throwables must not be empty");
// }
// this.fErrors = new ArrayList<Throwable>(errors.size());
// for (Throwable error : errors) {
// if (error instanceof AssumptionViolatedException) {
// error = new TestCouldNotBeSkippedException((AssumptionViolatedException) error);
// }
// fErrors.add(error);
// }
// }
//
// public List<Throwable> getFailures() {
// return Collections.unmodifiableList(fErrors);
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder(
// String.format("There were %d errors:", fErrors.size()));
// for (Throwable e : fErrors) {
// sb.append(String.format("%n %s(%s)", e.getClass().getName(), e.getMessage()));
// }
// return sb.toString();
// }
//
// @Override
// public void printStackTrace() {
// for (Throwable e: fErrors) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void printStackTrace(PrintStream s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// @Override
// public void printStackTrace(PrintWriter s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// /**
// * Asserts that a list of throwables is empty. If it isn't empty,
// * will throw {@link MultipleFailureException} (if there are
// * multiple throwables in the list) or the first element in the list
// * (if there is only one element).
// *
// * @param errors list to check
// * @throws Exception or Error if the list is not empty
// */
// @SuppressWarnings("deprecation")
// public static void assertEmpty(List<Throwable> errors) throws Exception {
// if (errors.isEmpty()) {
// return;
// }
// if (errors.size() == 1) {
// throw Throwables.rethrowAsException(errors.get(0));
// }
//
// /*
// * Many places in the code are documented to throw
// * org.junit.internal.runners.model.MultipleFailureException.
// * That class now extends this one, so we throw the internal
// * exception in case developers have tests that catch
// * MultipleFailureException.
// */
// throw new org.junit.internal.runners.model.MultipleFailureException(errors);
// }
// }
| import static org.junit.Assert.assertThrows;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.function.ThrowingRunnable;
import org.junit.internal.AssumptionViolatedException;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.junit.runners.model.MultipleFailureException; | package org.junit.rules;
/**
* The ErrorCollector rule allows execution of a test to continue after the
* first problem is found (for example, to collect _all_ the incorrect rows in a
* table, and report them all at once):
*
* <pre>
* public static class UsesErrorCollectorTwice {
* @Rule
* public ErrorCollector collector= new ErrorCollector();
*
* @Test
* public void example() {
* collector.addError(new Throwable("first thing went wrong"));
* collector.addError(new Throwable("second thing went wrong"));
* collector.checkThat(getResult(), not(containsString("ERROR!")));
* // all lines will run, and then a combined failure logged at the end.
* }
* }
* </pre>
*
* @since 4.7
*/
public class ErrorCollector extends Verifier {
private List<Throwable> errors = new ArrayList<Throwable>();
@Override
protected void verify() throws Throwable { | // Path: src/main/java/org/junit/Assert.java
// public static <T extends Throwable> T assertThrows(Class<T> expectedThrowable,
// ThrowingRunnable runnable) {
// return assertThrows(null, expectedThrowable, runnable);
// }
//
// Path: src/main/java/org/junit/runners/model/MultipleFailureException.java
// public class MultipleFailureException extends Exception {
// private static final long serialVersionUID = 1L;
//
// /*
// * We have to use the f prefix until the next major release to ensure
// * serialization compatibility.
// * See https://github.com/junit-team/junit4/issues/976
// */
// private final List<Throwable> fErrors;
//
// public MultipleFailureException(List<Throwable> errors) {
// if (errors.isEmpty()) {
// throw new IllegalArgumentException(
// "List of Throwables must not be empty");
// }
// this.fErrors = new ArrayList<Throwable>(errors.size());
// for (Throwable error : errors) {
// if (error instanceof AssumptionViolatedException) {
// error = new TestCouldNotBeSkippedException((AssumptionViolatedException) error);
// }
// fErrors.add(error);
// }
// }
//
// public List<Throwable> getFailures() {
// return Collections.unmodifiableList(fErrors);
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder(
// String.format("There were %d errors:", fErrors.size()));
// for (Throwable e : fErrors) {
// sb.append(String.format("%n %s(%s)", e.getClass().getName(), e.getMessage()));
// }
// return sb.toString();
// }
//
// @Override
// public void printStackTrace() {
// for (Throwable e: fErrors) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void printStackTrace(PrintStream s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// @Override
// public void printStackTrace(PrintWriter s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// /**
// * Asserts that a list of throwables is empty. If it isn't empty,
// * will throw {@link MultipleFailureException} (if there are
// * multiple throwables in the list) or the first element in the list
// * (if there is only one element).
// *
// * @param errors list to check
// * @throws Exception or Error if the list is not empty
// */
// @SuppressWarnings("deprecation")
// public static void assertEmpty(List<Throwable> errors) throws Exception {
// if (errors.isEmpty()) {
// return;
// }
// if (errors.size() == 1) {
// throw Throwables.rethrowAsException(errors.get(0));
// }
//
// /*
// * Many places in the code are documented to throw
// * org.junit.internal.runners.model.MultipleFailureException.
// * That class now extends this one, so we throw the internal
// * exception in case developers have tests that catch
// * MultipleFailureException.
// */
// throw new org.junit.internal.runners.model.MultipleFailureException(errors);
// }
// }
// Path: src/main/java/org/junit/rules/ErrorCollector.java
import static org.junit.Assert.assertThrows;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.function.ThrowingRunnable;
import org.junit.internal.AssumptionViolatedException;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.junit.runners.model.MultipleFailureException;
package org.junit.rules;
/**
* The ErrorCollector rule allows execution of a test to continue after the
* first problem is found (for example, to collect _all_ the incorrect rows in a
* table, and report them all at once):
*
* <pre>
* public static class UsesErrorCollectorTwice {
* @Rule
* public ErrorCollector collector= new ErrorCollector();
*
* @Test
* public void example() {
* collector.addError(new Throwable("first thing went wrong"));
* collector.addError(new Throwable("second thing went wrong"));
* collector.checkThat(getResult(), not(containsString("ERROR!")));
* // all lines will run, and then a combined failure logged at the end.
* }
* }
* </pre>
*
* @since 4.7
*/
public class ErrorCollector extends Verifier {
private List<Throwable> errors = new ArrayList<Throwable>();
@Override
protected void verify() throws Throwable { | MultipleFailureException.assertEmpty(errors); |
junit-team/junit4 | src/main/java/org/junit/rules/ErrorCollector.java | // Path: src/main/java/org/junit/Assert.java
// public static <T extends Throwable> T assertThrows(Class<T> expectedThrowable,
// ThrowingRunnable runnable) {
// return assertThrows(null, expectedThrowable, runnable);
// }
//
// Path: src/main/java/org/junit/runners/model/MultipleFailureException.java
// public class MultipleFailureException extends Exception {
// private static final long serialVersionUID = 1L;
//
// /*
// * We have to use the f prefix until the next major release to ensure
// * serialization compatibility.
// * See https://github.com/junit-team/junit4/issues/976
// */
// private final List<Throwable> fErrors;
//
// public MultipleFailureException(List<Throwable> errors) {
// if (errors.isEmpty()) {
// throw new IllegalArgumentException(
// "List of Throwables must not be empty");
// }
// this.fErrors = new ArrayList<Throwable>(errors.size());
// for (Throwable error : errors) {
// if (error instanceof AssumptionViolatedException) {
// error = new TestCouldNotBeSkippedException((AssumptionViolatedException) error);
// }
// fErrors.add(error);
// }
// }
//
// public List<Throwable> getFailures() {
// return Collections.unmodifiableList(fErrors);
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder(
// String.format("There were %d errors:", fErrors.size()));
// for (Throwable e : fErrors) {
// sb.append(String.format("%n %s(%s)", e.getClass().getName(), e.getMessage()));
// }
// return sb.toString();
// }
//
// @Override
// public void printStackTrace() {
// for (Throwable e: fErrors) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void printStackTrace(PrintStream s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// @Override
// public void printStackTrace(PrintWriter s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// /**
// * Asserts that a list of throwables is empty. If it isn't empty,
// * will throw {@link MultipleFailureException} (if there are
// * multiple throwables in the list) or the first element in the list
// * (if there is only one element).
// *
// * @param errors list to check
// * @throws Exception or Error if the list is not empty
// */
// @SuppressWarnings("deprecation")
// public static void assertEmpty(List<Throwable> errors) throws Exception {
// if (errors.isEmpty()) {
// return;
// }
// if (errors.size() == 1) {
// throw Throwables.rethrowAsException(errors.get(0));
// }
//
// /*
// * Many places in the code are documented to throw
// * org.junit.internal.runners.model.MultipleFailureException.
// * That class now extends this one, so we throw the internal
// * exception in case developers have tests that catch
// * MultipleFailureException.
// */
// throw new org.junit.internal.runners.model.MultipleFailureException(errors);
// }
// }
| import static org.junit.Assert.assertThrows;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.function.ThrowingRunnable;
import org.junit.internal.AssumptionViolatedException;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.junit.runners.model.MultipleFailureException; | * Adds to the table the exception, if any, thrown from {@code callable}.
* Execution continues, but the test will fail at the end if
* {@code callable} threw an exception.
*/
public <T> T checkSucceeds(Callable<T> callable) {
try {
return callable.call();
} catch (AssumptionViolatedException e) {
AssertionError error = new AssertionError("Callable threw AssumptionViolatedException");
error.initCause(e);
addError(error);
return null;
} catch (Throwable e) {
addError(e);
return null;
}
}
/**
* Adds a failure to the table if {@code runnable} does not throw an
* exception of type {@code expectedThrowable} when executed.
* Execution continues, but the test will fail at the end if the runnable
* does not throw an exception, or if it throws a different exception.
*
* @param expectedThrowable the expected type of the exception
* @param runnable a function that is expected to throw an exception when executed
* @since 4.13
*/
public void checkThrows(Class<? extends Throwable> expectedThrowable, ThrowingRunnable runnable) {
try { | // Path: src/main/java/org/junit/Assert.java
// public static <T extends Throwable> T assertThrows(Class<T> expectedThrowable,
// ThrowingRunnable runnable) {
// return assertThrows(null, expectedThrowable, runnable);
// }
//
// Path: src/main/java/org/junit/runners/model/MultipleFailureException.java
// public class MultipleFailureException extends Exception {
// private static final long serialVersionUID = 1L;
//
// /*
// * We have to use the f prefix until the next major release to ensure
// * serialization compatibility.
// * See https://github.com/junit-team/junit4/issues/976
// */
// private final List<Throwable> fErrors;
//
// public MultipleFailureException(List<Throwable> errors) {
// if (errors.isEmpty()) {
// throw new IllegalArgumentException(
// "List of Throwables must not be empty");
// }
// this.fErrors = new ArrayList<Throwable>(errors.size());
// for (Throwable error : errors) {
// if (error instanceof AssumptionViolatedException) {
// error = new TestCouldNotBeSkippedException((AssumptionViolatedException) error);
// }
// fErrors.add(error);
// }
// }
//
// public List<Throwable> getFailures() {
// return Collections.unmodifiableList(fErrors);
// }
//
// @Override
// public String getMessage() {
// StringBuilder sb = new StringBuilder(
// String.format("There were %d errors:", fErrors.size()));
// for (Throwable e : fErrors) {
// sb.append(String.format("%n %s(%s)", e.getClass().getName(), e.getMessage()));
// }
// return sb.toString();
// }
//
// @Override
// public void printStackTrace() {
// for (Throwable e: fErrors) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void printStackTrace(PrintStream s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// @Override
// public void printStackTrace(PrintWriter s) {
// for (Throwable e: fErrors) {
// e.printStackTrace(s);
// }
// }
//
// /**
// * Asserts that a list of throwables is empty. If it isn't empty,
// * will throw {@link MultipleFailureException} (if there are
// * multiple throwables in the list) or the first element in the list
// * (if there is only one element).
// *
// * @param errors list to check
// * @throws Exception or Error if the list is not empty
// */
// @SuppressWarnings("deprecation")
// public static void assertEmpty(List<Throwable> errors) throws Exception {
// if (errors.isEmpty()) {
// return;
// }
// if (errors.size() == 1) {
// throw Throwables.rethrowAsException(errors.get(0));
// }
//
// /*
// * Many places in the code are documented to throw
// * org.junit.internal.runners.model.MultipleFailureException.
// * That class now extends this one, so we throw the internal
// * exception in case developers have tests that catch
// * MultipleFailureException.
// */
// throw new org.junit.internal.runners.model.MultipleFailureException(errors);
// }
// }
// Path: src/main/java/org/junit/rules/ErrorCollector.java
import static org.junit.Assert.assertThrows;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.function.ThrowingRunnable;
import org.junit.internal.AssumptionViolatedException;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.junit.runners.model.MultipleFailureException;
* Adds to the table the exception, if any, thrown from {@code callable}.
* Execution continues, but the test will fail at the end if
* {@code callable} threw an exception.
*/
public <T> T checkSucceeds(Callable<T> callable) {
try {
return callable.call();
} catch (AssumptionViolatedException e) {
AssertionError error = new AssertionError("Callable threw AssumptionViolatedException");
error.initCause(e);
addError(error);
return null;
} catch (Throwable e) {
addError(e);
return null;
}
}
/**
* Adds a failure to the table if {@code runnable} does not throw an
* exception of type {@code expectedThrowable} when executed.
* Execution continues, but the test will fail at the end if the runnable
* does not throw an exception, or if it throws a different exception.
*
* @param expectedThrowable the expected type of the exception
* @param runnable a function that is expected to throw an exception when executed
* @since 4.13
*/
public void checkThrows(Class<? extends Throwable> expectedThrowable, ThrowingRunnable runnable) {
try { | assertThrows(expectedThrowable, runnable); |
junit-team/junit4 | src/test/java/org/junit/tests/running/methods/AnnotationTest.java | // Path: src/main/java/org/junit/runner/JUnitCore.java
// public class JUnitCore {
// private final RunNotifier notifier = new RunNotifier();
//
// /**
// * Run the tests contained in the classes named in the <code>args</code>.
// * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.
// * Write feedback while tests are running and write
// * stack traces for all failed tests after the tests all complete.
// *
// * @param args names of classes in which to find tests to run
// */
// public static void main(String... args) {
// Result result = new JUnitCore().runMain(new RealSystem(), args);
// System.exit(result.wasSuccessful() ? 0 : 1);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Class<?>... classes) {
// return runClasses(defaultComputer(), classes);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param computer Helps construct Runners from classes
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Computer computer, Class<?>... classes) {
// return new JUnitCore().run(computer, classes);
// }
//
// /**
// * @param system system to run with
// * @param args from main()
// */
// Result runMain(JUnitSystem system, String... args) {
// system.out().println("JUnit version " + Version.id());
//
// JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args);
//
// RunListener listener = new TextListener(system);
// addListener(listener);
//
// return run(jUnitCommandLineParseResult.createRequest(defaultComputer()));
// }
//
// /**
// * @return the version number of this release
// */
// public String getVersion() {
// return Version.id();
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Class<?>... classes) {
// return run(defaultComputer(), classes);
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param computer Helps construct Runners from classes
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Computer computer, Class<?>... classes) {
// return run(Request.classes(computer, classes));
// }
//
// /**
// * Run all the tests contained in <code>request</code>.
// *
// * @param request the request describing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Request request) {
// return run(request.getRunner());
// }
//
// /**
// * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility.
// *
// * @param test the old-style test
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(junit.framework.Test test) {
// return run(new JUnit38ClassRunner(test));
// }
//
// /**
// * Do not use. Testing purposes only.
// */
// public Result run(Runner runner) {
// Result result = new Result();
// RunListener listener = result.createListener();
// notifier.addFirstListener(listener);
// try {
// notifier.fireTestRunStarted(runner.getDescription());
// runner.run(notifier);
// notifier.fireTestRunFinished(result);
// } finally {
// removeListener(listener);
// }
// return result;
// }
//
// /**
// * Add a listener to be notified as the tests run.
// *
// * @param listener the listener to add
// * @see org.junit.runner.notification.RunListener
// */
// public void addListener(RunListener listener) {
// notifier.addListener(listener);
// }
//
// /**
// * Remove a listener.
// *
// * @param listener the listener to remove
// */
// public void removeListener(RunListener listener) {
// notifier.removeListener(listener);
// }
//
// static Computer defaultComputer() {
// return new Computer();
// }
// }
| import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import java.util.Collection;
import java.util.HashSet;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4; | package org.junit.tests.running.methods;
public class AnnotationTest extends TestCase {
static boolean run;
@Override
public void setUp() {
run = false;
}
public static class SimpleTest {
@Test
public void success() {
run = true;
}
}
public void testAnnotatedMethod() throws Exception { | // Path: src/main/java/org/junit/runner/JUnitCore.java
// public class JUnitCore {
// private final RunNotifier notifier = new RunNotifier();
//
// /**
// * Run the tests contained in the classes named in the <code>args</code>.
// * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.
// * Write feedback while tests are running and write
// * stack traces for all failed tests after the tests all complete.
// *
// * @param args names of classes in which to find tests to run
// */
// public static void main(String... args) {
// Result result = new JUnitCore().runMain(new RealSystem(), args);
// System.exit(result.wasSuccessful() ? 0 : 1);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Class<?>... classes) {
// return runClasses(defaultComputer(), classes);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param computer Helps construct Runners from classes
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Computer computer, Class<?>... classes) {
// return new JUnitCore().run(computer, classes);
// }
//
// /**
// * @param system system to run with
// * @param args from main()
// */
// Result runMain(JUnitSystem system, String... args) {
// system.out().println("JUnit version " + Version.id());
//
// JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args);
//
// RunListener listener = new TextListener(system);
// addListener(listener);
//
// return run(jUnitCommandLineParseResult.createRequest(defaultComputer()));
// }
//
// /**
// * @return the version number of this release
// */
// public String getVersion() {
// return Version.id();
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Class<?>... classes) {
// return run(defaultComputer(), classes);
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param computer Helps construct Runners from classes
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Computer computer, Class<?>... classes) {
// return run(Request.classes(computer, classes));
// }
//
// /**
// * Run all the tests contained in <code>request</code>.
// *
// * @param request the request describing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Request request) {
// return run(request.getRunner());
// }
//
// /**
// * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility.
// *
// * @param test the old-style test
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(junit.framework.Test test) {
// return run(new JUnit38ClassRunner(test));
// }
//
// /**
// * Do not use. Testing purposes only.
// */
// public Result run(Runner runner) {
// Result result = new Result();
// RunListener listener = result.createListener();
// notifier.addFirstListener(listener);
// try {
// notifier.fireTestRunStarted(runner.getDescription());
// runner.run(notifier);
// notifier.fireTestRunFinished(result);
// } finally {
// removeListener(listener);
// }
// return result;
// }
//
// /**
// * Add a listener to be notified as the tests run.
// *
// * @param listener the listener to add
// * @see org.junit.runner.notification.RunListener
// */
// public void addListener(RunListener listener) {
// notifier.addListener(listener);
// }
//
// /**
// * Remove a listener.
// *
// * @param listener the listener to remove
// */
// public void removeListener(RunListener listener) {
// notifier.removeListener(listener);
// }
//
// static Computer defaultComputer() {
// return new Computer();
// }
// }
// Path: src/test/java/org/junit/tests/running/methods/AnnotationTest.java
import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.isSuccessful;
import java.util.Collection;
import java.util.HashSet;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
package org.junit.tests.running.methods;
public class AnnotationTest extends TestCase {
static boolean run;
@Override
public void setUp() {
run = false;
}
public static class SimpleTest {
@Test
public void success() {
run = true;
}
}
public void testAnnotatedMethod() throws Exception { | JUnitCore runner = new JUnitCore(); |
junit-team/junit4 | src/test/java/org/junit/tests/listening/ListenerTest.java | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
//
// Path: src/main/java/org/junit/runner/JUnitCore.java
// public class JUnitCore {
// private final RunNotifier notifier = new RunNotifier();
//
// /**
// * Run the tests contained in the classes named in the <code>args</code>.
// * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.
// * Write feedback while tests are running and write
// * stack traces for all failed tests after the tests all complete.
// *
// * @param args names of classes in which to find tests to run
// */
// public static void main(String... args) {
// Result result = new JUnitCore().runMain(new RealSystem(), args);
// System.exit(result.wasSuccessful() ? 0 : 1);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Class<?>... classes) {
// return runClasses(defaultComputer(), classes);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param computer Helps construct Runners from classes
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Computer computer, Class<?>... classes) {
// return new JUnitCore().run(computer, classes);
// }
//
// /**
// * @param system system to run with
// * @param args from main()
// */
// Result runMain(JUnitSystem system, String... args) {
// system.out().println("JUnit version " + Version.id());
//
// JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args);
//
// RunListener listener = new TextListener(system);
// addListener(listener);
//
// return run(jUnitCommandLineParseResult.createRequest(defaultComputer()));
// }
//
// /**
// * @return the version number of this release
// */
// public String getVersion() {
// return Version.id();
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Class<?>... classes) {
// return run(defaultComputer(), classes);
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param computer Helps construct Runners from classes
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Computer computer, Class<?>... classes) {
// return run(Request.classes(computer, classes));
// }
//
// /**
// * Run all the tests contained in <code>request</code>.
// *
// * @param request the request describing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Request request) {
// return run(request.getRunner());
// }
//
// /**
// * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility.
// *
// * @param test the old-style test
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(junit.framework.Test test) {
// return run(new JUnit38ClassRunner(test));
// }
//
// /**
// * Do not use. Testing purposes only.
// */
// public Result run(Runner runner) {
// Result result = new Result();
// RunListener listener = result.createListener();
// notifier.addFirstListener(listener);
// try {
// notifier.fireTestRunStarted(runner.getDescription());
// runner.run(notifier);
// notifier.fireTestRunFinished(result);
// } finally {
// removeListener(listener);
// }
// return result;
// }
//
// /**
// * Add a listener to be notified as the tests run.
// *
// * @param listener the listener to add
// * @see org.junit.runner.notification.RunListener
// */
// public void addListener(RunListener listener) {
// notifier.addListener(listener);
// }
//
// /**
// * Remove a listener.
// *
// * @param listener the listener to remove
// */
// public void removeListener(RunListener listener) {
// notifier.removeListener(listener);
// }
//
// static Computer defaultComputer() {
// return new Computer();
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.notification.RunListener; | package org.junit.tests.listening;
public class ListenerTest {
private static String log;
public static class OneTest {
@Test
public void nothing() {
}
}
@Test
public void notifyListenersInTheOrderInWhichTheyAreAdded() { | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
//
// Path: src/main/java/org/junit/runner/JUnitCore.java
// public class JUnitCore {
// private final RunNotifier notifier = new RunNotifier();
//
// /**
// * Run the tests contained in the classes named in the <code>args</code>.
// * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.
// * Write feedback while tests are running and write
// * stack traces for all failed tests after the tests all complete.
// *
// * @param args names of classes in which to find tests to run
// */
// public static void main(String... args) {
// Result result = new JUnitCore().runMain(new RealSystem(), args);
// System.exit(result.wasSuccessful() ? 0 : 1);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Class<?>... classes) {
// return runClasses(defaultComputer(), classes);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param computer Helps construct Runners from classes
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Computer computer, Class<?>... classes) {
// return new JUnitCore().run(computer, classes);
// }
//
// /**
// * @param system system to run with
// * @param args from main()
// */
// Result runMain(JUnitSystem system, String... args) {
// system.out().println("JUnit version " + Version.id());
//
// JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args);
//
// RunListener listener = new TextListener(system);
// addListener(listener);
//
// return run(jUnitCommandLineParseResult.createRequest(defaultComputer()));
// }
//
// /**
// * @return the version number of this release
// */
// public String getVersion() {
// return Version.id();
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Class<?>... classes) {
// return run(defaultComputer(), classes);
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param computer Helps construct Runners from classes
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Computer computer, Class<?>... classes) {
// return run(Request.classes(computer, classes));
// }
//
// /**
// * Run all the tests contained in <code>request</code>.
// *
// * @param request the request describing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Request request) {
// return run(request.getRunner());
// }
//
// /**
// * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility.
// *
// * @param test the old-style test
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(junit.framework.Test test) {
// return run(new JUnit38ClassRunner(test));
// }
//
// /**
// * Do not use. Testing purposes only.
// */
// public Result run(Runner runner) {
// Result result = new Result();
// RunListener listener = result.createListener();
// notifier.addFirstListener(listener);
// try {
// notifier.fireTestRunStarted(runner.getDescription());
// runner.run(notifier);
// notifier.fireTestRunFinished(result);
// } finally {
// removeListener(listener);
// }
// return result;
// }
//
// /**
// * Add a listener to be notified as the tests run.
// *
// * @param listener the listener to add
// * @see org.junit.runner.notification.RunListener
// */
// public void addListener(RunListener listener) {
// notifier.addListener(listener);
// }
//
// /**
// * Remove a listener.
// *
// * @param listener the listener to remove
// */
// public void removeListener(RunListener listener) {
// notifier.removeListener(listener);
// }
//
// static Computer defaultComputer() {
// return new Computer();
// }
// }
// Path: src/test/java/org/junit/tests/listening/ListenerTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.notification.RunListener;
package org.junit.tests.listening;
public class ListenerTest {
private static String log;
public static class OneTest {
@Test
public void nothing() {
}
}
@Test
public void notifyListenersInTheOrderInWhichTheyAreAdded() { | JUnitCore core = new JUnitCore(); |
junit-team/junit4 | src/test/java/org/junit/tests/listening/ListenerTest.java | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
//
// Path: src/main/java/org/junit/runner/JUnitCore.java
// public class JUnitCore {
// private final RunNotifier notifier = new RunNotifier();
//
// /**
// * Run the tests contained in the classes named in the <code>args</code>.
// * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.
// * Write feedback while tests are running and write
// * stack traces for all failed tests after the tests all complete.
// *
// * @param args names of classes in which to find tests to run
// */
// public static void main(String... args) {
// Result result = new JUnitCore().runMain(new RealSystem(), args);
// System.exit(result.wasSuccessful() ? 0 : 1);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Class<?>... classes) {
// return runClasses(defaultComputer(), classes);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param computer Helps construct Runners from classes
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Computer computer, Class<?>... classes) {
// return new JUnitCore().run(computer, classes);
// }
//
// /**
// * @param system system to run with
// * @param args from main()
// */
// Result runMain(JUnitSystem system, String... args) {
// system.out().println("JUnit version " + Version.id());
//
// JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args);
//
// RunListener listener = new TextListener(system);
// addListener(listener);
//
// return run(jUnitCommandLineParseResult.createRequest(defaultComputer()));
// }
//
// /**
// * @return the version number of this release
// */
// public String getVersion() {
// return Version.id();
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Class<?>... classes) {
// return run(defaultComputer(), classes);
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param computer Helps construct Runners from classes
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Computer computer, Class<?>... classes) {
// return run(Request.classes(computer, classes));
// }
//
// /**
// * Run all the tests contained in <code>request</code>.
// *
// * @param request the request describing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Request request) {
// return run(request.getRunner());
// }
//
// /**
// * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility.
// *
// * @param test the old-style test
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(junit.framework.Test test) {
// return run(new JUnit38ClassRunner(test));
// }
//
// /**
// * Do not use. Testing purposes only.
// */
// public Result run(Runner runner) {
// Result result = new Result();
// RunListener listener = result.createListener();
// notifier.addFirstListener(listener);
// try {
// notifier.fireTestRunStarted(runner.getDescription());
// runner.run(notifier);
// notifier.fireTestRunFinished(result);
// } finally {
// removeListener(listener);
// }
// return result;
// }
//
// /**
// * Add a listener to be notified as the tests run.
// *
// * @param listener the listener to add
// * @see org.junit.runner.notification.RunListener
// */
// public void addListener(RunListener listener) {
// notifier.addListener(listener);
// }
//
// /**
// * Remove a listener.
// *
// * @param listener the listener to remove
// */
// public void removeListener(RunListener listener) {
// notifier.removeListener(listener);
// }
//
// static Computer defaultComputer() {
// return new Computer();
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.notification.RunListener; | package org.junit.tests.listening;
public class ListenerTest {
private static String log;
public static class OneTest {
@Test
public void nothing() {
}
}
@Test
public void notifyListenersInTheOrderInWhichTheyAreAdded() {
JUnitCore core = new JUnitCore();
log = "";
core.addListener(new RunListener() {
@Override
public void testRunStarted(Description description) throws Exception {
log += "first ";
}
});
core.addListener(new RunListener() {
@Override
public void testRunStarted(Description description) throws Exception {
log += "second ";
}
});
core.run(OneTest.class); | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
//
// Path: src/main/java/org/junit/runner/JUnitCore.java
// public class JUnitCore {
// private final RunNotifier notifier = new RunNotifier();
//
// /**
// * Run the tests contained in the classes named in the <code>args</code>.
// * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.
// * Write feedback while tests are running and write
// * stack traces for all failed tests after the tests all complete.
// *
// * @param args names of classes in which to find tests to run
// */
// public static void main(String... args) {
// Result result = new JUnitCore().runMain(new RealSystem(), args);
// System.exit(result.wasSuccessful() ? 0 : 1);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Class<?>... classes) {
// return runClasses(defaultComputer(), classes);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param computer Helps construct Runners from classes
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Computer computer, Class<?>... classes) {
// return new JUnitCore().run(computer, classes);
// }
//
// /**
// * @param system system to run with
// * @param args from main()
// */
// Result runMain(JUnitSystem system, String... args) {
// system.out().println("JUnit version " + Version.id());
//
// JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args);
//
// RunListener listener = new TextListener(system);
// addListener(listener);
//
// return run(jUnitCommandLineParseResult.createRequest(defaultComputer()));
// }
//
// /**
// * @return the version number of this release
// */
// public String getVersion() {
// return Version.id();
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Class<?>... classes) {
// return run(defaultComputer(), classes);
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param computer Helps construct Runners from classes
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Computer computer, Class<?>... classes) {
// return run(Request.classes(computer, classes));
// }
//
// /**
// * Run all the tests contained in <code>request</code>.
// *
// * @param request the request describing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Request request) {
// return run(request.getRunner());
// }
//
// /**
// * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility.
// *
// * @param test the old-style test
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(junit.framework.Test test) {
// return run(new JUnit38ClassRunner(test));
// }
//
// /**
// * Do not use. Testing purposes only.
// */
// public Result run(Runner runner) {
// Result result = new Result();
// RunListener listener = result.createListener();
// notifier.addFirstListener(listener);
// try {
// notifier.fireTestRunStarted(runner.getDescription());
// runner.run(notifier);
// notifier.fireTestRunFinished(result);
// } finally {
// removeListener(listener);
// }
// return result;
// }
//
// /**
// * Add a listener to be notified as the tests run.
// *
// * @param listener the listener to add
// * @see org.junit.runner.notification.RunListener
// */
// public void addListener(RunListener listener) {
// notifier.addListener(listener);
// }
//
// /**
// * Remove a listener.
// *
// * @param listener the listener to remove
// */
// public void removeListener(RunListener listener) {
// notifier.removeListener(listener);
// }
//
// static Computer defaultComputer() {
// return new Computer();
// }
// }
// Path: src/test/java/org/junit/tests/listening/ListenerTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.JUnitCore;
import org.junit.runner.notification.RunListener;
package org.junit.tests.listening;
public class ListenerTest {
private static String log;
public static class OneTest {
@Test
public void nothing() {
}
}
@Test
public void notifyListenersInTheOrderInWhichTheyAreAdded() {
JUnitCore core = new JUnitCore();
log = "";
core.addListener(new RunListener() {
@Override
public void testRunStarted(Description description) throws Exception {
log += "first ";
}
});
core.addListener(new RunListener() {
@Override
public void testRunStarted(Description description) throws Exception {
log += "second ";
}
});
core.run(OneTest.class); | assertEquals("first second ", log); |
junit-team/junit4 | src/test/java/org/junit/experimental/categories/JavadocTest.java | // Path: src/main/java/org/junit/Assert.java
// @Deprecated
// public static <T> void assertThat(T actual, Matcher<? super T> matcher) {
// assertThat("", actual, matcher);
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertTrue(String message, boolean condition) {
// if (!condition) {
// fail(message);
// }
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void fail(String message) {
// if (message == null) {
// throw new AssertionError();
// }
// throw new AssertionError(message);
// }
//
// Path: src/main/java/org/junit/runner/JUnitCore.java
// public class JUnitCore {
// private final RunNotifier notifier = new RunNotifier();
//
// /**
// * Run the tests contained in the classes named in the <code>args</code>.
// * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.
// * Write feedback while tests are running and write
// * stack traces for all failed tests after the tests all complete.
// *
// * @param args names of classes in which to find tests to run
// */
// public static void main(String... args) {
// Result result = new JUnitCore().runMain(new RealSystem(), args);
// System.exit(result.wasSuccessful() ? 0 : 1);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Class<?>... classes) {
// return runClasses(defaultComputer(), classes);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param computer Helps construct Runners from classes
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Computer computer, Class<?>... classes) {
// return new JUnitCore().run(computer, classes);
// }
//
// /**
// * @param system system to run with
// * @param args from main()
// */
// Result runMain(JUnitSystem system, String... args) {
// system.out().println("JUnit version " + Version.id());
//
// JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args);
//
// RunListener listener = new TextListener(system);
// addListener(listener);
//
// return run(jUnitCommandLineParseResult.createRequest(defaultComputer()));
// }
//
// /**
// * @return the version number of this release
// */
// public String getVersion() {
// return Version.id();
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Class<?>... classes) {
// return run(defaultComputer(), classes);
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param computer Helps construct Runners from classes
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Computer computer, Class<?>... classes) {
// return run(Request.classes(computer, classes));
// }
//
// /**
// * Run all the tests contained in <code>request</code>.
// *
// * @param request the request describing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Request request) {
// return run(request.getRunner());
// }
//
// /**
// * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility.
// *
// * @param test the old-style test
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(junit.framework.Test test) {
// return run(new JUnit38ClassRunner(test));
// }
//
// /**
// * Do not use. Testing purposes only.
// */
// public Result run(Runner runner) {
// Result result = new Result();
// RunListener listener = result.createListener();
// notifier.addFirstListener(listener);
// try {
// notifier.fireTestRunStarted(runner.getDescription());
// runner.run(notifier);
// notifier.fireTestRunFinished(result);
// } finally {
// removeListener(listener);
// }
// return result;
// }
//
// /**
// * Add a listener to be notified as the tests run.
// *
// * @param listener the listener to add
// * @see org.junit.runner.notification.RunListener
// */
// public void addListener(RunListener listener) {
// notifier.addListener(listener);
// }
//
// /**
// * Remove a listener.
// *
// * @param listener the listener to remove
// */
// public void removeListener(RunListener listener) {
// notifier.removeListener(listener);
// }
//
// static Computer defaultComputer() {
// return new Computer();
// }
// }
| import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runners.Suite; | package org.junit.experimental.categories;
/**
* @author tibor17
* @version 4.12
* @since 4.12
*/
public class JavadocTest {
public static interface FastTests {}
public static interface SlowTests {}
public static interface SmokeTests {}
public static class A {
public void a() { | // Path: src/main/java/org/junit/Assert.java
// @Deprecated
// public static <T> void assertThat(T actual, Matcher<? super T> matcher) {
// assertThat("", actual, matcher);
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void assertTrue(String message, boolean condition) {
// if (!condition) {
// fail(message);
// }
// }
//
// Path: src/main/java/org/junit/Assert.java
// public static void fail(String message) {
// if (message == null) {
// throw new AssertionError();
// }
// throw new AssertionError(message);
// }
//
// Path: src/main/java/org/junit/runner/JUnitCore.java
// public class JUnitCore {
// private final RunNotifier notifier = new RunNotifier();
//
// /**
// * Run the tests contained in the classes named in the <code>args</code>.
// * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.
// * Write feedback while tests are running and write
// * stack traces for all failed tests after the tests all complete.
// *
// * @param args names of classes in which to find tests to run
// */
// public static void main(String... args) {
// Result result = new JUnitCore().runMain(new RealSystem(), args);
// System.exit(result.wasSuccessful() ? 0 : 1);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Class<?>... classes) {
// return runClasses(defaultComputer(), classes);
// }
//
// /**
// * Run the tests contained in <code>classes</code>. Write feedback while the tests
// * are running and write stack traces for all failed tests after all tests complete. This is
// * similar to {@link #main(String[])}, but intended to be used programmatically.
// *
// * @param computer Helps construct Runners from classes
// * @param classes Classes in which to find tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public static Result runClasses(Computer computer, Class<?>... classes) {
// return new JUnitCore().run(computer, classes);
// }
//
// /**
// * @param system system to run with
// * @param args from main()
// */
// Result runMain(JUnitSystem system, String... args) {
// system.out().println("JUnit version " + Version.id());
//
// JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args);
//
// RunListener listener = new TextListener(system);
// addListener(listener);
//
// return run(jUnitCommandLineParseResult.createRequest(defaultComputer()));
// }
//
// /**
// * @return the version number of this release
// */
// public String getVersion() {
// return Version.id();
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Class<?>... classes) {
// return run(defaultComputer(), classes);
// }
//
// /**
// * Run all the tests in <code>classes</code>.
// *
// * @param computer Helps construct Runners from classes
// * @param classes the classes containing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Computer computer, Class<?>... classes) {
// return run(Request.classes(computer, classes));
// }
//
// /**
// * Run all the tests contained in <code>request</code>.
// *
// * @param request the request describing tests
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(Request request) {
// return run(request.getRunner());
// }
//
// /**
// * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility.
// *
// * @param test the old-style test
// * @return a {@link Result} describing the details of the test run and the failed tests.
// */
// public Result run(junit.framework.Test test) {
// return run(new JUnit38ClassRunner(test));
// }
//
// /**
// * Do not use. Testing purposes only.
// */
// public Result run(Runner runner) {
// Result result = new Result();
// RunListener listener = result.createListener();
// notifier.addFirstListener(listener);
// try {
// notifier.fireTestRunStarted(runner.getDescription());
// runner.run(notifier);
// notifier.fireTestRunFinished(result);
// } finally {
// removeListener(listener);
// }
// return result;
// }
//
// /**
// * Add a listener to be notified as the tests run.
// *
// * @param listener the listener to add
// * @see org.junit.runner.notification.RunListener
// */
// public void addListener(RunListener listener) {
// notifier.addListener(listener);
// }
//
// /**
// * Remove a listener.
// *
// * @param listener the listener to remove
// */
// public void removeListener(RunListener listener) {
// notifier.removeListener(listener);
// }
//
// static Computer defaultComputer() {
// return new Computer();
// }
// }
// Path: src/test/java/org/junit/experimental/categories/JavadocTest.java
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
package org.junit.experimental.categories;
/**
* @author tibor17
* @version 4.12
* @since 4.12
*/
public class JavadocTest {
public static interface FastTests {}
public static interface SlowTests {}
public static interface SmokeTests {}
public static class A {
public void a() { | fail(); |
junit-team/junit4 | src/main/java/org/junit/runner/FilterFactories.java | // Path: src/main/java/org/junit/internal/Classes.java
// public class Classes {
//
// /**
// * Do not instantiate.
// * @deprecated will be private soon.
// */
// @Deprecated
// public Classes() {
// }
//
// /**
// * Returns Class.forName for {@code className} using the current thread's class loader.
// * If the current thread does not have a class loader, falls back to the class loader for
// * {@link Classes}.
// *
// * @param className Name of the class.
// */
// public static Class<?> getClass(String className) throws ClassNotFoundException {
// return getClass(className, Classes.class);
// }
//
// /**
// * Returns Class.forName for {@code className} using the current thread's class loader.
// * If the current thread does not have a class loader, falls back to the class loader for the
// * passed-in class.
// *
// * @param className Name of the class.
// * @param callingClass Class that is requesting a the class
// * @since 4.13
// */
// public static Class<?> getClass(String className, Class<?> callingClass) throws ClassNotFoundException {
// ClassLoader classLoader = currentThread().getContextClassLoader();
// return Class.forName(className, true, classLoader == null ? callingClass.getClassLoader() : classLoader);
// }
// }
| import org.junit.internal.Classes;
import org.junit.runner.FilterFactory.FilterNotCreatedException;
import org.junit.runner.manipulation.Filter;
| package org.junit.runner;
/**
* Utility class whose methods create a {@link FilterFactory}.
*/
class FilterFactories {
/**
* Creates a {@link Filter}.
*
* A filter specification is of the form "package.of.FilterFactory=args-to-filter-factory" or
* "package.of.FilterFactory".
*
* @param request the request that will be filtered
* @param filterSpec the filter specification
*/
public static Filter createFilterFromFilterSpec(Request request, String filterSpec)
throws FilterFactory.FilterNotCreatedException {
Description topLevelDescription = request.getRunner().getDescription();
String[] tuple;
if (filterSpec.contains("=")) {
tuple = filterSpec.split("=", 2);
} else {
tuple = new String[]{ filterSpec, "" };
}
return createFilter(tuple[0], new FilterFactoryParams(topLevelDescription, tuple[1]));
}
/**
* Creates a {@link Filter}.
*
* @param filterFactoryFqcn The fully qualified class name of the {@link FilterFactory}
* @param params The arguments to the {@link FilterFactory}
*/
public static Filter createFilter(String filterFactoryFqcn, FilterFactoryParams params)
throws FilterFactory.FilterNotCreatedException {
FilterFactory filterFactory = createFilterFactory(filterFactoryFqcn);
return filterFactory.createFilter(params);
}
/**
* Creates a {@link Filter}.
*
* @param filterFactoryClass The class of the {@link FilterFactory}
* @param params The arguments to the {@link FilterFactory}
*
*/
public static Filter createFilter(Class<? extends FilterFactory> filterFactoryClass, FilterFactoryParams params)
throws FilterFactory.FilterNotCreatedException {
FilterFactory filterFactory = createFilterFactory(filterFactoryClass);
return filterFactory.createFilter(params);
}
static FilterFactory createFilterFactory(String filterFactoryFqcn) throws FilterNotCreatedException {
Class<? extends FilterFactory> filterFactoryClass;
try {
| // Path: src/main/java/org/junit/internal/Classes.java
// public class Classes {
//
// /**
// * Do not instantiate.
// * @deprecated will be private soon.
// */
// @Deprecated
// public Classes() {
// }
//
// /**
// * Returns Class.forName for {@code className} using the current thread's class loader.
// * If the current thread does not have a class loader, falls back to the class loader for
// * {@link Classes}.
// *
// * @param className Name of the class.
// */
// public static Class<?> getClass(String className) throws ClassNotFoundException {
// return getClass(className, Classes.class);
// }
//
// /**
// * Returns Class.forName for {@code className} using the current thread's class loader.
// * If the current thread does not have a class loader, falls back to the class loader for the
// * passed-in class.
// *
// * @param className Name of the class.
// * @param callingClass Class that is requesting a the class
// * @since 4.13
// */
// public static Class<?> getClass(String className, Class<?> callingClass) throws ClassNotFoundException {
// ClassLoader classLoader = currentThread().getContextClassLoader();
// return Class.forName(className, true, classLoader == null ? callingClass.getClassLoader() : classLoader);
// }
// }
// Path: src/main/java/org/junit/runner/FilterFactories.java
import org.junit.internal.Classes;
import org.junit.runner.FilterFactory.FilterNotCreatedException;
import org.junit.runner.manipulation.Filter;
package org.junit.runner;
/**
* Utility class whose methods create a {@link FilterFactory}.
*/
class FilterFactories {
/**
* Creates a {@link Filter}.
*
* A filter specification is of the form "package.of.FilterFactory=args-to-filter-factory" or
* "package.of.FilterFactory".
*
* @param request the request that will be filtered
* @param filterSpec the filter specification
*/
public static Filter createFilterFromFilterSpec(Request request, String filterSpec)
throws FilterFactory.FilterNotCreatedException {
Description topLevelDescription = request.getRunner().getDescription();
String[] tuple;
if (filterSpec.contains("=")) {
tuple = filterSpec.split("=", 2);
} else {
tuple = new String[]{ filterSpec, "" };
}
return createFilter(tuple[0], new FilterFactoryParams(topLevelDescription, tuple[1]));
}
/**
* Creates a {@link Filter}.
*
* @param filterFactoryFqcn The fully qualified class name of the {@link FilterFactory}
* @param params The arguments to the {@link FilterFactory}
*/
public static Filter createFilter(String filterFactoryFqcn, FilterFactoryParams params)
throws FilterFactory.FilterNotCreatedException {
FilterFactory filterFactory = createFilterFactory(filterFactoryFqcn);
return filterFactory.createFilter(params);
}
/**
* Creates a {@link Filter}.
*
* @param filterFactoryClass The class of the {@link FilterFactory}
* @param params The arguments to the {@link FilterFactory}
*
*/
public static Filter createFilter(Class<? extends FilterFactory> filterFactoryClass, FilterFactoryParams params)
throws FilterFactory.FilterNotCreatedException {
FilterFactory filterFactory = createFilterFactory(filterFactoryClass);
return filterFactory.createFilter(params);
}
static FilterFactory createFilterFactory(String filterFactoryFqcn) throws FilterNotCreatedException {
Class<? extends FilterFactory> filterFactoryClass;
try {
| filterFactoryClass = Classes.getClass(filterFactoryFqcn).asSubclass(FilterFactory.class);
|
junit-team/junit4 | src/test/java/org/junit/tests/experimental/theories/runner/WithAutoGeneratedDataPoints.java | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.tests.experimental.theories.TheoryTestUtils.potentialAssignments;
import org.junit.Test;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.Theories;
import org.junit.runner.RunWith; | package org.junit.tests.experimental.theories.runner;
public class WithAutoGeneratedDataPoints {
private enum ENUM { VALUE, OTHER_VALUE, THIRD_VALUE }
@RunWith(Theories.class)
public static class TheoryTestClassWithAutogeneratedParameterValues {
public void theory(ENUM e) {
}
public void theory(boolean b) {
}
}
@Test
public void shouldAutomaticallyGenerateEnumDataPoints() throws Throwable { | // Path: src/main/java/org/junit/Assert.java
// public static void assertEquals(String message, Object expected,
// Object actual) {
// if (equalsRegardingNull(expected, actual)) {
// return;
// }
// if (expected instanceof String && actual instanceof String) {
// String cleanMessage = message == null ? "" : message;
// throw new ComparisonFailure(cleanMessage, (String) expected,
// (String) actual);
// } else {
// failNotEquals(message, expected, actual);
// }
// }
// Path: src/test/java/org/junit/tests/experimental/theories/runner/WithAutoGeneratedDataPoints.java
import static org.junit.Assert.assertEquals;
import static org.junit.tests.experimental.theories.TheoryTestUtils.potentialAssignments;
import org.junit.Test;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.Theories;
import org.junit.runner.RunWith;
package org.junit.tests.experimental.theories.runner;
public class WithAutoGeneratedDataPoints {
private enum ENUM { VALUE, OTHER_VALUE, THIRD_VALUE }
@RunWith(Theories.class)
public static class TheoryTestClassWithAutogeneratedParameterValues {
public void theory(ENUM e) {
}
public void theory(boolean b) {
}
}
@Test
public void shouldAutomaticallyGenerateEnumDataPoints() throws Throwable { | assertEquals(ENUM.values().length, potentialAssignments( |
junit-team/junit4 | src/main/java/org/junit/rules/ExpectedException.java | // Path: src/main/java/org/junit/Assert.java
// public static void fail(String message) {
// if (message == null) {
// throw new AssertionError();
// }
// throw new AssertionError(message);
// }
| import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.fail;
import static org.junit.internal.matchers.ThrowableCauseMatcher.hasCause;
import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.hamcrest.StringDescription;
import org.junit.AssumptionViolatedException;
import org.junit.runners.model.Statement; | private class ExpectedExceptionStatement extends Statement {
private final Statement next;
public ExpectedExceptionStatement(Statement base) {
next = base;
}
@Override
public void evaluate() throws Throwable {
try {
next.evaluate();
} catch (Throwable e) {
handleException(e);
return;
}
if (isAnyExceptionExpected()) {
failDueToMissingException();
}
}
}
private void handleException(Throwable e) throws Throwable {
if (isAnyExceptionExpected()) {
MatcherAssert.assertThat(e, matcherBuilder.build());
} else {
throw e;
}
}
private void failDueToMissingException() throws AssertionError { | // Path: src/main/java/org/junit/Assert.java
// public static void fail(String message) {
// if (message == null) {
// throw new AssertionError();
// }
// throw new AssertionError(message);
// }
// Path: src/main/java/org/junit/rules/ExpectedException.java
import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.fail;
import static org.junit.internal.matchers.ThrowableCauseMatcher.hasCause;
import static org.junit.internal.matchers.ThrowableMessageMatcher.hasMessage;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.hamcrest.StringDescription;
import org.junit.AssumptionViolatedException;
import org.junit.runners.model.Statement;
private class ExpectedExceptionStatement extends Statement {
private final Statement next;
public ExpectedExceptionStatement(Statement base) {
next = base;
}
@Override
public void evaluate() throws Throwable {
try {
next.evaluate();
} catch (Throwable e) {
handleException(e);
return;
}
if (isAnyExceptionExpected()) {
failDueToMissingException();
}
}
}
private void handleException(Throwable e) throws Throwable {
if (isAnyExceptionExpected()) {
MatcherAssert.assertThat(e, matcherBuilder.build());
} else {
throw e;
}
}
private void failDueToMissingException() throws AssertionError { | fail(missingExceptionMessage()); |
Simsilica/SiO2 | demos/bullet/src/main/java/com/simsilica/demo/bullet/WanderDriver.java | // Path: src/main/java/com/simsilica/sim/SimTime.java
// public class SimTime {
// private long frame;
// private long lastRealTime;
// private boolean rebase;
//
// /**
// * gameTime is the 0-based 'game time' that is adjusted based on
// * the advancement of 'real time' provided by update().
// */
// private long gameTime;
//
// private double tpf;
// private double invTimeScale = 1000000000.0; // nanos
// private double timeScale = 1.0 / invTimeScale;
//
// public SimTime() {
// }
//
// public void update( long realTime ) {
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// rebase = false;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// lastRealTime = realTime;
//
// frame++;
// tpf = timeDelta * timeScale;
// this.gameTime += timeDelta;
// }
//
// /**
// * Returns the SimTime version of the specified timestamp that
// * is compatible with what would normally be provided to update().
// * SimTime.getTime() will provide 'frame locked' timestamps that will
// * not update during a frame which is what the systems will want 99.99%
// * of the time. Rarely it is desirable to get a "real" timestamp that
// * is not locked to frames, usually as part of providing matching accurate
// * timesource information to something else that is trying to synch.
// */
// public long getUnlockedTime( long realTime ) {
// // Figure out what time would be if realTime were
// // passed to update.
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// return gameTime + timeDelta;
// }
//
// public long toSimTime( double seconds ) {
// return (long)(seconds * invTimeScale);
// }
//
// public long getFutureTime( double seconds ) {
// return gameTime + toSimTime(seconds);
// }
//
// public final double getTpf() {
// return tpf;
// }
//
// public final long getFrame() {
// return frame;
// }
//
// public final long getTime() {
// return gameTime;
// }
//
// /**
// * Force the game time to a certain value. Note that going backwards while
// * systems are running may have undesirable effects.
// * The next immediate call to getTime() will return the specified value.
// * If update() is called then getTime() will return this value plus whatever
// * time has passed since the last time update() was called.
// * This is primarily used as a way for games to preset the game time to
// * some known value, say when restoring a saved game or a persistent world.
// */
// public final void setCurrentTime( long time ) {
// this.gameTime = time;
// this.rebase = true;
// }
//
// public final double getTimeInSeconds() {
// return gameTime * timeScale;
// }
//
// public final double getTimeScale() {
// return timeScale;
// }
//
// public final long addMillis( long ms ) {
// return gameTime + ms * 1000000L;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "[tpf=" + getTpf() + ", seconds=" + getTimeInSeconds() + "]";
// }
// }
| import java.util.Random;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.math.*;
import com.simsilica.es.*;
import com.simsilica.sim.SimTime;
import com.simsilica.bullet.*;
| protected float calculateWanderSteer() {
// We do this by imagining a wheel in front of us that randomly
// turns left or right... we will steer towards wherever the 0 degree
// mark on the wheel happens to be in our field of view.
float volatility = 0.4f;
headingAngle += random.nextFloat() * volatility - (volatility * 0.499);
while( headingAngle > FastMath.TWO_PI ) {
headingAngle -= FastMath.TWO_PI;
}
while( headingAngle < -FastMath.TWO_PI ) {
headingAngle += FastMath.TWO_PI;
}
float sin = FastMath.sin(headingAngle);
float cos = FastMath.cos(headingAngle);
// Project it in front of us some distance
// The farther out, the less dramatic turning will be
cos += 10f;
// The heading is imaginary and already in local space...
Vector3f heading = new Vector3f(sin, 0, cos).normalizeLocal();
//Vector3f left = Vector3f.UNIT_X;
//System.out.println("Steer:" + heading.x + " headingAngle:" + headingAngle + " heading:" + heading);
return heading.x; //heading.dot(left);
}
@Override
| // Path: src/main/java/com/simsilica/sim/SimTime.java
// public class SimTime {
// private long frame;
// private long lastRealTime;
// private boolean rebase;
//
// /**
// * gameTime is the 0-based 'game time' that is adjusted based on
// * the advancement of 'real time' provided by update().
// */
// private long gameTime;
//
// private double tpf;
// private double invTimeScale = 1000000000.0; // nanos
// private double timeScale = 1.0 / invTimeScale;
//
// public SimTime() {
// }
//
// public void update( long realTime ) {
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// rebase = false;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// lastRealTime = realTime;
//
// frame++;
// tpf = timeDelta * timeScale;
// this.gameTime += timeDelta;
// }
//
// /**
// * Returns the SimTime version of the specified timestamp that
// * is compatible with what would normally be provided to update().
// * SimTime.getTime() will provide 'frame locked' timestamps that will
// * not update during a frame which is what the systems will want 99.99%
// * of the time. Rarely it is desirable to get a "real" timestamp that
// * is not locked to frames, usually as part of providing matching accurate
// * timesource information to something else that is trying to synch.
// */
// public long getUnlockedTime( long realTime ) {
// // Figure out what time would be if realTime were
// // passed to update.
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// return gameTime + timeDelta;
// }
//
// public long toSimTime( double seconds ) {
// return (long)(seconds * invTimeScale);
// }
//
// public long getFutureTime( double seconds ) {
// return gameTime + toSimTime(seconds);
// }
//
// public final double getTpf() {
// return tpf;
// }
//
// public final long getFrame() {
// return frame;
// }
//
// public final long getTime() {
// return gameTime;
// }
//
// /**
// * Force the game time to a certain value. Note that going backwards while
// * systems are running may have undesirable effects.
// * The next immediate call to getTime() will return the specified value.
// * If update() is called then getTime() will return this value plus whatever
// * time has passed since the last time update() was called.
// * This is primarily used as a way for games to preset the game time to
// * some known value, say when restoring a saved game or a persistent world.
// */
// public final void setCurrentTime( long time ) {
// this.gameTime = time;
// this.rebase = true;
// }
//
// public final double getTimeInSeconds() {
// return gameTime * timeScale;
// }
//
// public final double getTimeScale() {
// return timeScale;
// }
//
// public final long addMillis( long ms ) {
// return gameTime + ms * 1000000L;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "[tpf=" + getTpf() + ", seconds=" + getTimeInSeconds() + "]";
// }
// }
// Path: demos/bullet/src/main/java/com/simsilica/demo/bullet/WanderDriver.java
import java.util.Random;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.math.*;
import com.simsilica.es.*;
import com.simsilica.sim.SimTime;
import com.simsilica.bullet.*;
protected float calculateWanderSteer() {
// We do this by imagining a wheel in front of us that randomly
// turns left or right... we will steer towards wherever the 0 degree
// mark on the wheel happens to be in our field of view.
float volatility = 0.4f;
headingAngle += random.nextFloat() * volatility - (volatility * 0.499);
while( headingAngle > FastMath.TWO_PI ) {
headingAngle -= FastMath.TWO_PI;
}
while( headingAngle < -FastMath.TWO_PI ) {
headingAngle += FastMath.TWO_PI;
}
float sin = FastMath.sin(headingAngle);
float cos = FastMath.cos(headingAngle);
// Project it in front of us some distance
// The farther out, the less dramatic turning will be
cos += 10f;
// The heading is imaginary and already in local space...
Vector3f heading = new Vector3f(sin, 0, cos).normalizeLocal();
//Vector3f left = Vector3f.UNIT_X;
//System.out.println("Steer:" + heading.x + " headingAngle:" + headingAngle + " heading:" + heading);
return heading.x; //heading.dot(left);
}
@Override
| public void update( SimTime time, EntityRigidBody body ) {
|
Simsilica/SiO2 | src/main/java/com/simsilica/net/server/ChatHostedService.java | // Path: src/main/java/com/simsilica/net/ChatSession.java
// public interface ChatSession {
//
// /**
// * Sends a new message to the chat.
// */
// @Asynchronous
// public void sendMessage( String message );
//
// /**
// * Returns the list of players currently in the chat.
// */
// public List<String> getPlayerNames();
// }
//
// Path: src/main/java/com/simsilica/net/ChatSessionListener.java
// public interface ChatSessionListener {
//
// /**
// * Called when a new player has joined the chat.
// */
// @Asynchronous
// public void playerJoined( int clientId, String playerName );
//
// /**
// * Called when a player has sent a message to the chat.
// */
// @Asynchronous
// public void newMessage( int clientId, String playerName, String message );
//
// /**
// * Called when an existing player has left the chat.
// */
// @Asynchronous
// public void playerLeft( int clientId, String playerName );
//
// }
| import java.util.*;
import java.util.concurrent.*;
import org.slf4j.*;
import com.jme3.network.HostedConnection;
import com.jme3.network.MessageConnection;
import com.jme3.network.Server;
import com.jme3.network.service.AbstractHostedConnectionService;
import com.jme3.network.service.HostedServiceManager;
import com.jme3.network.service.rmi.RmiHostedService;
import com.jme3.network.service.rmi.RmiRegistry;
import com.simsilica.net.ChatSession;
import com.simsilica.net.ChatSessionListener;
| /*
* $Id$
*
* Copyright (c) 2016, Simsilica, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.simsilica.net.server;
/**
* HostedService providing a chat server for connected players. Some
* time during player connection setup, the game must start hosting
* and provide the player name in order for the client to participate.
*
* @author Paul Speed
*/
public class ChatHostedService extends AbstractHostedConnectionService {
static Logger log = LoggerFactory.getLogger(ChatHostedService.class);
private static final String ATTRIBUTE_SESSION = ChatHostedService.class.getName();
private RmiHostedService rmiService;
private int channel;
private List<ChatSessionImpl> players = new CopyOnWriteArrayList<>();
/**
* Creates a new chat service that will use the default reliable channel
* for reliable communication.
*/
public ChatHostedService() {
this(MessageConnection.CHANNEL_DEFAULT_RELIABLE);
}
/**
* Creates a new chat service that will use the specified channel
* for reliable communication.
*/
public ChatHostedService( int channel ) {
this.channel = channel;
setAutoHost(false);
}
protected ChatSessionImpl getChatSession( HostedConnection conn ) {
return conn.getAttribute(ATTRIBUTE_SESSION);
}
@Override
protected void onInitialize( HostedServiceManager s ) {
// Grab the RMI service so we can easily use it later
this.rmiService = getService(RmiHostedService.class);
if( rmiService == null ) {
throw new RuntimeException("ChatHostedService requires an RMI service.");
}
}
/**
* Starts hosting the chat services on the specified connection using
* a specified player name. This causes the player to 'enter' the chat
* room and will then be able to send/receive messages.
*/
public void startHostingOnConnection( HostedConnection conn, String playerName ) {
log.debug("startHostingOnConnection(" + conn + ")");
ChatSessionImpl session = new ChatSessionImpl(conn, playerName);
conn.setAttribute(ATTRIBUTE_SESSION, session);
// Expose the session as an RMI resource to the client
RmiRegistry rmi = rmiService.getRmiRegistry(conn);
| // Path: src/main/java/com/simsilica/net/ChatSession.java
// public interface ChatSession {
//
// /**
// * Sends a new message to the chat.
// */
// @Asynchronous
// public void sendMessage( String message );
//
// /**
// * Returns the list of players currently in the chat.
// */
// public List<String> getPlayerNames();
// }
//
// Path: src/main/java/com/simsilica/net/ChatSessionListener.java
// public interface ChatSessionListener {
//
// /**
// * Called when a new player has joined the chat.
// */
// @Asynchronous
// public void playerJoined( int clientId, String playerName );
//
// /**
// * Called when a player has sent a message to the chat.
// */
// @Asynchronous
// public void newMessage( int clientId, String playerName, String message );
//
// /**
// * Called when an existing player has left the chat.
// */
// @Asynchronous
// public void playerLeft( int clientId, String playerName );
//
// }
// Path: src/main/java/com/simsilica/net/server/ChatHostedService.java
import java.util.*;
import java.util.concurrent.*;
import org.slf4j.*;
import com.jme3.network.HostedConnection;
import com.jme3.network.MessageConnection;
import com.jme3.network.Server;
import com.jme3.network.service.AbstractHostedConnectionService;
import com.jme3.network.service.HostedServiceManager;
import com.jme3.network.service.rmi.RmiHostedService;
import com.jme3.network.service.rmi.RmiRegistry;
import com.simsilica.net.ChatSession;
import com.simsilica.net.ChatSessionListener;
/*
* $Id$
*
* Copyright (c) 2016, Simsilica, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.simsilica.net.server;
/**
* HostedService providing a chat server for connected players. Some
* time during player connection setup, the game must start hosting
* and provide the player name in order for the client to participate.
*
* @author Paul Speed
*/
public class ChatHostedService extends AbstractHostedConnectionService {
static Logger log = LoggerFactory.getLogger(ChatHostedService.class);
private static final String ATTRIBUTE_SESSION = ChatHostedService.class.getName();
private RmiHostedService rmiService;
private int channel;
private List<ChatSessionImpl> players = new CopyOnWriteArrayList<>();
/**
* Creates a new chat service that will use the default reliable channel
* for reliable communication.
*/
public ChatHostedService() {
this(MessageConnection.CHANNEL_DEFAULT_RELIABLE);
}
/**
* Creates a new chat service that will use the specified channel
* for reliable communication.
*/
public ChatHostedService( int channel ) {
this.channel = channel;
setAutoHost(false);
}
protected ChatSessionImpl getChatSession( HostedConnection conn ) {
return conn.getAttribute(ATTRIBUTE_SESSION);
}
@Override
protected void onInitialize( HostedServiceManager s ) {
// Grab the RMI service so we can easily use it later
this.rmiService = getService(RmiHostedService.class);
if( rmiService == null ) {
throw new RuntimeException("ChatHostedService requires an RMI service.");
}
}
/**
* Starts hosting the chat services on the specified connection using
* a specified player name. This causes the player to 'enter' the chat
* room and will then be able to send/receive messages.
*/
public void startHostingOnConnection( HostedConnection conn, String playerName ) {
log.debug("startHostingOnConnection(" + conn + ")");
ChatSessionImpl session = new ChatSessionImpl(conn, playerName);
conn.setAttribute(ATTRIBUTE_SESSION, session);
// Expose the session as an RMI resource to the client
RmiRegistry rmi = rmiService.getRmiRegistry(conn);
| rmi.share((byte)channel, session, ChatSession.class);
|
Simsilica/SiO2 | src/main/java/com/simsilica/net/server/ChatHostedService.java | // Path: src/main/java/com/simsilica/net/ChatSession.java
// public interface ChatSession {
//
// /**
// * Sends a new message to the chat.
// */
// @Asynchronous
// public void sendMessage( String message );
//
// /**
// * Returns the list of players currently in the chat.
// */
// public List<String> getPlayerNames();
// }
//
// Path: src/main/java/com/simsilica/net/ChatSessionListener.java
// public interface ChatSessionListener {
//
// /**
// * Called when a new player has joined the chat.
// */
// @Asynchronous
// public void playerJoined( int clientId, String playerName );
//
// /**
// * Called when a player has sent a message to the chat.
// */
// @Asynchronous
// public void newMessage( int clientId, String playerName, String message );
//
// /**
// * Called when an existing player has left the chat.
// */
// @Asynchronous
// public void playerLeft( int clientId, String playerName );
//
// }
| import java.util.*;
import java.util.concurrent.*;
import org.slf4j.*;
import com.jme3.network.HostedConnection;
import com.jme3.network.MessageConnection;
import com.jme3.network.Server;
import com.jme3.network.service.AbstractHostedConnectionService;
import com.jme3.network.service.HostedServiceManager;
import com.jme3.network.service.rmi.RmiHostedService;
import com.jme3.network.service.rmi.RmiRegistry;
import com.simsilica.net.ChatSession;
import com.simsilica.net.ChatSessionListener;
| // may call it and it will also be called during connection shutdown.
conn.setAttribute(ATTRIBUTE_SESSION, null);
// Remove player session from the active sessions list
players.remove(player);
// Send the leave event to other players
for( ChatSessionImpl chatter : players ) {
if( chatter == player ) {
// Don't send our enter event to ourselves
continue;
}
chatter.playerLeft(player.conn.getId(), player.name);
}
}
}
protected void postMessage( ChatSessionImpl from, String message ) {
log.info("chat> " + from.name + " said:" + message);
for( ChatSessionImpl chatter : players ) {
chatter.newMessage(from.conn.getId(), from.name, message);
}
}
/**
* The connection-specific 'host' for the ChatSession. For convenience
* this also implements the ChatSessionListener. Since the methods don't
* collide at all it's convenient for our other code not to have to worry
* about the internal delegate.
*/
| // Path: src/main/java/com/simsilica/net/ChatSession.java
// public interface ChatSession {
//
// /**
// * Sends a new message to the chat.
// */
// @Asynchronous
// public void sendMessage( String message );
//
// /**
// * Returns the list of players currently in the chat.
// */
// public List<String> getPlayerNames();
// }
//
// Path: src/main/java/com/simsilica/net/ChatSessionListener.java
// public interface ChatSessionListener {
//
// /**
// * Called when a new player has joined the chat.
// */
// @Asynchronous
// public void playerJoined( int clientId, String playerName );
//
// /**
// * Called when a player has sent a message to the chat.
// */
// @Asynchronous
// public void newMessage( int clientId, String playerName, String message );
//
// /**
// * Called when an existing player has left the chat.
// */
// @Asynchronous
// public void playerLeft( int clientId, String playerName );
//
// }
// Path: src/main/java/com/simsilica/net/server/ChatHostedService.java
import java.util.*;
import java.util.concurrent.*;
import org.slf4j.*;
import com.jme3.network.HostedConnection;
import com.jme3.network.MessageConnection;
import com.jme3.network.Server;
import com.jme3.network.service.AbstractHostedConnectionService;
import com.jme3.network.service.HostedServiceManager;
import com.jme3.network.service.rmi.RmiHostedService;
import com.jme3.network.service.rmi.RmiRegistry;
import com.simsilica.net.ChatSession;
import com.simsilica.net.ChatSessionListener;
// may call it and it will also be called during connection shutdown.
conn.setAttribute(ATTRIBUTE_SESSION, null);
// Remove player session from the active sessions list
players.remove(player);
// Send the leave event to other players
for( ChatSessionImpl chatter : players ) {
if( chatter == player ) {
// Don't send our enter event to ourselves
continue;
}
chatter.playerLeft(player.conn.getId(), player.name);
}
}
}
protected void postMessage( ChatSessionImpl from, String message ) {
log.info("chat> " + from.name + " said:" + message);
for( ChatSessionImpl chatter : players ) {
chatter.newMessage(from.conn.getId(), from.name, message);
}
}
/**
* The connection-specific 'host' for the ChatSession. For convenience
* this also implements the ChatSessionListener. Since the methods don't
* collide at all it's convenient for our other code not to have to worry
* about the internal delegate.
*/
| private class ChatSessionImpl implements ChatSession, ChatSessionListener {
|
Simsilica/SiO2 | extensions/bullet/src/main/java/com/simsilica/bullet/DefaultContactPublisher.java | // Path: src/main/java/com/simsilica/es/common/Decay.java
// public class Decay implements EntityComponent, PersistentComponent {
// private long startTime;
// private long endTime;
//
// public Decay() {
// }
//
// /**
// * Creates a decay component with a start/end time that can
// * provide things like time remaining and percent remaining.
// */
// public Decay( long startTime, long endTime ) {
// this.startTime = startTime;
// this.endTime = endTime;
// }
//
// /**
// * Creates a decay component with only an end time. getPercentRemaining()
// * will not work sensibly in this case.
// */
// public Decay( long endTime ) {
// this.startTime = endTime;
// this.endTime = endTime;
// }
//
// public static Decay duration( long startTime, long duration ) {
// return new Decay(startTime, startTime + duration);
// }
//
// public long getStartTime() {
// return startTime;
// }
//
// public long getEndTime() {
// return endTime;
// }
//
// public long getTimeRemaining( long time ) {
// return Math.max(0, endTime - time);
// }
//
// public boolean isDead( long time ) {
// return time >= endTime;
// }
//
// public double getPercentRemaining( long time ) {
// if( time >= endTime ) {
// return 0;
// }
// if( startTime == endTime ) {
// return 1;
// }
// long remain = endTime - time;
// double total = endTime - startTime;
// return remain / total;
// }
//
// @Override
// public String toString() {
// return "Decay[startTime=" + startTime + ", endTime=" + endTime + "]";
// }
// }
| import com.simsilica.es.*;
import com.simsilica.es.common.Decay;
import com.jme3.bullet.collision.*;
import com.jme3.math.*;
| // Calculate the energy of the collision
Vector3f v1 = (object1 instanceof EntityRigidBody) ? ((EntityRigidBody)object1).getLastVelocity() : Vector3f.ZERO;
Vector3f v2 = (object2 instanceof EntityRigidBody) ? ((EntityRigidBody)object2).getLastVelocity() : Vector3f.ZERO;
// Normal is always pointing towards object1 and away from object2... because
// normal comes from getNormalWorldOnB().
float dot1 = -normal.dot(v1);
float dot2 = normal.dot(v2);
energy = dot1 + dot2;
}
return Contact.create(object1, object2, wp, normal, energy);
}
@Override
public void collision( EntityPhysicsObject object1, EntityPhysicsObject object2, PhysicsCollisionEvent event ) {
//System.out.println("collision:" + object1 + " -> " + object2);
Contact c = createContact(object1, object2, event);
createEntity(c);
}
/**
* Called by the collision method to create the contact entity and populate its Contact
* and Decay components. Can be overridden by subclasses as needed to have different behavior.
* The default behavior sets a Decay component with no time so it will be removed when the
* decay system first detects it.
*/
protected EntityId createEntity( Contact c ) {
EntityId contactEntity = ed.createEntity();
| // Path: src/main/java/com/simsilica/es/common/Decay.java
// public class Decay implements EntityComponent, PersistentComponent {
// private long startTime;
// private long endTime;
//
// public Decay() {
// }
//
// /**
// * Creates a decay component with a start/end time that can
// * provide things like time remaining and percent remaining.
// */
// public Decay( long startTime, long endTime ) {
// this.startTime = startTime;
// this.endTime = endTime;
// }
//
// /**
// * Creates a decay component with only an end time. getPercentRemaining()
// * will not work sensibly in this case.
// */
// public Decay( long endTime ) {
// this.startTime = endTime;
// this.endTime = endTime;
// }
//
// public static Decay duration( long startTime, long duration ) {
// return new Decay(startTime, startTime + duration);
// }
//
// public long getStartTime() {
// return startTime;
// }
//
// public long getEndTime() {
// return endTime;
// }
//
// public long getTimeRemaining( long time ) {
// return Math.max(0, endTime - time);
// }
//
// public boolean isDead( long time ) {
// return time >= endTime;
// }
//
// public double getPercentRemaining( long time ) {
// if( time >= endTime ) {
// return 0;
// }
// if( startTime == endTime ) {
// return 1;
// }
// long remain = endTime - time;
// double total = endTime - startTime;
// return remain / total;
// }
//
// @Override
// public String toString() {
// return "Decay[startTime=" + startTime + ", endTime=" + endTime + "]";
// }
// }
// Path: extensions/bullet/src/main/java/com/simsilica/bullet/DefaultContactPublisher.java
import com.simsilica.es.*;
import com.simsilica.es.common.Decay;
import com.jme3.bullet.collision.*;
import com.jme3.math.*;
// Calculate the energy of the collision
Vector3f v1 = (object1 instanceof EntityRigidBody) ? ((EntityRigidBody)object1).getLastVelocity() : Vector3f.ZERO;
Vector3f v2 = (object2 instanceof EntityRigidBody) ? ((EntityRigidBody)object2).getLastVelocity() : Vector3f.ZERO;
// Normal is always pointing towards object1 and away from object2... because
// normal comes from getNormalWorldOnB().
float dot1 = -normal.dot(v1);
float dot2 = normal.dot(v2);
energy = dot1 + dot2;
}
return Contact.create(object1, object2, wp, normal, energy);
}
@Override
public void collision( EntityPhysicsObject object1, EntityPhysicsObject object2, PhysicsCollisionEvent event ) {
//System.out.println("collision:" + object1 + " -> " + object2);
Contact c = createContact(object1, object2, event);
createEntity(c);
}
/**
* Called by the collision method to create the contact entity and populate its Contact
* and Decay components. Can be overridden by subclasses as needed to have different behavior.
* The default behavior sets a Decay component with no time so it will be removed when the
* decay system first detects it.
*/
protected EntityId createEntity( Contact c ) {
EntityId contactEntity = ed.createEntity();
| ed.setComponents(contactEntity, c, new Decay());
|
Simsilica/SiO2 | src/main/java/com/simsilica/net/client/ChatClientService.java | // Path: src/main/java/com/simsilica/net/ChatSession.java
// public interface ChatSession {
//
// /**
// * Sends a new message to the chat.
// */
// @Asynchronous
// public void sendMessage( String message );
//
// /**
// * Returns the list of players currently in the chat.
// */
// public List<String> getPlayerNames();
// }
//
// Path: src/main/java/com/simsilica/net/ChatSessionListener.java
// public interface ChatSessionListener {
//
// /**
// * Called when a new player has joined the chat.
// */
// @Asynchronous
// public void playerJoined( int clientId, String playerName );
//
// /**
// * Called when a player has sent a message to the chat.
// */
// @Asynchronous
// public void newMessage( int clientId, String playerName, String message );
//
// /**
// * Called when an existing player has left the chat.
// */
// @Asynchronous
// public void playerLeft( int clientId, String playerName );
//
// }
| import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.*;
import com.jme3.network.MessageConnection;
import com.jme3.network.service.AbstractClientService;
import com.jme3.network.service.ClientServiceManager;
import com.jme3.network.service.rmi.RmiClientService;
import com.simsilica.net.ChatSession;
import com.simsilica.net.ChatSessionListener;
| /*
* $Id$
*
* Copyright (c) 2016, Simsilica, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.simsilica.net.client;
/**
* Client-side service providing access to the chat server.
* Register this with the SpiderMonkey Client's services to
* get chat service features.
*
* @author Paul Speed
*/
public class ChatClientService extends AbstractClientService
implements ChatSession {
static Logger log = LoggerFactory.getLogger(ChatClientService.class);
private RmiClientService rmiService;
private int channel;
private ChatSession delegate;
private String playerName;
private ChatSessionCallback sessionCallback = new ChatSessionCallback();
| // Path: src/main/java/com/simsilica/net/ChatSession.java
// public interface ChatSession {
//
// /**
// * Sends a new message to the chat.
// */
// @Asynchronous
// public void sendMessage( String message );
//
// /**
// * Returns the list of players currently in the chat.
// */
// public List<String> getPlayerNames();
// }
//
// Path: src/main/java/com/simsilica/net/ChatSessionListener.java
// public interface ChatSessionListener {
//
// /**
// * Called when a new player has joined the chat.
// */
// @Asynchronous
// public void playerJoined( int clientId, String playerName );
//
// /**
// * Called when a player has sent a message to the chat.
// */
// @Asynchronous
// public void newMessage( int clientId, String playerName, String message );
//
// /**
// * Called when an existing player has left the chat.
// */
// @Asynchronous
// public void playerLeft( int clientId, String playerName );
//
// }
// Path: src/main/java/com/simsilica/net/client/ChatClientService.java
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.*;
import com.jme3.network.MessageConnection;
import com.jme3.network.service.AbstractClientService;
import com.jme3.network.service.ClientServiceManager;
import com.jme3.network.service.rmi.RmiClientService;
import com.simsilica.net.ChatSession;
import com.simsilica.net.ChatSessionListener;
/*
* $Id$
*
* Copyright (c) 2016, Simsilica, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.simsilica.net.client;
/**
* Client-side service providing access to the chat server.
* Register this with the SpiderMonkey Client's services to
* get chat service features.
*
* @author Paul Speed
*/
public class ChatClientService extends AbstractClientService
implements ChatSession {
static Logger log = LoggerFactory.getLogger(ChatClientService.class);
private RmiClientService rmiService;
private int channel;
private ChatSession delegate;
private String playerName;
private ChatSessionCallback sessionCallback = new ChatSessionCallback();
| private List<ChatSessionListener> listeners = new CopyOnWriteArrayList<>();
|
Simsilica/SiO2 | src/main/java/com/simsilica/state/DebugHudState.java | // Path: src/main/java/com/simsilica/post/DefaultSceneProcessor.java
// public class DefaultSceneProcessor implements SceneProcessor {
//
// @Override
// public void initialize( RenderManager rm, ViewPort vp ) {
// }
//
// @Override
// public void reshape( ViewPort vp, int w, int h ) {
// }
//
// /**
// * Default implementation always returns true. Note
// * that this may prevent initialize() from ever being called.
// * Subclasses that wish to have proper lifecycle should return
// * a real value from this method.
// */
// @Override
// public boolean isInitialized() {
// return true;
// }
//
// @Override
// public void preFrame( float tpf ) {
// }
//
// @Override
// public void postQueue( RenderQueue rq ) {
// }
//
// @Override
// public void postFrame( FrameBuffer out ) {
// }
//
// @Override
// public void cleanup() {
// }
//
// @Override
// public void setProfiler( AppProfiler profiler ) {
// }
// }
| import java.util.HashMap;
import java.util.Map;
import org.slf4j.*;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.BaseAppState;
import com.jme3.math.Vector3f;
import com.jme3.post.SceneProcessor;
import com.jme3.renderer.Camera;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Node;
import com.jme3.util.SafeArrayList;
import com.simsilica.lemur.*;
import com.simsilica.lemur.component.BorderLayout;
import com.simsilica.lemur.component.SpringGridLayout;
import com.simsilica.lemur.core.*;
import com.simsilica.lemur.input.FunctionId;
import com.simsilica.lemur.style.ElementId;
import com.simsilica.post.DefaultSceneProcessor;
| screen.removeFromParent();
getHudViewPort().removeProcessor(reshapeListener);
}
private class DebugView {
String name;
VersionedReference<String> ref;
Label nameLabel;
Label label;
Location location;
public DebugView( String name, Location location, VersionedReference<String> ref ) {
this.name = name;
this.location = location;
this.ref = ref;
this.nameLabel = new Label(name + ": ", new ElementId("debug.name.label"));
this.label = new Label(ref.get(), new ElementId("debug.value.label"));
}
public void update() {
if( ref.update() ) {
label.setText(ref.get());
}
}
}
/**
* The only way I've found in JME to listen for reshape events
* is to hook in a scene processor.
*/
| // Path: src/main/java/com/simsilica/post/DefaultSceneProcessor.java
// public class DefaultSceneProcessor implements SceneProcessor {
//
// @Override
// public void initialize( RenderManager rm, ViewPort vp ) {
// }
//
// @Override
// public void reshape( ViewPort vp, int w, int h ) {
// }
//
// /**
// * Default implementation always returns true. Note
// * that this may prevent initialize() from ever being called.
// * Subclasses that wish to have proper lifecycle should return
// * a real value from this method.
// */
// @Override
// public boolean isInitialized() {
// return true;
// }
//
// @Override
// public void preFrame( float tpf ) {
// }
//
// @Override
// public void postQueue( RenderQueue rq ) {
// }
//
// @Override
// public void postFrame( FrameBuffer out ) {
// }
//
// @Override
// public void cleanup() {
// }
//
// @Override
// public void setProfiler( AppProfiler profiler ) {
// }
// }
// Path: src/main/java/com/simsilica/state/DebugHudState.java
import java.util.HashMap;
import java.util.Map;
import org.slf4j.*;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.BaseAppState;
import com.jme3.math.Vector3f;
import com.jme3.post.SceneProcessor;
import com.jme3.renderer.Camera;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Node;
import com.jme3.util.SafeArrayList;
import com.simsilica.lemur.*;
import com.simsilica.lemur.component.BorderLayout;
import com.simsilica.lemur.component.SpringGridLayout;
import com.simsilica.lemur.core.*;
import com.simsilica.lemur.input.FunctionId;
import com.simsilica.lemur.style.ElementId;
import com.simsilica.post.DefaultSceneProcessor;
screen.removeFromParent();
getHudViewPort().removeProcessor(reshapeListener);
}
private class DebugView {
String name;
VersionedReference<String> ref;
Label nameLabel;
Label label;
Location location;
public DebugView( String name, Location location, VersionedReference<String> ref ) {
this.name = name;
this.location = location;
this.ref = ref;
this.nameLabel = new Label(name + ": ", new ElementId("debug.name.label"));
this.label = new Label(ref.get(), new ElementId("debug.value.label"));
}
public void update() {
if( ref.update() ) {
label.setText(ref.get());
}
}
}
/**
* The only way I've found in JME to listen for reshape events
* is to hook in a scene processor.
*/
| private class ReshapeListener extends DefaultSceneProcessor {
|
Simsilica/SiO2 | extensions/bullet/src/main/java/com/simsilica/bullet/debug/PhysicsDebugState.java | // Path: extensions/bullet/src/main/java/com/simsilica/bullet/CollisionShapes.java
// public interface CollisionShapes {
//
// /**
// * Registers the specific shape for the specified ShapeInfo such that
// * subsequent calls to loadShape(info) will resolve to that shape.
// * This can be used to bypass any (potentially expensive) collision
// * shape loading that the CollisionShapes implementation might be attempting
// * for registry misses.
// */
// public CollisionShape register( ShapeInfo info, CollisionShape shape );
//
// /**
// * Returns the collision shape for the specified shape info.
// * This will generally reuse CollisionShapes (without cloning) if they have
// * already been loaded or registered... though ultimately it is up to the
// * specific implementation of CollisionShapes.
// */
// public CollisionShape getShape( ShapeInfo shape );
// }
//
// Path: extensions/bullet/src/main/java/com/simsilica/bullet/ShapeInfo.java
// public class ShapeInfo implements EntityComponent {
//
// private int id;
//
// protected ShapeInfo() {
// }
//
// /**
// * Creates a new ShapeInfo component with the specified integer ID, usually
// * representing some specific string in the EntityData's string index.
// */
// public ShapeInfo( int id ) {
// this.id = id;
// }
//
// /**
// * Returns the integer ID of the collision shape associated with the
// * entity to which this component applies. Usually this is an ID in the
// * EntityData's strings table.
// */
// public int getShapeId() {
// return id;
// }
//
// /**
// * Returns the shape ID name if it exists in the EntityData's string table.
// */
// public String getShapeName( EntityData ed ) {
// return ed.getStrings().getString(id);
// }
//
// /**
// * Creates a ShapeInfo for the specified name by reusing or generating
// * a unique ID as required.
// */
// public static ShapeInfo create( String name, EntityData ed ) {
// return new ShapeInfo(ed.getStrings().getStringId(name, true));
// }
//
// /**
// * Returns the same string representation as toString() but if EntityData is
// * non-null then the ID will be resolved to a string. If EntityData is null
// * then this is the same as calling toString().
// */
// public String toString( EntityData ed ) {
// String s = ed == null ? String.valueOf(id) : getShapeName(ed);
// return getClass().getSimpleName() + "[" + s + "]";
// }
//
// @Override
// public String toString() {
// return toString(null);
// }
// }
| import java.util.*;
import org.slf4j.*;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.BaseAppState;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.util.DebugShapeFactory;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.*;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.*;
import com.jme3.scene.shape.Box;
import com.jme3.scene.debug.Arrow;
import com.jme3.util.SafeArrayList;
import com.simsilica.es.*;
import com.simsilica.lemur.GuiGlobals;
import com.simsilica.bullet.CollisionShapes;
import com.simsilica.bullet.ShapeInfo;
| /*
* $Id$
*
* Copyright (c) 2018, Simsilica, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.simsilica.bullet.debug;
/**
* Draws wireframe representations of the physics objects managed by the
* ES. This does not show any objects directly injected into the physics
* space. The application needs to add the DebugPhysicsListener to the
* BulletSystem for this state to show anything.
*
* @author Paul Speed
*/
public class PhysicsDebugState extends BaseAppState {
static Logger log = LoggerFactory.getLogger(PhysicsDebugState.class);
private EntityData ed;
| // Path: extensions/bullet/src/main/java/com/simsilica/bullet/CollisionShapes.java
// public interface CollisionShapes {
//
// /**
// * Registers the specific shape for the specified ShapeInfo such that
// * subsequent calls to loadShape(info) will resolve to that shape.
// * This can be used to bypass any (potentially expensive) collision
// * shape loading that the CollisionShapes implementation might be attempting
// * for registry misses.
// */
// public CollisionShape register( ShapeInfo info, CollisionShape shape );
//
// /**
// * Returns the collision shape for the specified shape info.
// * This will generally reuse CollisionShapes (without cloning) if they have
// * already been loaded or registered... though ultimately it is up to the
// * specific implementation of CollisionShapes.
// */
// public CollisionShape getShape( ShapeInfo shape );
// }
//
// Path: extensions/bullet/src/main/java/com/simsilica/bullet/ShapeInfo.java
// public class ShapeInfo implements EntityComponent {
//
// private int id;
//
// protected ShapeInfo() {
// }
//
// /**
// * Creates a new ShapeInfo component with the specified integer ID, usually
// * representing some specific string in the EntityData's string index.
// */
// public ShapeInfo( int id ) {
// this.id = id;
// }
//
// /**
// * Returns the integer ID of the collision shape associated with the
// * entity to which this component applies. Usually this is an ID in the
// * EntityData's strings table.
// */
// public int getShapeId() {
// return id;
// }
//
// /**
// * Returns the shape ID name if it exists in the EntityData's string table.
// */
// public String getShapeName( EntityData ed ) {
// return ed.getStrings().getString(id);
// }
//
// /**
// * Creates a ShapeInfo for the specified name by reusing or generating
// * a unique ID as required.
// */
// public static ShapeInfo create( String name, EntityData ed ) {
// return new ShapeInfo(ed.getStrings().getStringId(name, true));
// }
//
// /**
// * Returns the same string representation as toString() but if EntityData is
// * non-null then the ID will be resolved to a string. If EntityData is null
// * then this is the same as calling toString().
// */
// public String toString( EntityData ed ) {
// String s = ed == null ? String.valueOf(id) : getShapeName(ed);
// return getClass().getSimpleName() + "[" + s + "]";
// }
//
// @Override
// public String toString() {
// return toString(null);
// }
// }
// Path: extensions/bullet/src/main/java/com/simsilica/bullet/debug/PhysicsDebugState.java
import java.util.*;
import org.slf4j.*;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.BaseAppState;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.util.DebugShapeFactory;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.*;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.*;
import com.jme3.scene.shape.Box;
import com.jme3.scene.debug.Arrow;
import com.jme3.util.SafeArrayList;
import com.simsilica.es.*;
import com.simsilica.lemur.GuiGlobals;
import com.simsilica.bullet.CollisionShapes;
import com.simsilica.bullet.ShapeInfo;
/*
* $Id$
*
* Copyright (c) 2018, Simsilica, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.simsilica.bullet.debug;
/**
* Draws wireframe representations of the physics objects managed by the
* ES. This does not show any objects directly injected into the physics
* space. The application needs to add the DebugPhysicsListener to the
* BulletSystem for this state to show anything.
*
* @author Paul Speed
*/
public class PhysicsDebugState extends BaseAppState {
static Logger log = LoggerFactory.getLogger(PhysicsDebugState.class);
private EntityData ed;
| private CollisionShapes shapes;
|
Simsilica/SiO2 | extensions/bullet/src/main/java/com/simsilica/bullet/debug/PhysicsDebugState.java | // Path: extensions/bullet/src/main/java/com/simsilica/bullet/CollisionShapes.java
// public interface CollisionShapes {
//
// /**
// * Registers the specific shape for the specified ShapeInfo such that
// * subsequent calls to loadShape(info) will resolve to that shape.
// * This can be used to bypass any (potentially expensive) collision
// * shape loading that the CollisionShapes implementation might be attempting
// * for registry misses.
// */
// public CollisionShape register( ShapeInfo info, CollisionShape shape );
//
// /**
// * Returns the collision shape for the specified shape info.
// * This will generally reuse CollisionShapes (without cloning) if they have
// * already been loaded or registered... though ultimately it is up to the
// * specific implementation of CollisionShapes.
// */
// public CollisionShape getShape( ShapeInfo shape );
// }
//
// Path: extensions/bullet/src/main/java/com/simsilica/bullet/ShapeInfo.java
// public class ShapeInfo implements EntityComponent {
//
// private int id;
//
// protected ShapeInfo() {
// }
//
// /**
// * Creates a new ShapeInfo component with the specified integer ID, usually
// * representing some specific string in the EntityData's string index.
// */
// public ShapeInfo( int id ) {
// this.id = id;
// }
//
// /**
// * Returns the integer ID of the collision shape associated with the
// * entity to which this component applies. Usually this is an ID in the
// * EntityData's strings table.
// */
// public int getShapeId() {
// return id;
// }
//
// /**
// * Returns the shape ID name if it exists in the EntityData's string table.
// */
// public String getShapeName( EntityData ed ) {
// return ed.getStrings().getString(id);
// }
//
// /**
// * Creates a ShapeInfo for the specified name by reusing or generating
// * a unique ID as required.
// */
// public static ShapeInfo create( String name, EntityData ed ) {
// return new ShapeInfo(ed.getStrings().getStringId(name, true));
// }
//
// /**
// * Returns the same string representation as toString() but if EntityData is
// * non-null then the ID will be resolved to a string. If EntityData is null
// * then this is the same as calling toString().
// */
// public String toString( EntityData ed ) {
// String s = ed == null ? String.valueOf(id) : getShapeName(ed);
// return getClass().getSimpleName() + "[" + s + "]";
// }
//
// @Override
// public String toString() {
// return toString(null);
// }
// }
| import java.util.*;
import org.slf4j.*;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.BaseAppState;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.util.DebugShapeFactory;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.*;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.*;
import com.jme3.scene.shape.Box;
import com.jme3.scene.debug.Arrow;
import com.jme3.util.SafeArrayList;
import com.simsilica.es.*;
import com.simsilica.lemur.GuiGlobals;
import com.simsilica.bullet.CollisionShapes;
import com.simsilica.bullet.ShapeInfo;
| Spatial result = debugShapeCache.get(shape);
if( result == null && create ) {
result = DebugShapeFactory.getDebugShape(shape);
debugShapeCache.put(shape, result);
}
return result.clone();
} catch( Exception e ) {
log.error("Error creating debug shape for:" + id + " CollisionShape:" + shape);
Box b = new Box(0.1f, 0.1f, 0.1f);
Node node = new Node("errorShape");
Geometry geom;
geom = new Geometry("errorBox", b);
node.attachChild(geom);
geom = new Geometry("errorBox", b);
geom.rotate(FastMath.QUARTER_PI, FastMath.QUARTER_PI, 0);
node.attachChild(geom);
return node;
}
}
private class BodyDebugView {
private Entity entity;
private CollisionShape shape;
private Spatial spatial;
private int status = BodyDebugStatus.INACTIVE;
public BodyDebugView( Entity entity ) {
this.entity = entity;
| // Path: extensions/bullet/src/main/java/com/simsilica/bullet/CollisionShapes.java
// public interface CollisionShapes {
//
// /**
// * Registers the specific shape for the specified ShapeInfo such that
// * subsequent calls to loadShape(info) will resolve to that shape.
// * This can be used to bypass any (potentially expensive) collision
// * shape loading that the CollisionShapes implementation might be attempting
// * for registry misses.
// */
// public CollisionShape register( ShapeInfo info, CollisionShape shape );
//
// /**
// * Returns the collision shape for the specified shape info.
// * This will generally reuse CollisionShapes (without cloning) if they have
// * already been loaded or registered... though ultimately it is up to the
// * specific implementation of CollisionShapes.
// */
// public CollisionShape getShape( ShapeInfo shape );
// }
//
// Path: extensions/bullet/src/main/java/com/simsilica/bullet/ShapeInfo.java
// public class ShapeInfo implements EntityComponent {
//
// private int id;
//
// protected ShapeInfo() {
// }
//
// /**
// * Creates a new ShapeInfo component with the specified integer ID, usually
// * representing some specific string in the EntityData's string index.
// */
// public ShapeInfo( int id ) {
// this.id = id;
// }
//
// /**
// * Returns the integer ID of the collision shape associated with the
// * entity to which this component applies. Usually this is an ID in the
// * EntityData's strings table.
// */
// public int getShapeId() {
// return id;
// }
//
// /**
// * Returns the shape ID name if it exists in the EntityData's string table.
// */
// public String getShapeName( EntityData ed ) {
// return ed.getStrings().getString(id);
// }
//
// /**
// * Creates a ShapeInfo for the specified name by reusing or generating
// * a unique ID as required.
// */
// public static ShapeInfo create( String name, EntityData ed ) {
// return new ShapeInfo(ed.getStrings().getStringId(name, true));
// }
//
// /**
// * Returns the same string representation as toString() but if EntityData is
// * non-null then the ID will be resolved to a string. If EntityData is null
// * then this is the same as calling toString().
// */
// public String toString( EntityData ed ) {
// String s = ed == null ? String.valueOf(id) : getShapeName(ed);
// return getClass().getSimpleName() + "[" + s + "]";
// }
//
// @Override
// public String toString() {
// return toString(null);
// }
// }
// Path: extensions/bullet/src/main/java/com/simsilica/bullet/debug/PhysicsDebugState.java
import java.util.*;
import org.slf4j.*;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.BaseAppState;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.util.DebugShapeFactory;
import com.jme3.material.Material;
import com.jme3.material.RenderState.BlendMode;
import com.jme3.math.*;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.*;
import com.jme3.scene.shape.Box;
import com.jme3.scene.debug.Arrow;
import com.jme3.util.SafeArrayList;
import com.simsilica.es.*;
import com.simsilica.lemur.GuiGlobals;
import com.simsilica.bullet.CollisionShapes;
import com.simsilica.bullet.ShapeInfo;
Spatial result = debugShapeCache.get(shape);
if( result == null && create ) {
result = DebugShapeFactory.getDebugShape(shape);
debugShapeCache.put(shape, result);
}
return result.clone();
} catch( Exception e ) {
log.error("Error creating debug shape for:" + id + " CollisionShape:" + shape);
Box b = new Box(0.1f, 0.1f, 0.1f);
Node node = new Node("errorShape");
Geometry geom;
geom = new Geometry("errorBox", b);
node.attachChild(geom);
geom = new Geometry("errorBox", b);
geom.rotate(FastMath.QUARTER_PI, FastMath.QUARTER_PI, 0);
node.attachChild(geom);
return node;
}
}
private class BodyDebugView {
private Entity entity;
private CollisionShape shape;
private Spatial spatial;
private int status = BodyDebugStatus.INACTIVE;
public BodyDebugView( Entity entity ) {
this.entity = entity;
| this.shape = shapes.getShape(entity.get(ShapeInfo.class));
|
Simsilica/SiO2 | demos/bullet-char/src/main/java/com/simsilica/demo/bullet/PlatformPathDriver.java | // Path: src/main/java/com/simsilica/sim/SimTime.java
// public class SimTime {
// private long frame;
// private long lastRealTime;
// private boolean rebase;
//
// /**
// * gameTime is the 0-based 'game time' that is adjusted based on
// * the advancement of 'real time' provided by update().
// */
// private long gameTime;
//
// private double tpf;
// private double invTimeScale = 1000000000.0; // nanos
// private double timeScale = 1.0 / invTimeScale;
//
// public SimTime() {
// }
//
// public void update( long realTime ) {
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// rebase = false;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// lastRealTime = realTime;
//
// frame++;
// tpf = timeDelta * timeScale;
// this.gameTime += timeDelta;
// }
//
// /**
// * Returns the SimTime version of the specified timestamp that
// * is compatible with what would normally be provided to update().
// * SimTime.getTime() will provide 'frame locked' timestamps that will
// * not update during a frame which is what the systems will want 99.99%
// * of the time. Rarely it is desirable to get a "real" timestamp that
// * is not locked to frames, usually as part of providing matching accurate
// * timesource information to something else that is trying to synch.
// */
// public long getUnlockedTime( long realTime ) {
// // Figure out what time would be if realTime were
// // passed to update.
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// return gameTime + timeDelta;
// }
//
// public long toSimTime( double seconds ) {
// return (long)(seconds * invTimeScale);
// }
//
// public long getFutureTime( double seconds ) {
// return gameTime + toSimTime(seconds);
// }
//
// public final double getTpf() {
// return tpf;
// }
//
// public final long getFrame() {
// return frame;
// }
//
// public final long getTime() {
// return gameTime;
// }
//
// /**
// * Force the game time to a certain value. Note that going backwards while
// * systems are running may have undesirable effects.
// * The next immediate call to getTime() will return the specified value.
// * If update() is called then getTime() will return this value plus whatever
// * time has passed since the last time update() was called.
// * This is primarily used as a way for games to preset the game time to
// * some known value, say when restoring a saved game or a persistent world.
// */
// public final void setCurrentTime( long time ) {
// this.gameTime = time;
// this.rebase = true;
// }
//
// public final double getTimeInSeconds() {
// return gameTime * timeScale;
// }
//
// public final double getTimeScale() {
// return timeScale;
// }
//
// public final long addMillis( long ms ) {
// return gameTime + ms * 1000000L;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "[tpf=" + getTpf() + ", seconds=" + getTimeInSeconds() + "]";
// }
// }
| import java.util.Random;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.math.*;
import com.simsilica.es.*;
import com.simsilica.mathd.*;
import com.simsilica.sim.SimTime;
import com.simsilica.bullet.*;
|
public PlatformPathDriver( Entity entity ) {
this.entity = entity;
}
public void setPath( PlatformPath path ) {
this.path = path;
if( path == null ) {
return;
}
this.start = path.getStart().toVector3f();
this.end = path.getEnd().toVector3f();
this.position = new Vector3f();
}
public PlatformPath getPath() {
return path;
}
@Override
public void initialize( EntityRigidBody body ) {
this.body = body;
body.setKinematic(true);
}
@Override
public void addCollision( EntityPhysicsObject otherBody, PhysicsCollisionEvent event ) {
}
@Override
| // Path: src/main/java/com/simsilica/sim/SimTime.java
// public class SimTime {
// private long frame;
// private long lastRealTime;
// private boolean rebase;
//
// /**
// * gameTime is the 0-based 'game time' that is adjusted based on
// * the advancement of 'real time' provided by update().
// */
// private long gameTime;
//
// private double tpf;
// private double invTimeScale = 1000000000.0; // nanos
// private double timeScale = 1.0 / invTimeScale;
//
// public SimTime() {
// }
//
// public void update( long realTime ) {
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// rebase = false;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// lastRealTime = realTime;
//
// frame++;
// tpf = timeDelta * timeScale;
// this.gameTime += timeDelta;
// }
//
// /**
// * Returns the SimTime version of the specified timestamp that
// * is compatible with what would normally be provided to update().
// * SimTime.getTime() will provide 'frame locked' timestamps that will
// * not update during a frame which is what the systems will want 99.99%
// * of the time. Rarely it is desirable to get a "real" timestamp that
// * is not locked to frames, usually as part of providing matching accurate
// * timesource information to something else that is trying to synch.
// */
// public long getUnlockedTime( long realTime ) {
// // Figure out what time would be if realTime were
// // passed to update.
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// return gameTime + timeDelta;
// }
//
// public long toSimTime( double seconds ) {
// return (long)(seconds * invTimeScale);
// }
//
// public long getFutureTime( double seconds ) {
// return gameTime + toSimTime(seconds);
// }
//
// public final double getTpf() {
// return tpf;
// }
//
// public final long getFrame() {
// return frame;
// }
//
// public final long getTime() {
// return gameTime;
// }
//
// /**
// * Force the game time to a certain value. Note that going backwards while
// * systems are running may have undesirable effects.
// * The next immediate call to getTime() will return the specified value.
// * If update() is called then getTime() will return this value plus whatever
// * time has passed since the last time update() was called.
// * This is primarily used as a way for games to preset the game time to
// * some known value, say when restoring a saved game or a persistent world.
// */
// public final void setCurrentTime( long time ) {
// this.gameTime = time;
// this.rebase = true;
// }
//
// public final double getTimeInSeconds() {
// return gameTime * timeScale;
// }
//
// public final double getTimeScale() {
// return timeScale;
// }
//
// public final long addMillis( long ms ) {
// return gameTime + ms * 1000000L;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "[tpf=" + getTpf() + ", seconds=" + getTimeInSeconds() + "]";
// }
// }
// Path: demos/bullet-char/src/main/java/com/simsilica/demo/bullet/PlatformPathDriver.java
import java.util.Random;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.math.*;
import com.simsilica.es.*;
import com.simsilica.mathd.*;
import com.simsilica.sim.SimTime;
import com.simsilica.bullet.*;
public PlatformPathDriver( Entity entity ) {
this.entity = entity;
}
public void setPath( PlatformPath path ) {
this.path = path;
if( path == null ) {
return;
}
this.start = path.getStart().toVector3f();
this.end = path.getEnd().toVector3f();
this.position = new Vector3f();
}
public PlatformPath getPath() {
return path;
}
@Override
public void initialize( EntityRigidBody body ) {
this.body = body;
body.setKinematic(true);
}
@Override
public void addCollision( EntityPhysicsObject otherBody, PhysicsCollisionEvent event ) {
}
@Override
| public void update( SimTime time, EntityRigidBody body ) {
|
Simsilica/SiO2 | extensions/bullet/src/main/java/com/simsilica/bullet/ControlDriver.java | // Path: src/main/java/com/simsilica/sim/SimTime.java
// public class SimTime {
// private long frame;
// private long lastRealTime;
// private boolean rebase;
//
// /**
// * gameTime is the 0-based 'game time' that is adjusted based on
// * the advancement of 'real time' provided by update().
// */
// private long gameTime;
//
// private double tpf;
// private double invTimeScale = 1000000000.0; // nanos
// private double timeScale = 1.0 / invTimeScale;
//
// public SimTime() {
// }
//
// public void update( long realTime ) {
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// rebase = false;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// lastRealTime = realTime;
//
// frame++;
// tpf = timeDelta * timeScale;
// this.gameTime += timeDelta;
// }
//
// /**
// * Returns the SimTime version of the specified timestamp that
// * is compatible with what would normally be provided to update().
// * SimTime.getTime() will provide 'frame locked' timestamps that will
// * not update during a frame which is what the systems will want 99.99%
// * of the time. Rarely it is desirable to get a "real" timestamp that
// * is not locked to frames, usually as part of providing matching accurate
// * timesource information to something else that is trying to synch.
// */
// public long getUnlockedTime( long realTime ) {
// // Figure out what time would be if realTime were
// // passed to update.
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// return gameTime + timeDelta;
// }
//
// public long toSimTime( double seconds ) {
// return (long)(seconds * invTimeScale);
// }
//
// public long getFutureTime( double seconds ) {
// return gameTime + toSimTime(seconds);
// }
//
// public final double getTpf() {
// return tpf;
// }
//
// public final long getFrame() {
// return frame;
// }
//
// public final long getTime() {
// return gameTime;
// }
//
// /**
// * Force the game time to a certain value. Note that going backwards while
// * systems are running may have undesirable effects.
// * The next immediate call to getTime() will return the specified value.
// * If update() is called then getTime() will return this value plus whatever
// * time has passed since the last time update() was called.
// * This is primarily used as a way for games to preset the game time to
// * some known value, say when restoring a saved game or a persistent world.
// */
// public final void setCurrentTime( long time ) {
// this.gameTime = time;
// this.rebase = true;
// }
//
// public final double getTimeInSeconds() {
// return gameTime * timeScale;
// }
//
// public final double getTimeScale() {
// return timeScale;
// }
//
// public final long addMillis( long ms ) {
// return gameTime + ms * 1000000L;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "[tpf=" + getTpf() + ", seconds=" + getTimeInSeconds() + "]";
// }
// }
| import com.simsilica.es.EntityId;
import com.simsilica.sim.SimTime;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
| /*
* $Id$
*
* Copyright (c) 2018, Simsilica, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.simsilica.bullet;
/**
*
*
* @author Paul Speed
*/
public interface ControlDriver {
public void initialize( EntityRigidBody body );
| // Path: src/main/java/com/simsilica/sim/SimTime.java
// public class SimTime {
// private long frame;
// private long lastRealTime;
// private boolean rebase;
//
// /**
// * gameTime is the 0-based 'game time' that is adjusted based on
// * the advancement of 'real time' provided by update().
// */
// private long gameTime;
//
// private double tpf;
// private double invTimeScale = 1000000000.0; // nanos
// private double timeScale = 1.0 / invTimeScale;
//
// public SimTime() {
// }
//
// public void update( long realTime ) {
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// rebase = false;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// lastRealTime = realTime;
//
// frame++;
// tpf = timeDelta * timeScale;
// this.gameTime += timeDelta;
// }
//
// /**
// * Returns the SimTime version of the specified timestamp that
// * is compatible with what would normally be provided to update().
// * SimTime.getTime() will provide 'frame locked' timestamps that will
// * not update during a frame which is what the systems will want 99.99%
// * of the time. Rarely it is desirable to get a "real" timestamp that
// * is not locked to frames, usually as part of providing matching accurate
// * timesource information to something else that is trying to synch.
// */
// public long getUnlockedTime( long realTime ) {
// // Figure out what time would be if realTime were
// // passed to update.
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// return gameTime + timeDelta;
// }
//
// public long toSimTime( double seconds ) {
// return (long)(seconds * invTimeScale);
// }
//
// public long getFutureTime( double seconds ) {
// return gameTime + toSimTime(seconds);
// }
//
// public final double getTpf() {
// return tpf;
// }
//
// public final long getFrame() {
// return frame;
// }
//
// public final long getTime() {
// return gameTime;
// }
//
// /**
// * Force the game time to a certain value. Note that going backwards while
// * systems are running may have undesirable effects.
// * The next immediate call to getTime() will return the specified value.
// * If update() is called then getTime() will return this value plus whatever
// * time has passed since the last time update() was called.
// * This is primarily used as a way for games to preset the game time to
// * some known value, say when restoring a saved game or a persistent world.
// */
// public final void setCurrentTime( long time ) {
// this.gameTime = time;
// this.rebase = true;
// }
//
// public final double getTimeInSeconds() {
// return gameTime * timeScale;
// }
//
// public final double getTimeScale() {
// return timeScale;
// }
//
// public final long addMillis( long ms ) {
// return gameTime + ms * 1000000L;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "[tpf=" + getTpf() + ", seconds=" + getTimeInSeconds() + "]";
// }
// }
// Path: extensions/bullet/src/main/java/com/simsilica/bullet/ControlDriver.java
import com.simsilica.es.EntityId;
import com.simsilica.sim.SimTime;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
/*
* $Id$
*
* Copyright (c) 2018, Simsilica, LLC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.simsilica.bullet;
/**
*
*
* @author Paul Speed
*/
public interface ControlDriver {
public void initialize( EntityRigidBody body );
| public void update( SimTime time, EntityRigidBody body );
|
Simsilica/SiO2 | demos/bullet-char/src/main/java/com/simsilica/demo/bullet/CharInputDriver.java | // Path: src/main/java/com/simsilica/sim/SimTime.java
// public class SimTime {
// private long frame;
// private long lastRealTime;
// private boolean rebase;
//
// /**
// * gameTime is the 0-based 'game time' that is adjusted based on
// * the advancement of 'real time' provided by update().
// */
// private long gameTime;
//
// private double tpf;
// private double invTimeScale = 1000000000.0; // nanos
// private double timeScale = 1.0 / invTimeScale;
//
// public SimTime() {
// }
//
// public void update( long realTime ) {
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// rebase = false;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// lastRealTime = realTime;
//
// frame++;
// tpf = timeDelta * timeScale;
// this.gameTime += timeDelta;
// }
//
// /**
// * Returns the SimTime version of the specified timestamp that
// * is compatible with what would normally be provided to update().
// * SimTime.getTime() will provide 'frame locked' timestamps that will
// * not update during a frame which is what the systems will want 99.99%
// * of the time. Rarely it is desirable to get a "real" timestamp that
// * is not locked to frames, usually as part of providing matching accurate
// * timesource information to something else that is trying to synch.
// */
// public long getUnlockedTime( long realTime ) {
// // Figure out what time would be if realTime were
// // passed to update.
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// return gameTime + timeDelta;
// }
//
// public long toSimTime( double seconds ) {
// return (long)(seconds * invTimeScale);
// }
//
// public long getFutureTime( double seconds ) {
// return gameTime + toSimTime(seconds);
// }
//
// public final double getTpf() {
// return tpf;
// }
//
// public final long getFrame() {
// return frame;
// }
//
// public final long getTime() {
// return gameTime;
// }
//
// /**
// * Force the game time to a certain value. Note that going backwards while
// * systems are running may have undesirable effects.
// * The next immediate call to getTime() will return the specified value.
// * If update() is called then getTime() will return this value plus whatever
// * time has passed since the last time update() was called.
// * This is primarily used as a way for games to preset the game time to
// * some known value, say when restoring a saved game or a persistent world.
// */
// public final void setCurrentTime( long time ) {
// this.gameTime = time;
// this.rebase = true;
// }
//
// public final double getTimeInSeconds() {
// return gameTime * timeScale;
// }
//
// public final double getTimeScale() {
// return timeScale;
// }
//
// public final long addMillis( long ms ) {
// return gameTime + ms * 1000000L;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "[tpf=" + getTpf() + ", seconds=" + getTimeInSeconds() + "]";
// }
// }
| import java.util.Random;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.objects.PhysicsRigidBody;
import com.jme3.math.*;
import com.simsilica.es.*;
import com.simsilica.mathd.*;
import com.simsilica.sim.SimTime;
import com.simsilica.bullet.*;
| //System.out.println("++++ contact:" + otherBody);
// Just until we can tweak our ghost size more appropriately
canJump = true;
PhysicsRigidBody rb = (PhysicsRigidBody)otherBody;
rb.getLinearVelocity(vTemp);
groundVelocity.addLocal(vTemp);
groundContactCount++;
//System.out.println("Standing on:" + otherBody);
// Whatever the most recent ground entity is
groundEntity = otherBody.getId();
}
}
protected void calculateCollisionData() {
if( groundContactCount > 0 ) {
// Average the various ground velocities
groundVelocity.multLocal(1f/groundContactCount);
}
}
protected void invalidateCollisionData() {
groundEntity = null;
groundContactCount = 0;
groundVelocity.set(0, 0, 0);
canJump = false;
}
@Override
| // Path: src/main/java/com/simsilica/sim/SimTime.java
// public class SimTime {
// private long frame;
// private long lastRealTime;
// private boolean rebase;
//
// /**
// * gameTime is the 0-based 'game time' that is adjusted based on
// * the advancement of 'real time' provided by update().
// */
// private long gameTime;
//
// private double tpf;
// private double invTimeScale = 1000000000.0; // nanos
// private double timeScale = 1.0 / invTimeScale;
//
// public SimTime() {
// }
//
// public void update( long realTime ) {
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// rebase = false;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// lastRealTime = realTime;
//
// frame++;
// tpf = timeDelta * timeScale;
// this.gameTime += timeDelta;
// }
//
// /**
// * Returns the SimTime version of the specified timestamp that
// * is compatible with what would normally be provided to update().
// * SimTime.getTime() will provide 'frame locked' timestamps that will
// * not update during a frame which is what the systems will want 99.99%
// * of the time. Rarely it is desirable to get a "real" timestamp that
// * is not locked to frames, usually as part of providing matching accurate
// * timesource information to something else that is trying to synch.
// */
// public long getUnlockedTime( long realTime ) {
// // Figure out what time would be if realTime were
// // passed to update.
// long timeDelta;
// if( frame == 0 || rebase ) {
// timeDelta = 0;
// } else {
// timeDelta = realTime - lastRealTime;
// }
// return gameTime + timeDelta;
// }
//
// public long toSimTime( double seconds ) {
// return (long)(seconds * invTimeScale);
// }
//
// public long getFutureTime( double seconds ) {
// return gameTime + toSimTime(seconds);
// }
//
// public final double getTpf() {
// return tpf;
// }
//
// public final long getFrame() {
// return frame;
// }
//
// public final long getTime() {
// return gameTime;
// }
//
// /**
// * Force the game time to a certain value. Note that going backwards while
// * systems are running may have undesirable effects.
// * The next immediate call to getTime() will return the specified value.
// * If update() is called then getTime() will return this value plus whatever
// * time has passed since the last time update() was called.
// * This is primarily used as a way for games to preset the game time to
// * some known value, say when restoring a saved game or a persistent world.
// */
// public final void setCurrentTime( long time ) {
// this.gameTime = time;
// this.rebase = true;
// }
//
// public final double getTimeInSeconds() {
// return gameTime * timeScale;
// }
//
// public final double getTimeScale() {
// return timeScale;
// }
//
// public final long addMillis( long ms ) {
// return gameTime + ms * 1000000L;
// }
//
// @Override
// public String toString() {
// return getClass().getSimpleName() + "[tpf=" + getTpf() + ", seconds=" + getTimeInSeconds() + "]";
// }
// }
// Path: demos/bullet-char/src/main/java/com/simsilica/demo/bullet/CharInputDriver.java
import java.util.Random;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionObject;
import com.jme3.bullet.objects.PhysicsRigidBody;
import com.jme3.math.*;
import com.simsilica.es.*;
import com.simsilica.mathd.*;
import com.simsilica.sim.SimTime;
import com.simsilica.bullet.*;
//System.out.println("++++ contact:" + otherBody);
// Just until we can tweak our ghost size more appropriately
canJump = true;
PhysicsRigidBody rb = (PhysicsRigidBody)otherBody;
rb.getLinearVelocity(vTemp);
groundVelocity.addLocal(vTemp);
groundContactCount++;
//System.out.println("Standing on:" + otherBody);
// Whatever the most recent ground entity is
groundEntity = otherBody.getId();
}
}
protected void calculateCollisionData() {
if( groundContactCount > 0 ) {
// Average the various ground velocities
groundVelocity.multLocal(1f/groundContactCount);
}
}
protected void invalidateCollisionData() {
groundEntity = null;
groundContactCount = 0;
groundVelocity.set(0, 0, 0);
canJump = false;
}
@Override
| public void update( SimTime time, EntityRigidBody body ) {
|
Simsilica/SiO2 | extensions/bullet/src/main/java/com/simsilica/bullet/debug/ContactDebugState.java | // Path: extensions/bullet/src/main/java/com/simsilica/bullet/Contact.java
// public class Contact implements EntityComponent {
//
// private EntityId entity1;
// private int type1;
//
// private EntityId entity2;
// private int type2;
//
// private int typeMask;
//
// private Vector3f location;
// private Vector3f normal;
// private float energy;
//
// private Contact() {
// }
//
// public Contact( EntityId entity1, int type1, EntityId entity2, int type2,
// Vector3f location, Vector3f normal, float energy ) {
// this.entity1 = entity1;
// this.type1 = type1;
// this.entity2 = entity2;
// this.type2 = type2;
// this.typeMask = type1 | type2;
// this.location = location;
// this.normal = normal;
// this.energy = energy;
// }
//
// public static Contact create( EntityPhysicsObject object1, EntityPhysicsObject object2,
// Vector3f wp, Vector3f normal, float energy ) {
// Contact result = new Contact();
// if( object1 != null ) {
// result.entity1 = object1.getId();
// result.type1 = object1.getMassType();
// }
// if( object2 != null ) {
// result.entity2 = object2.getId();
// result.type2 = object2.getMassType();
// }
// result.typeMask = result.type1 | result.type2;
// result.location = wp;
// result.normal = normal;
// result.energy = energy;
//
// return result;
// }
//
// public EntityId getEntity1() {
// return entity1;
// }
//
// public int getType1() {
// return type1;
// }
//
// public EntityId getEntity2() {
// return entity2;
// }
//
// public int getType2() {
// return type2;
// }
//
// public int getTypeMask() {
// return typeMask;
// }
//
// public Vector3f getLocation() {
// return location;
// }
//
// public Vector3f getNormal() {
// return normal;
// }
//
// public float getEnergy() {
// return energy;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(getClass().getSimpleName())
// //.omitNullValues()
// .add("entity1", entity1)
// .add("type1", "0b" + Integer.toBinaryString(type1))
// .add("entity2", entity2)
// .add("type2", "0b" + Integer.toBinaryString(type2))
// .add("location", location)
// .add("normal", normal)
// .add("energy", energy)
// .add("typeMask", typeMask)
// .toString();
// }
// }
| import java.util.*;
import org.slf4j.*;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.BaseAppState;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.util.DebugShapeFactory;
import com.jme3.material.Material;
import com.jme3.material.MatParamOverride;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.*;
import com.jme3.scene.shape.Box;
import com.jme3.scene.debug.Arrow;
import com.jme3.shader.VarType;
import com.simsilica.es.*;
import com.simsilica.lemur.GuiGlobals;
import com.simsilica.bullet.Contact;
|
this.debugRoot = new Node("contactDebugRoot");
this.contacts = new ContactDebugContainer(ed);
}
@Override
protected void cleanup( Application app ) {
}
@Override
protected void onEnable() {
((SimpleApplication)getApplication()).getRootNode().attachChild(debugRoot);
contacts.start();
}
@Override
public void update( float tpf ) {
contacts.update();
updateContactViews();
}
@Override
protected void onDisable() {
contacts.stop();
debugRoot.removeFromParent();
}
protected void updateContactViews() {
// Try to reuse items when we can
int i = 0;
| // Path: extensions/bullet/src/main/java/com/simsilica/bullet/Contact.java
// public class Contact implements EntityComponent {
//
// private EntityId entity1;
// private int type1;
//
// private EntityId entity2;
// private int type2;
//
// private int typeMask;
//
// private Vector3f location;
// private Vector3f normal;
// private float energy;
//
// private Contact() {
// }
//
// public Contact( EntityId entity1, int type1, EntityId entity2, int type2,
// Vector3f location, Vector3f normal, float energy ) {
// this.entity1 = entity1;
// this.type1 = type1;
// this.entity2 = entity2;
// this.type2 = type2;
// this.typeMask = type1 | type2;
// this.location = location;
// this.normal = normal;
// this.energy = energy;
// }
//
// public static Contact create( EntityPhysicsObject object1, EntityPhysicsObject object2,
// Vector3f wp, Vector3f normal, float energy ) {
// Contact result = new Contact();
// if( object1 != null ) {
// result.entity1 = object1.getId();
// result.type1 = object1.getMassType();
// }
// if( object2 != null ) {
// result.entity2 = object2.getId();
// result.type2 = object2.getMassType();
// }
// result.typeMask = result.type1 | result.type2;
// result.location = wp;
// result.normal = normal;
// result.energy = energy;
//
// return result;
// }
//
// public EntityId getEntity1() {
// return entity1;
// }
//
// public int getType1() {
// return type1;
// }
//
// public EntityId getEntity2() {
// return entity2;
// }
//
// public int getType2() {
// return type2;
// }
//
// public int getTypeMask() {
// return typeMask;
// }
//
// public Vector3f getLocation() {
// return location;
// }
//
// public Vector3f getNormal() {
// return normal;
// }
//
// public float getEnergy() {
// return energy;
// }
//
// @Override
// public String toString() {
// return MoreObjects.toStringHelper(getClass().getSimpleName())
// //.omitNullValues()
// .add("entity1", entity1)
// .add("type1", "0b" + Integer.toBinaryString(type1))
// .add("entity2", entity2)
// .add("type2", "0b" + Integer.toBinaryString(type2))
// .add("location", location)
// .add("normal", normal)
// .add("energy", energy)
// .add("typeMask", typeMask)
// .toString();
// }
// }
// Path: extensions/bullet/src/main/java/com/simsilica/bullet/debug/ContactDebugState.java
import java.util.*;
import org.slf4j.*;
import com.jme3.app.Application;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.BaseAppState;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.util.DebugShapeFactory;
import com.jme3.material.Material;
import com.jme3.material.MatParamOverride;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.*;
import com.jme3.scene.shape.Box;
import com.jme3.scene.debug.Arrow;
import com.jme3.shader.VarType;
import com.simsilica.es.*;
import com.simsilica.lemur.GuiGlobals;
import com.simsilica.bullet.Contact;
this.debugRoot = new Node("contactDebugRoot");
this.contacts = new ContactDebugContainer(ed);
}
@Override
protected void cleanup( Application app ) {
}
@Override
protected void onEnable() {
((SimpleApplication)getApplication()).getRootNode().attachChild(debugRoot);
contacts.start();
}
@Override
public void update( float tpf ) {
contacts.update();
updateContactViews();
}
@Override
protected void onDisable() {
contacts.stop();
debugRoot.removeFromParent();
}
protected void updateContactViews() {
// Try to reuse items when we can
int i = 0;
| for( Contact c : contacts.getArray() ) {
|
pviotti/hybris | src/main/java/fr/eurecom/hybris/mds/Rmds.java | // Path: src/main/java/fr/eurecom/hybris/Hybris.java
// public class HybrisWatcher implements CuratorWatcher {
//
// private boolean changed = false;
// public boolean isChanged() { return this.changed; }
//
// /**
// * Process a notification sent by ZooKeeper
// * @see org.apache.curator.framework.api.CuratorWatcher#process(org.apache.zookeeper.WatchedEvent)
// */
// public void process(WatchedEvent event) throws Exception {
// this.changed = true;
// }
// }
//
// Path: src/main/java/fr/eurecom/hybris/mds/Metadata.java
// public static class Timestamp implements KryoSerializable {
//
// private int num;
// private String cid;
//
// public Timestamp() { }
// public Timestamp(int n, String c) {
// this.num = n;
// this.cid = c;
// }
//
// public static Timestamp parseString(String tsStr) {
// String[] tsParts = tsStr.split("_");
// int n = Integer.parseInt(tsParts[0]);
// String cid = tsParts[1];
// return new Timestamp(n, cid);
// }
//
// public int getNum() { return this.num; }
// public void setNum(int num) { this.num = num; }
// public String getCid() { return this.cid; }
// public void setCid(String cid) { this.cid = cid; }
//
// public boolean isGreater(Timestamp ts) {
// if (ts == null || this.num > ts.num ||
// this.num == ts.num && this.cid.compareTo(ts.cid) < 0)
// return true;
// return false;
// }
//
// public void inc(String client) {
// this.num = this.num + 1;
// this.cid = client;
// }
//
// public String toString() {
// return this.num + "_" + this.cid;
// }
//
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (this.cid == null ? 0 : this.cid.hashCode());
// result = prime * result + this.num;
// return result;
// }
//
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (this.getClass() != obj.getClass())
// return false;
// Timestamp other = (Timestamp) obj;
// if (this.cid == null) {
// if (other.cid != null)
// return false;
// } else if (!this.cid.equals(other.cid))
// return false;
// if (this.num != other.num)
// return false;
// return true;
// }
//
// public void write(Kryo kryo, Output output) {
// output.writeShort(this.num);
// output.writeAscii(this.cid);
// }
// public void read(Kryo kryo, Input input) {
// this.num = input.readShort();
// this.cid = input.readString();
// }
// }
//
// Path: src/main/java/fr/eurecom/hybris/HybrisException.java
// public class HybrisException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public HybrisException(String message){
// super(message);
// }
//
// public HybrisException(String message, Throwable t){
// super(message, t);
// }
//
// public HybrisException(Exception e) {
// super(e);
// }
// }
| import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.zookeeper.data.Stat;
import fr.eurecom.hybris.Hybris.HybrisWatcher;
import fr.eurecom.hybris.kvs.drivers.Kvs;
import fr.eurecom.hybris.mds.Metadata.Timestamp;
import fr.eurecom.hybris.HybrisException; | /**
* Copyright (C) 2013 EURECOM (www.eurecom.fr)
*
* 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 fr.eurecom.hybris.mds;
/**
* Reliable Metadata Store interface.
* @author viotti
*/
public interface Rmds {
public static final String ZOOKEEPER_ID = "zk";
public static final String CONSUL_ID = "consul";
/* Conventional integer marker to tell whether a
* metadata key has to be created (rather than modified).
*
* Used as Zookeeper setData API parameter,
* it forces overwriting no matter which
* znode version is currently written.
*/
public static final int NONODE = -1;
/**
* Timestamped write on metadata storage.
* @param key - the key
* @param md - the metadata to be written
* @param version - the existing metadata key version we expect; -1 when the metadata key does not exist
* @return boolean: true if a metadata key has been modified and stale old values need to be garbage-collected
* false otherwise (i.e. a new metadata key has been created)
* @throws HybrisException
*/ | // Path: src/main/java/fr/eurecom/hybris/Hybris.java
// public class HybrisWatcher implements CuratorWatcher {
//
// private boolean changed = false;
// public boolean isChanged() { return this.changed; }
//
// /**
// * Process a notification sent by ZooKeeper
// * @see org.apache.curator.framework.api.CuratorWatcher#process(org.apache.zookeeper.WatchedEvent)
// */
// public void process(WatchedEvent event) throws Exception {
// this.changed = true;
// }
// }
//
// Path: src/main/java/fr/eurecom/hybris/mds/Metadata.java
// public static class Timestamp implements KryoSerializable {
//
// private int num;
// private String cid;
//
// public Timestamp() { }
// public Timestamp(int n, String c) {
// this.num = n;
// this.cid = c;
// }
//
// public static Timestamp parseString(String tsStr) {
// String[] tsParts = tsStr.split("_");
// int n = Integer.parseInt(tsParts[0]);
// String cid = tsParts[1];
// return new Timestamp(n, cid);
// }
//
// public int getNum() { return this.num; }
// public void setNum(int num) { this.num = num; }
// public String getCid() { return this.cid; }
// public void setCid(String cid) { this.cid = cid; }
//
// public boolean isGreater(Timestamp ts) {
// if (ts == null || this.num > ts.num ||
// this.num == ts.num && this.cid.compareTo(ts.cid) < 0)
// return true;
// return false;
// }
//
// public void inc(String client) {
// this.num = this.num + 1;
// this.cid = client;
// }
//
// public String toString() {
// return this.num + "_" + this.cid;
// }
//
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + (this.cid == null ? 0 : this.cid.hashCode());
// result = prime * result + this.num;
// return result;
// }
//
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (this.getClass() != obj.getClass())
// return false;
// Timestamp other = (Timestamp) obj;
// if (this.cid == null) {
// if (other.cid != null)
// return false;
// } else if (!this.cid.equals(other.cid))
// return false;
// if (this.num != other.num)
// return false;
// return true;
// }
//
// public void write(Kryo kryo, Output output) {
// output.writeShort(this.num);
// output.writeAscii(this.cid);
// }
// public void read(Kryo kryo, Input input) {
// this.num = input.readShort();
// this.cid = input.readString();
// }
// }
//
// Path: src/main/java/fr/eurecom/hybris/HybrisException.java
// public class HybrisException extends Exception {
//
// private static final long serialVersionUID = 1L;
//
// public HybrisException(String message){
// super(message);
// }
//
// public HybrisException(String message, Throwable t){
// super(message, t);
// }
//
// public HybrisException(Exception e) {
// super(e);
// }
// }
// Path: src/main/java/fr/eurecom/hybris/mds/Rmds.java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.zookeeper.data.Stat;
import fr.eurecom.hybris.Hybris.HybrisWatcher;
import fr.eurecom.hybris.kvs.drivers.Kvs;
import fr.eurecom.hybris.mds.Metadata.Timestamp;
import fr.eurecom.hybris.HybrisException;
/**
* Copyright (C) 2013 EURECOM (www.eurecom.fr)
*
* 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 fr.eurecom.hybris.mds;
/**
* Reliable Metadata Store interface.
* @author viotti
*/
public interface Rmds {
public static final String ZOOKEEPER_ID = "zk";
public static final String CONSUL_ID = "consul";
/* Conventional integer marker to tell whether a
* metadata key has to be created (rather than modified).
*
* Used as Zookeeper setData API parameter,
* it forces overwriting no matter which
* znode version is currently written.
*/
public static final int NONODE = -1;
/**
* Timestamped write on metadata storage.
* @param key - the key
* @param md - the metadata to be written
* @param version - the existing metadata key version we expect; -1 when the metadata key does not exist
* @return boolean: true if a metadata key has been modified and stale old values need to be garbage-collected
* false otherwise (i.e. a new metadata key has been created)
* @throws HybrisException
*/ | boolean tsWrite(String key, Metadata md, long version) throws HybrisException; |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java | // Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.converters.path;
public interface IPathToProjectNameConverter {
public abstract String convert(String toParse) | // Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.converters.path;
public interface IPathToProjectNameConverter {
public abstract String convert(String toParse) | throws UnparsableProjectException; |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandImpl.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler; | package com.asolutions.scmsshd.commands.git;
public abstract class GitSCMCommandImpl implements ISCMCommandHandler {
protected final Logger log = LoggerFactory.getLogger(getClass());
public GitSCMCommandImpl() {
super();
}
| // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandImpl.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler;
package com.asolutions.scmsshd.commands.git;
public abstract class GitSCMCommandImpl implements ISCMCommandHandler {
protected final Logger log = LoggerFactory.getLogger(getClass());
public GitSCMCommandImpl() {
super();
}
| public void execute(FilteredCommand filteredCommand, |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandImpl.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
| import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler; | package com.asolutions.scmsshd.commands.git;
public abstract class GitSCMCommandImpl implements ISCMCommandHandler {
protected final Logger log = LoggerFactory.getLogger(getClass());
public GitSCMCommandImpl() {
super();
}
public void execute(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandImpl.java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler;
package com.asolutions.scmsshd.commands.git;
public abstract class GitSCMCommandImpl implements ISCMCommandHandler {
protected final Logger log = LoggerFactory.getLogger(getClass());
public GitSCMCommandImpl() {
super();
}
public void execute(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | Properties config, AuthorizationLevel authorizationLevel) { |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
| final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
|
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
| will(throwException(new BadCommandException()));
|
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
| assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
|
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
| final FilteredCommand filteredCommand = new FilteredCommand(COMMAND, ARGUMENT);
|
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
final FilteredCommand filteredCommand = new FilteredCommand(COMMAND, ARGUMENT);
final ISCMCommandFactory mockScmCommandFactory = context.mock(ISCMCommandFactory.class);
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
final FilteredCommand filteredCommand = new FilteredCommand(COMMAND, ARGUMENT);
final ISCMCommandFactory mockScmCommandFactory = context.mock(ISCMCommandFactory.class);
| final IProjectAuthorizer mockProjAuth = context.mock(IProjectAuthorizer.class);
|
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
final FilteredCommand filteredCommand = new FilteredCommand(COMMAND, ARGUMENT);
final ISCMCommandFactory mockScmCommandFactory = context.mock(ISCMCommandFactory.class);
final IProjectAuthorizer mockProjAuth = context.mock(IProjectAuthorizer.class);
| // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBaseTest.java
import static org.junit.Assert.assertEquals;
import java.util.Properties;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBaseTest extends MockTestCase {
private static final String ARGUMENT = "argument";
private static final String COMMAND = "command";
@Test
public void testBadCommandReturnsNoOp() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
checking(new Expectations(){{
one(mockBadCommandFilter).filterOrThrow(COMMAND);
will(throwException(new BadCommandException()));
}});
CommandFactoryBase factory = new CommandFactoryBase();
factory.setBadCommandFilter(mockBadCommandFilter);
assertEquals(NoOpCommand.class, factory.createCommand(COMMAND).getClass());
}
@Test
public void testChecksBadCommandFirst() throws Exception {
final IBadCommandFilter mockBadCommandFilter = context.mock(IBadCommandFilter.class);
final FilteredCommand filteredCommand = new FilteredCommand(COMMAND, ARGUMENT);
final ISCMCommandFactory mockScmCommandFactory = context.mock(ISCMCommandFactory.class);
final IProjectAuthorizer mockProjAuth = context.mock(IProjectAuthorizer.class);
| final IPathToProjectNameConverter mockPathConverter = context.mock(IPathToProjectNameConverter.class);
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/ldap/JavaxNamingProvider.java | // Path: src/main/java/com/asolutions/scmsshd/ssl/PromiscuousSSLSocketFactory.java
// public class PromiscuousSSLSocketFactory extends SocketFactory {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private static SocketFactory blindFactory = null;
//
// /**
// *
// * Builds an all trusting "blind" ssl socket factory.
// *
// */
//
// static {
// // create a trust manager that will purposefully fall down on the
// // job
// TrustManager[] blindTrustMan = new TrustManager[] { new X509TrustManager() {
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
// public void checkClientTrusted(X509Certificate[] c, String a) {
// }
// public void checkServerTrusted(X509Certificate[] c, String a) {
// }
// } };
//
// // create our "blind" ssl socket factory with our lazy trust manager
// try {
// SSLContext sc = SSLContext.getInstance("SSL");
// sc.init(null, blindTrustMan, new java.security.SecureRandom());
// blindFactory = sc.getSocketFactory();
// } catch (GeneralSecurityException e) {
// LoggerFactory.getLogger(PromiscuousSSLSocketFactory.class).error("Error taking security promiscuous" , e);
// }
// }
//
// /**
// *
// * @see javax.net.SocketFactory#getDefault()
// *
// */
//
// public static SocketFactory getDefault() {
// return new PromiscuousSSLSocketFactory();
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1) throws IOException,
// UnknownHostException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1) throws IOException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3)
// throws IOException, UnknownHostException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
//
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
// }
//
// }
| import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import com.asolutions.scmsshd.ssl.PromiscuousSSLSocketFactory; | package com.asolutions.scmsshd.ldap;
public class JavaxNamingProvider implements IJavaxNamingProvider {
private String url;
private boolean promiscuous;
public JavaxNamingProvider(String url, boolean promiscuous) {
this.url = url;
this.promiscuous = promiscuous;
}
public InitialDirContext getBinding(String userDN, String lookupUserPassword) throws NamingException {
return new InitialDirContext(getProperties(url, userDN, lookupUserPassword, promiscuous));
}
public Properties getProperties(String url, String username, String password, boolean promiscuous)
{
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.setProperty(Context.PROVIDER_URL, url);
properties.setProperty(Context.SECURITY_PRINCIPAL, username);
properties.setProperty(Context.SECURITY_CREDENTIALS, password);
if (promiscuous){ | // Path: src/main/java/com/asolutions/scmsshd/ssl/PromiscuousSSLSocketFactory.java
// public class PromiscuousSSLSocketFactory extends SocketFactory {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private static SocketFactory blindFactory = null;
//
// /**
// *
// * Builds an all trusting "blind" ssl socket factory.
// *
// */
//
// static {
// // create a trust manager that will purposefully fall down on the
// // job
// TrustManager[] blindTrustMan = new TrustManager[] { new X509TrustManager() {
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
// public void checkClientTrusted(X509Certificate[] c, String a) {
// }
// public void checkServerTrusted(X509Certificate[] c, String a) {
// }
// } };
//
// // create our "blind" ssl socket factory with our lazy trust manager
// try {
// SSLContext sc = SSLContext.getInstance("SSL");
// sc.init(null, blindTrustMan, new java.security.SecureRandom());
// blindFactory = sc.getSocketFactory();
// } catch (GeneralSecurityException e) {
// LoggerFactory.getLogger(PromiscuousSSLSocketFactory.class).error("Error taking security promiscuous" , e);
// }
// }
//
// /**
// *
// * @see javax.net.SocketFactory#getDefault()
// *
// */
//
// public static SocketFactory getDefault() {
// return new PromiscuousSSLSocketFactory();
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1) throws IOException,
// UnknownHostException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1) throws IOException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3)
// throws IOException, UnknownHostException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
//
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/ldap/JavaxNamingProvider.java
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import com.asolutions.scmsshd.ssl.PromiscuousSSLSocketFactory;
package com.asolutions.scmsshd.ldap;
public class JavaxNamingProvider implements IJavaxNamingProvider {
private String url;
private boolean promiscuous;
public JavaxNamingProvider(String url, boolean promiscuous) {
this.url = url;
this.promiscuous = promiscuous;
}
public InitialDirContext getBinding(String userDN, String lookupUserPassword) throws NamingException {
return new InitialDirContext(getProperties(url, userDN, lookupUserPassword, promiscuous));
}
public Properties getProperties(String url, String username, String password, boolean promiscuous)
{
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.setProperty(Context.PROVIDER_URL, url);
properties.setProperty(Context.SECURITY_PRINCIPAL, username);
properties.setProperty(Context.SECURITY_CREDENTIALS, password);
if (promiscuous){ | properties.setProperty("java.naming.ldap.factory.socket", PromiscuousSSLSocketFactory.class.getName()); |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java | // Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.authorizors;
public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
public AuthorizationLevel userIsAuthorizedForProject(String username, | // Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.authorizors;
public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
public AuthorizationLevel userIsAuthorizedForProject(String username, | String project) throws UnparsableProjectException { |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/converters/path/regexp/ConfigurablePathToProjectConverterTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/asynchrony/customizations/AsynchronyPathToProjectNameConverter.java
// public class AsynchronyPathToProjectNameConverter extends AMatchingGroupPathToProjectNameConverter {
//
// private static Pattern pattern = Pattern.compile("(proj-\\d+)");
//
// public AsynchronyPathToProjectNameConverter() {
// }
//
// @Override
// public Pattern getPattern() {
// return pattern;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.asynchrony.customizations.AsynchronyPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.converters.path.regexp;
public class ConfigurablePathToProjectConverterTest extends MockTestCase{
@Test
public void testMatchReturnsTrue() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
assertEquals("2", converter.convert("'/proj-2/git.git'"));
}
@Test
public void testNoMatchThrowsException() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
try{ | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/asynchrony/customizations/AsynchronyPathToProjectNameConverter.java
// public class AsynchronyPathToProjectNameConverter extends AMatchingGroupPathToProjectNameConverter {
//
// private static Pattern pattern = Pattern.compile("(proj-\\d+)");
//
// public AsynchronyPathToProjectNameConverter() {
// }
//
// @Override
// public Pattern getPattern() {
// return pattern;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/converters/path/regexp/ConfigurablePathToProjectConverterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.asynchrony.customizations.AsynchronyPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.converters.path.regexp;
public class ConfigurablePathToProjectConverterTest extends MockTestCase{
@Test
public void testMatchReturnsTrue() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
assertEquals("2", converter.convert("'/proj-2/git.git'"));
}
@Test
public void testNoMatchThrowsException() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
try{ | new AsynchronyPathToProjectNameConverter().convert(""); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/converters/path/regexp/ConfigurablePathToProjectConverterTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/asynchrony/customizations/AsynchronyPathToProjectNameConverter.java
// public class AsynchronyPathToProjectNameConverter extends AMatchingGroupPathToProjectNameConverter {
//
// private static Pattern pattern = Pattern.compile("(proj-\\d+)");
//
// public AsynchronyPathToProjectNameConverter() {
// }
//
// @Override
// public Pattern getPattern() {
// return pattern;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.asynchrony.customizations.AsynchronyPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.converters.path.regexp;
public class ConfigurablePathToProjectConverterTest extends MockTestCase{
@Test
public void testMatchReturnsTrue() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
assertEquals("2", converter.convert("'/proj-2/git.git'"));
}
@Test
public void testNoMatchThrowsException() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
try{
new AsynchronyPathToProjectNameConverter().convert("");
fail("Did not throw");
} | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/asynchrony/customizations/AsynchronyPathToProjectNameConverter.java
// public class AsynchronyPathToProjectNameConverter extends AMatchingGroupPathToProjectNameConverter {
//
// private static Pattern pattern = Pattern.compile("(proj-\\d+)");
//
// public AsynchronyPathToProjectNameConverter() {
// }
//
// @Override
// public Pattern getPattern() {
// return pattern;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/converters/path/regexp/ConfigurablePathToProjectConverterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.asynchrony.customizations.AsynchronyPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.converters.path.regexp;
public class ConfigurablePathToProjectConverterTest extends MockTestCase{
@Test
public void testMatchReturnsTrue() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
assertEquals("2", converter.convert("'/proj-2/git.git'"));
}
@Test
public void testNoMatchThrowsException() throws Exception {
ConfigurablePathToProjectConverter converter = new ConfigurablePathToProjectConverter();
converter.setProjectPattern("(\\d)");
try{
new AsynchronyPathToProjectNameConverter().convert("");
fail("Did not throw");
} | catch (UnparsableProjectException e){ |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandlerTest extends MockTestCase {
@Test
public void testReceivePackPassesCorrectStuffToJGIT() throws Exception {
final String pathtobasedir = "pathtobasedir"; | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandlerTest extends MockTestCase {
@Test
public void testReceivePackPassesCorrectStuffToJGIT() throws Exception {
final String pathtobasedir = "pathtobasedir"; | final FilteredCommand filteredCommand = new FilteredCommand( |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | final OutputStream mockOutputStream = context.mock(OutputStream.class,
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final Repository mockRepoistory = context.mock(Repository.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final ReceivePack mockUploadPack = context.mock(ReceivePack.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
one(mockRepoProvider).provide(base,
filteredCommand.getArgument());
will(returnValue(mockRepoistory));
one(mockReceivePackProvider).provide(mockRepoistory);
will(returnValue(mockUploadPack));
one(mockUploadPack).receive(mockInputStream, mockOutputStream,
mockErrorStream);
// one(mockExitCallback).onExit(0);
// one(mockOutputStream).flush();
// one(mockErrorStream).flush();
one(mockConfig).getProperty( | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
final OutputStream mockOutputStream = context.mock(OutputStream.class,
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final Repository mockRepoistory = context.mock(Repository.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final ReceivePack mockUploadPack = context.mock(ReceivePack.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
one(mockRepoProvider).provide(base,
filteredCommand.getArgument());
will(returnValue(mockRepoistory));
one(mockReceivePackProvider).provide(mockRepoistory);
will(returnValue(mockUploadPack));
one(mockUploadPack).receive(mockInputStream, mockOutputStream,
mockErrorStream);
// one(mockExitCallback).onExit(0);
// one(mockOutputStream).flush();
// one(mockErrorStream).flush();
one(mockConfig).getProperty( | GitSCMCommandFactory.REPOSITORY_BASE); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final ReceivePack mockUploadPack = context.mock(ReceivePack.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
one(mockRepoProvider).provide(base,
filteredCommand.getArgument());
will(returnValue(mockRepoistory));
one(mockReceivePackProvider).provide(mockRepoistory);
will(returnValue(mockUploadPack));
one(mockUploadPack).receive(mockInputStream, mockOutputStream,
mockErrorStream);
// one(mockExitCallback).onExit(0);
// one(mockOutputStream).flush();
// one(mockErrorStream).flush();
one(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
will(returnValue(pathtobasedir));
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
handler.runCommand(filteredCommand, mockInputStream, mockOutputStream,
mockErrorStream, mockExitCallback, mockConfig, | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final ReceivePack mockUploadPack = context.mock(ReceivePack.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
one(mockRepoProvider).provide(base,
filteredCommand.getArgument());
will(returnValue(mockRepoistory));
one(mockReceivePackProvider).provide(mockRepoistory);
will(returnValue(mockUploadPack));
one(mockUploadPack).receive(mockInputStream, mockOutputStream,
mockErrorStream);
// one(mockExitCallback).onExit(0);
// one(mockOutputStream).flush();
// one(mockErrorStream).flush();
one(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
will(returnValue(pathtobasedir));
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
handler.runCommand(filteredCommand, mockInputStream, mockOutputStream,
mockErrorStream, mockExitCallback, mockConfig, | AuthorizationLevel.AUTH_LEVEL_READ_WRITE); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | final OutputStream mockOutputStream = context.mock(OutputStream.class,
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
never(mockRepoProvider).provide(base,
filteredCommand.getArgument());
never(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
try {
handler.runCommand(filteredCommand, mockInputStream,
mockOutputStream, mockErrorStream, mockExitCallback,
mockConfig, AuthorizationLevel.AUTH_LEVEL_READ_ONLY);
fail("didn't throw"); | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
final OutputStream mockOutputStream = context.mock(OutputStream.class,
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
never(mockRepoProvider).provide(base,
filteredCommand.getArgument());
never(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
try {
handler.runCommand(filteredCommand, mockInputStream,
mockOutputStream, mockErrorStream, mockExitCallback,
mockConfig, AuthorizationLevel.AUTH_LEVEL_READ_ONLY);
fail("didn't throw"); | } catch (Failure e) { |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | "mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
never(mockRepoProvider).provide(base,
filteredCommand.getArgument());
never(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
try {
handler.runCommand(filteredCommand, mockInputStream,
mockOutputStream, mockErrorStream, mockExitCallback,
mockConfig, AuthorizationLevel.AUTH_LEVEL_READ_ONLY);
fail("didn't throw");
} catch (Failure e) { | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/Failure.java
// public class Failure extends RuntimeException {
//
// private static final long serialVersionUID = 5704607166844629700L;
// private int resultCode;
// private final String genericError;
// private final String specifics;
//
// public Failure(int i, String genericError, String specifics) {
// this.resultCode = i;
// this.genericError = genericError;
// this.specifics = specifics;
// }
//
// public int getResultCode() {
// return resultCode;
// }
//
// public String toFormattedErrorMessage(){
// StringBuilder builder = new StringBuilder();
// builder.append("**********************************\n");
// builder.append("\n");
// builder.append(genericError);
// builder.append("\n");
// builder.append("\n");
// builder.append("Specifics:\n");
// builder.append(" ").append(specifics).append("\n");
// builder.append("\n");
// builder.append("**********************************\n");
// return builder.toString();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandlerTest.java
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.jmock.Expectations;
import org.junit.Test;
import static org.junit.Assert.*;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.Failure;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
"mockOutputStream");
final OutputStream mockErrorStream = context.mock(OutputStream.class,
"mockErrorStream");
final ExitCallback mockExitCallback = context.mock(ExitCallback.class);
final GitSCMRepositoryProvider mockRepoProvider = context
.mock(GitSCMRepositoryProvider.class);
final File base = new File(pathtobasedir);
final GitReceivePackProvider mockReceivePackProvider = context
.mock(GitReceivePackProvider.class);
final Properties mockConfig = context.mock(Properties.class);
checking(new Expectations() {
{
never(mockRepoProvider).provide(base,
filteredCommand.getArgument());
never(mockConfig).getProperty(
GitSCMCommandFactory.REPOSITORY_BASE);
}
});
GitSCMCommandImpl handler = new GitReceivePackSCMCommandHandler(
mockRepoProvider, mockReceivePackProvider);
try {
handler.runCommand(filteredCommand, mockInputStream,
mockOutputStream, mockErrorStream, mockExitCallback,
mockConfig, AuthorizationLevel.AUTH_LEVEL_READ_ONLY);
fail("didn't throw");
} catch (Failure e) { | assertEquals(MustHaveWritePrivilagesToPushFailure.class, e |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory; | package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override | protected void runCommand(FilteredCommand filteredCommand, |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory; | package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | Properties config, AuthorizationLevel authorizationLevel) |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory; | package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel)
throws IOException {
log.info("Starting Upload Pack Of: " + filteredCommand.getArgument());
| // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitUploadPackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.UploadPack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
package com.asolutions.scmsshd.commands.git;
public class GitUploadPackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitUploadPackProvider uploadPackProvider;
public GitUploadPackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(),
new GitUploadPackProvider());
}
public GitUploadPackSCMCommandHandler(
GitSCMRepositoryProvider repositoryProvider,
GitUploadPackProvider uploadPackProvider) {
this.repositoryProvider = repositoryProvider;
this.uploadPackProvider = uploadPackProvider;
}
@Override
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel)
throws IOException {
log.info("Starting Upload Pack Of: " + filteredCommand.getArgument());
| String strRepoBase = config.getProperty(GitSCMCommandFactory.REPOSITORY_BASE); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/PushTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spearce.jgit.lib.Ref;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | }
@After
public void closeRepos()
{
fromRepository.close();
}
@Test
public void testPush() throws Exception {
addRemoteConfigForLocalGitDirectory(fromRepository, toRepoDir, ORIGIN);
push(ORIGIN, REFSPEC, fromRepository);
assertPushOfMaster(fromRefMaster);
}
@Test
public void testRoundTrip() throws Exception {
File gitDir = new File(".git");
addRemoteConfigForLocalGitDirectory(fromRepository, toRepoDir, ORIGIN);
push(ORIGIN, REFSPEC, fromRepository);
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, ORIGIN);
FetchResult r = cloneFromRemote(db, ORIGIN);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testPushSCuMD() throws Exception { | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/PushTest.java
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.spearce.jgit.lib.Ref;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
}
@After
public void closeRepos()
{
fromRepository.close();
}
@Test
public void testPush() throws Exception {
addRemoteConfigForLocalGitDirectory(fromRepository, toRepoDir, ORIGIN);
push(ORIGIN, REFSPEC, fromRepository);
assertPushOfMaster(fromRefMaster);
}
@Test
public void testRoundTrip() throws Exception {
File gitDir = new File(".git");
addRemoteConfigForLocalGitDirectory(fromRepository, toRepoDir, ORIGIN);
push(ORIGIN, REFSPEC, fromRepository);
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, ORIGIN);
FetchResult r = cloneFromRemote(db, ORIGIN);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testPushSCuMD() throws Exception { | final SCuMD sshd = new SCuMD(); |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
| private IProjectAuthorizer projectAuthorizer;
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
| private IBadCommandFilter badCommandFilter;
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
| private IPathToProjectNameConverter pathToProjectNameConverter;
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
| FilteredCommand fc = badCommandFilter.filterOrThrow(command);
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
FilteredCommand fc = badCommandFilter.filterOrThrow(command);
return scmCommandFactory.create(fc, projectAuthorizer, pathToProjectNameConverter, getConfiguration());
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
FilteredCommand fc = badCommandFilter.filterOrThrow(command);
return scmCommandFactory.create(fc, projectAuthorizer, pathToProjectNameConverter, getConfiguration());
| } catch (BadCommandException e) {
|
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
| package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
FilteredCommand fc = badCommandFilter.filterOrThrow(command);
return scmCommandFactory.create(fc, projectAuthorizer, pathToProjectNameConverter, getConfiguration());
} catch (BadCommandException e) {
log.error("Got Bad Command Exception For Command: [" + command
+ "]", e);
| // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/NoOpCommand.java
// public class NoOpCommand implements Command {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private ExitCallback callback;
//
// public void setErrorStream(OutputStream err) {
// }
//
// public void setExitCallback(ExitCallback callback) {
// this.callback = callback;
// }
//
// public void setInputStream(InputStream in) {
// }
//
// public void setOutputStream(OutputStream out) {
// }
//
// public void start() throws IOException {
// log.info("Executing No Op Command");
// callback.onExit(-1);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/IBadCommandFilter.java
// public interface IBadCommandFilter {
//
// FilteredCommand filterOrThrow(String command) throws BadCommandException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/CommandFactoryBase.java
import java.util.Properties;
import org.apache.sshd.server.CommandFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.NoOpCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.IBadCommandFilter;
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.commands.factories;
public class CommandFactoryBase implements CommandFactory {
protected final Logger log = LoggerFactory.getLogger(getClass());
private IProjectAuthorizer projectAuthorizer;
private IBadCommandFilter badCommandFilter;
private ISCMCommandFactory scmCommandFactory;
private IPathToProjectNameConverter pathToProjectNameConverter;
private Properties configuration;
public CommandFactoryBase() {
}
public Command createCommand(String command) {
log.info("Creating command handler for {}", command);
try {
FilteredCommand fc = badCommandFilter.filterOrThrow(command);
return scmCommandFactory.create(fc, projectAuthorizer, pathToProjectNameConverter, getConfiguration());
} catch (BadCommandException e) {
log.error("Got Bad Command Exception For Command: [" + command
+ "]", e);
| return new NoOpCommand();
|
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java | // Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.test.integration.util;
public class ConstantProjectNameConverter implements
IPathToProjectNameConverter {
public ConstantProjectNameConverter() {
}
| // Path: src/main/java/com/asolutions/scmsshd/converters/path/IPathToProjectNameConverter.java
// public interface IPathToProjectNameConverter {
//
// public abstract String convert(String toParse)
// throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
import com.asolutions.scmsshd.converters.path.IPathToProjectNameConverter;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.test.integration.util;
public class ConstantProjectNameConverter implements
IPathToProjectNameConverter {
public ConstantProjectNameConverter() {
}
| public String convert(String toParse) throws UnparsableProjectException { |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/authorizors/PassIfAnyInCollectionPassAuthorizorTest.java | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
| import static org.junit.Assert.*;
import java.util.ArrayList;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer; | package com.asolutions.scmsshd.authorizors;
public class PassIfAnyInCollectionPassAuthorizorTest extends MockTestCase {
private static final String PROJECT = "project";
private static final String USERNAME = "username";
@Test
public void testAuthingWithEmptyChainFails() throws Exception {
assertNull(new PassIfAnyInCollectionPassAuthorizor().userIsAuthorizedForProject(USERNAME, PROJECT));
}
@Test
public void testIfAnyPassItPasses() throws Exception { | // Path: src/test/java/com/asolutions/MockTestCase.java
// public class MockTestCase {
//
// protected Mockery context = new JUnit4Mockery();
//
// @Before
// public void setupMockery() {
// context.setImposteriser(ClassImposteriser.INSTANCE);
// }
//
// @After
// public void mockeryAssertIsSatisfied(){
// context.assertIsSatisfied();
// }
//
// protected void checking(Expectations expectations) {
// context.checking(expectations);
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
// Path: src/test/java/com/asolutions/scmsshd/authorizors/PassIfAnyInCollectionPassAuthorizorTest.java
import static org.junit.Assert.*;
import java.util.ArrayList;
import org.jmock.Expectations;
import org.junit.Test;
import com.asolutions.MockTestCase;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
package com.asolutions.scmsshd.authorizors;
public class PassIfAnyInCollectionPassAuthorizorTest extends MockTestCase {
private static final String PROJECT = "project";
private static final String USERNAME = "username";
@Test
public void testAuthingWithEmptyChainFails() throws Exception {
assertNull(new PassIfAnyInCollectionPassAuthorizor().userIsAuthorizedForProject(USERNAME, PROJECT));
}
@Test
public void testIfAnyPassItPasses() throws Exception { | final IProjectAuthorizer failsAuth = context.mock(IProjectAuthorizer.class, "failsAuth"); |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
| import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler; | package com.asolutions.scmsshd.commands.git;
public class GitSCMCommandHandler implements ISCMCommandHandler {
private ISCMCommandHandler uploadPackHandler;
private ISCMCommandHandler receivePackHandler;
public GitSCMCommandHandler() {
this(new GitUploadPackSCMCommandHandler(), new GitReceivePackSCMCommandHandler());
}
public GitSCMCommandHandler(ISCMCommandHandler uploadPackHandler,
ISCMCommandHandler receivePackHandler) {
this.uploadPackHandler = uploadPackHandler;
this.receivePackHandler = receivePackHandler;
}
| // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandHandler.java
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler;
package com.asolutions.scmsshd.commands.git;
public class GitSCMCommandHandler implements ISCMCommandHandler {
private ISCMCommandHandler uploadPackHandler;
private ISCMCommandHandler receivePackHandler;
public GitSCMCommandHandler() {
this(new GitUploadPackSCMCommandHandler(), new GitReceivePackSCMCommandHandler());
}
public GitSCMCommandHandler(ISCMCommandHandler uploadPackHandler,
ISCMCommandHandler receivePackHandler) {
this.uploadPackHandler = uploadPackHandler;
this.receivePackHandler = receivePackHandler;
}
| public void execute(FilteredCommand filteredCommand, |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
| import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler; | package com.asolutions.scmsshd.commands.git;
public class GitSCMCommandHandler implements ISCMCommandHandler {
private ISCMCommandHandler uploadPackHandler;
private ISCMCommandHandler receivePackHandler;
public GitSCMCommandHandler() {
this(new GitUploadPackSCMCommandHandler(), new GitReceivePackSCMCommandHandler());
}
public GitSCMCommandHandler(ISCMCommandHandler uploadPackHandler,
ISCMCommandHandler receivePackHandler) {
this.uploadPackHandler = uploadPackHandler;
this.receivePackHandler = receivePackHandler;
}
public void execute(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties configuration, | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/handlers/ISCMCommandHandler.java
// public interface ISCMCommandHandler {
//
// void execute(FilteredCommand filteredCommand, InputStream inputStream,
// OutputStream outputStream, OutputStream errorStream,
// ExitCallback exitCallback, Properties configuration, AuthorizationLevel authorizationLevel);
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitSCMCommandHandler.java
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.handlers.ISCMCommandHandler;
package com.asolutions.scmsshd.commands.git;
public class GitSCMCommandHandler implements ISCMCommandHandler {
private ISCMCommandHandler uploadPackHandler;
private ISCMCommandHandler receivePackHandler;
public GitSCMCommandHandler() {
this(new GitUploadPackSCMCommandHandler(), new GitReceivePackSCMCommandHandler());
}
public GitSCMCommandHandler(ISCMCommandHandler uploadPackHandler,
ISCMCommandHandler receivePackHandler) {
this.uploadPackHandler = uploadPackHandler;
this.receivePackHandler = receivePackHandler;
}
public void execute(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties configuration, | AuthorizationLevel authorizationLevel) { |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/authorizors/PassIfAnyInCollectionPassAuthorizor.java | // Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import java.util.ArrayList;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.authorizors;
public class PassIfAnyInCollectionPassAuthorizor implements IProjectAuthorizer {
private ArrayList<IProjectAuthorizer> authList = new ArrayList<IProjectAuthorizer>();
public AuthorizationLevel userIsAuthorizedForProject(String username, String project) | // Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/authorizors/PassIfAnyInCollectionPassAuthorizor.java
import java.util.ArrayList;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.authorizors;
public class PassIfAnyInCollectionPassAuthorizor implements IProjectAuthorizer {
private ArrayList<IProjectAuthorizer> authList = new ArrayList<IProjectAuthorizer>();
public AuthorizationLevel userIsAuthorizedForProject(String username, String project) | throws UnparsableProjectException { |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/ldap/LDAPBindingProvider.java | // Path: src/main/java/com/asolutions/scmsshd/ssl/PromiscuousSSLSocketFactory.java
// public class PromiscuousSSLSocketFactory extends SocketFactory {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private static SocketFactory blindFactory = null;
//
// /**
// *
// * Builds an all trusting "blind" ssl socket factory.
// *
// */
//
// static {
// // create a trust manager that will purposefully fall down on the
// // job
// TrustManager[] blindTrustMan = new TrustManager[] { new X509TrustManager() {
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
// public void checkClientTrusted(X509Certificate[] c, String a) {
// }
// public void checkServerTrusted(X509Certificate[] c, String a) {
// }
// } };
//
// // create our "blind" ssl socket factory with our lazy trust manager
// try {
// SSLContext sc = SSLContext.getInstance("SSL");
// sc.init(null, blindTrustMan, new java.security.SecureRandom());
// blindFactory = sc.getSocketFactory();
// } catch (GeneralSecurityException e) {
// LoggerFactory.getLogger(PromiscuousSSLSocketFactory.class).error("Error taking security promiscuous" , e);
// }
// }
//
// /**
// *
// * @see javax.net.SocketFactory#getDefault()
// *
// */
//
// public static SocketFactory getDefault() {
// return new PromiscuousSSLSocketFactory();
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1) throws IOException,
// UnknownHostException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1) throws IOException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3)
// throws IOException, UnknownHostException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
//
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
// }
//
// }
| import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import com.asolutions.scmsshd.ssl.PromiscuousSSLSocketFactory; | /**
*
*/
package com.asolutions.scmsshd.ldap;
public class LDAPBindingProvider {
private String lookupUserDN;
private String lookupUserPassword;
private String url;
private boolean promiscuous;
public LDAPBindingProvider(String lookupUserDN, String lookupUserPassword,
String url, boolean promiscuous) {
this.lookupUserDN = lookupUserDN;
this.lookupUserPassword = lookupUserPassword;
this.url = url;
this.promiscuous = promiscuous;
}
public InitialDirContext getBinding() throws NamingException {
return new InitialDirContext(getProperties(url, lookupUserDN, lookupUserPassword, promiscuous));
}
public InitialDirContext getBinding(String lookupUserDN, String lookupUserPassword) throws NamingException {
return new InitialDirContext(getProperties(url, lookupUserDN, lookupUserPassword, promiscuous));
}
public Properties getProperties(String url, String username, String password, boolean promiscuous)
{
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.setProperty(Context.PROVIDER_URL, url);
properties.setProperty(Context.SECURITY_PRINCIPAL, username);
properties.setProperty(Context.SECURITY_CREDENTIALS, password);
if (promiscuous){ | // Path: src/main/java/com/asolutions/scmsshd/ssl/PromiscuousSSLSocketFactory.java
// public class PromiscuousSSLSocketFactory extends SocketFactory {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// private static SocketFactory blindFactory = null;
//
// /**
// *
// * Builds an all trusting "blind" ssl socket factory.
// *
// */
//
// static {
// // create a trust manager that will purposefully fall down on the
// // job
// TrustManager[] blindTrustMan = new TrustManager[] { new X509TrustManager() {
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
// public void checkClientTrusted(X509Certificate[] c, String a) {
// }
// public void checkServerTrusted(X509Certificate[] c, String a) {
// }
// } };
//
// // create our "blind" ssl socket factory with our lazy trust manager
// try {
// SSLContext sc = SSLContext.getInstance("SSL");
// sc.init(null, blindTrustMan, new java.security.SecureRandom());
// blindFactory = sc.getSocketFactory();
// } catch (GeneralSecurityException e) {
// LoggerFactory.getLogger(PromiscuousSSLSocketFactory.class).error("Error taking security promiscuous" , e);
// }
// }
//
// /**
// *
// * @see javax.net.SocketFactory#getDefault()
// *
// */
//
// public static SocketFactory getDefault() {
// return new PromiscuousSSLSocketFactory();
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1) throws IOException,
// UnknownHostException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1) throws IOException {
// return blindFactory.createSocket(arg0, arg1);
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.lang.String, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(String arg0, int arg1, InetAddress arg2, int arg3)
// throws IOException, UnknownHostException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
//
// }
//
// /**
// *
// * @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int,
// *
// * java.net.InetAddress, int)
// *
// */
//
// @Override
// public Socket createSocket(InetAddress arg0, int arg1, InetAddress arg2, int arg3) throws IOException {
// return blindFactory.createSocket(arg0, arg1, arg2, arg3);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/ldap/LDAPBindingProvider.java
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.InitialDirContext;
import com.asolutions.scmsshd.ssl.PromiscuousSSLSocketFactory;
/**
*
*/
package com.asolutions.scmsshd.ldap;
public class LDAPBindingProvider {
private String lookupUserDN;
private String lookupUserPassword;
private String url;
private boolean promiscuous;
public LDAPBindingProvider(String lookupUserDN, String lookupUserPassword,
String url, boolean promiscuous) {
this.lookupUserDN = lookupUserDN;
this.lookupUserPassword = lookupUserPassword;
this.url = url;
this.promiscuous = promiscuous;
}
public InitialDirContext getBinding() throws NamingException {
return new InitialDirContext(getProperties(url, lookupUserDN, lookupUserPassword, promiscuous));
}
public InitialDirContext getBinding(String lookupUserDN, String lookupUserPassword) throws NamingException {
return new InitialDirContext(getProperties(url, lookupUserDN, lookupUserPassword, promiscuous));
}
public Properties getProperties(String url, String username, String password, boolean promiscuous)
{
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.setProperty(Context.PROVIDER_URL, url);
properties.setProperty(Context.SECURITY_PRINCIPAL, username);
properties.setProperty(Context.SECURITY_CREDENTIALS, password);
if (promiscuous){ | properties.setProperty("java.naming.ldap.factory.socket", PromiscuousSSLSocketFactory.class.getName()); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception { | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception { | final SCuMD sshd = new SCuMD(); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" })); | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" })); | sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator()); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
| // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
| GitCommandFactory factory = new GitCommandFactory(); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory(); | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory(); | factory.setPathToProjectNameConverter(new ConstantProjectNameConverter()); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory();
factory.setPathToProjectNameConverter(new ConstantProjectNameConverter()); | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory();
factory.setPathToProjectNameConverter(new ConstantProjectNameConverter()); | factory.setProjectAuthorizor(new AlwaysPassProjectAuthorizer()); |
gaffo/scumd | src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
| import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter; | package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory();
factory.setPathToProjectNameConverter(new ConstantProjectNameConverter());
factory.setProjectAuthorizor(new AlwaysPassProjectAuthorizer());
Properties config = new Properties(); | // Path: src/main/java/com/asolutions/scmsshd/SCuMD.java
// public class SCuMD extends SshServer {
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// if (args.length != 1) {
// System.err.println("Usage: SCuMD pathToConfigFile");
// return;
// }
// new FileSystemXmlApplicationContext(args[0]);
// }
//
// public SCuMD() {
// if (SecurityUtils.isBouncyCastleRegistered()) {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG14.Factory(), new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new BouncyCastleRandom.Factory()));
// } else {
// setKeyExchangeFactories(Arrays.<NamedFactory<KeyExchange>> asList(new DHG1.Factory()));
// setRandomFactory(new SingletonRandomFactory(new JceRandom.Factory()));
// }
// setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(
// new UserAuthPassword.Factory(),
// new UserAuthPublicKey.Factory()
// ));
// setCipherFactories(Arrays.<NamedFactory<Cipher>> asList(new AES128CBC.Factory(),
// new TripleDESCBC.Factory(),
// new BlowfishCBC.Factory(),
// new AES192CBC.Factory(),
// new AES256CBC.Factory()));
// setCompressionFactories(Arrays.<NamedFactory<Compression>> asList(new CompressionNone.Factory()));
//
// setMacFactories(Arrays.<NamedFactory<Mac>> asList(new HMACMD5.Factory(),
// new HMACSHA1.Factory(),
// new HMACMD596.Factory(),
// new HMACSHA196.Factory()));
//
// setChannelFactories(Arrays.<NamedFactory<ServerChannel>>asList(
// new ChannelSession.Factory()));
// setSignatureFactories(Arrays.<NamedFactory<Signature>> asList(new SignatureDSA.Factory(), new SignatureRSA.Factory()));
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authenticators/AlwaysPassPublicKeyAuthenticator.java
// public class AlwaysPassPublicKeyAuthenticator implements PublickeyAuthenticator {
//
// public boolean hasKey(String username, PublicKey key, ServerSession session) {
// return true;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AlwaysPassProjectAuthorizer.java
// public class AlwaysPassProjectAuthorizer implements IProjectAuthorizer {
//
// public AuthorizationLevel userIsAuthorizedForProject(String username,
// String project) throws UnparsableProjectException {
// return AuthorizationLevel.AUTH_LEVEL_READ_WRITE;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitCommandFactory.java
// public class GitCommandFactory extends CommandFactoryBase {
// protected final Logger log = LoggerFactory.getLogger(getClass());
// public GitCommandFactory() {
// setBadCommandFilter(new GitBadCommandFilter());
// setScmCommandFactory(new GitSCMCommandFactory());
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/util/ConstantProjectNameConverter.java
// public class ConstantProjectNameConverter implements
// IPathToProjectNameConverter {
//
// public ConstantProjectNameConverter() {
// }
//
// public String convert(String toParse) throws UnparsableProjectException {
// return "constant";
// }
//
// }
// Path: src/exttest/java/com/asolutions/scmsshd/test/integration/FetchTest.java
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.junit.Test;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.FetchResult;
import com.asolutions.scmsshd.SCuMD;
import com.asolutions.scmsshd.authenticators.AlwaysPassPublicKeyAuthenticator;
import com.asolutions.scmsshd.authorizors.AlwaysPassProjectAuthorizer;
import com.asolutions.scmsshd.commands.factories.GitCommandFactory;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.test.integration.util.ConstantProjectNameConverter;
package com.asolutions.scmsshd.test.integration;
public class FetchTest extends IntegrationTestCase {
@Test
public void testFetchLocal() throws Exception {
File gitDir = new File(".git");
String remoteName = "origin";
Repository db = createCloneToRepo();
addRemoteConfigForLocalGitDirectory(db, gitDir, remoteName);
FetchResult r = cloneFromRemote(db, remoteName);
assert(r.getTrackingRefUpdates().size() > 0);
}
@Test
public void testFetchFromScumd() throws Exception {
final SCuMD sshd = new SCuMD();
try{
int serverPort = generatePort();
System.out.println("Running on port: " + serverPort);
sshd.setPort(serverPort);
sshd.setKeyPairProvider(new FileKeyPairProvider(new String[] { "src/main/resources/ssh_host_rsa_key",
"src/main/resources/ssh_host_dsa_key" }));
sshd.setPublickeyAuthenticator(new AlwaysPassPublicKeyAuthenticator());
GitCommandFactory factory = new GitCommandFactory();
factory.setPathToProjectNameConverter(new ConstantProjectNameConverter());
factory.setProjectAuthorizor(new AlwaysPassProjectAuthorizer());
Properties config = new Properties(); | config.setProperty(GitSCMCommandFactory.REPOSITORY_BASE, System.getProperty("user.dir")); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/AllowedCommandCheckerTest.java | // Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
| import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.filters.BadCommandException; | package com.asolutions.scmsshd.commands;
public class AllowedCommandCheckerTest {
@Test
public void testParsesGitCommands() throws Exception {
new AllowedCommandChecker("git-upload-pack");
new AllowedCommandChecker("git upload-pack");
new AllowedCommandChecker("git-receive-pack");
new AllowedCommandChecker("git receive-pack");
}
@Test
public void testFailsOnUnknownCommand() throws Exception {
try{
new AllowedCommandChecker("git receive-packs");
fail("Didn't Throw");
} | // Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/AllowedCommandCheckerTest.java
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
package com.asolutions.scmsshd.commands;
public class AllowedCommandCheckerTest {
@Test
public void testParsesGitCommands() throws Exception {
new AllowedCommandChecker("git-upload-pack");
new AllowedCommandChecker("git upload-pack");
new AllowedCommandChecker("git-receive-pack");
new AllowedCommandChecker("git receive-pack");
}
@Test
public void testFailsOnUnknownCommand() throws Exception {
try{
new AllowedCommandChecker("git receive-packs");
fail("Didn't Throw");
} | catch (BadCommandException e){ |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
| // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
| protected void runCommand(FilteredCommand filteredCommand, |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback, | Properties config, AuthorizationLevel authorizationLevel) throws IOException { |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel) throws IOException {
if (authorizationLevel == AuthorizationLevel.AUTH_LEVEL_READ_ONLY){ | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel) throws IOException {
if (authorizationLevel == AuthorizationLevel.AUTH_LEVEL_READ_ONLY){ | throw new MustHaveWritePrivilagesToPushFailure("Tried to push to " + filteredCommand.getArgument()); |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
| import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure; | package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel) throws IOException {
if (authorizationLevel == AuthorizationLevel.AUTH_LEVEL_READ_ONLY){
throw new MustHaveWritePrivilagesToPushFailure("Tried to push to " + filteredCommand.getArgument());
}
try{
String strRepoBase = config | // Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/factories/GitSCMCommandFactory.java
// public class GitSCMCommandFactory implements ISCMCommandFactory {
//
// public static final String REPOSITORY_BASE = "repositoryBase";
//
// public Command create(FilteredCommand filteredCommand,
// IProjectAuthorizer projectAuthorizer,
// IPathToProjectNameConverter pathToProjectNameConverter,
// Properties configuration) {
// SCMCommand retVal = new SCMCommand(filteredCommand, projectAuthorizer, new GitSCMCommandHandler(), pathToProjectNameConverter, configuration);
// return retVal;
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/exceptions/MustHaveWritePrivilagesToPushFailure.java
// public class MustHaveWritePrivilagesToPushFailure extends Failure{
//
// private static final long serialVersionUID = 7650486977318806435L;
//
// public MustHaveWritePrivilagesToPushFailure(String specifics) {
// super(0, "You must have write privilages to be able to push", specifics);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/commands/git/GitReceivePackSCMCommandHandler.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.sshd.server.CommandFactory.ExitCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spearce.jgit.lib.Repository;
import org.spearce.jgit.transport.ReceivePack;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.factories.GitSCMCommandFactory;
import com.asolutions.scmsshd.exceptions.MustHaveWritePrivilagesToPushFailure;
package com.asolutions.scmsshd.commands.git;
public class GitReceivePackSCMCommandHandler extends GitSCMCommandImpl {
protected final Logger log = LoggerFactory.getLogger(getClass());
private GitSCMRepositoryProvider repositoryProvider;
private GitReceivePackProvider receivePackProvider;
public GitReceivePackSCMCommandHandler() {
this(new GitSCMRepositoryProvider(), new GitReceivePackProvider());
}
public GitReceivePackSCMCommandHandler(
GitSCMRepositoryProvider repoProvider,
GitReceivePackProvider uploadPackProvider) {
this.repositoryProvider = repoProvider;
this.receivePackProvider = uploadPackProvider;
}
protected void runCommand(FilteredCommand filteredCommand,
InputStream inputStream, OutputStream outputStream,
OutputStream errorStream, ExitCallback exitCallback,
Properties config, AuthorizationLevel authorizationLevel) throws IOException {
if (authorizationLevel == AuthorizationLevel.AUTH_LEVEL_READ_ONLY){
throw new MustHaveWritePrivilagesToPushFailure("Tried to push to " + filteredCommand.getArgument());
}
try{
String strRepoBase = config | .getProperty(GitSCMCommandFactory.REPOSITORY_BASE); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter; | package com.asolutions.scmsshd.commands.git;
public class GitBadCommandFilterTest {
@Test
public void testCorrect() throws Exception { | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter;
package com.asolutions.scmsshd.commands.git;
public class GitBadCommandFilterTest {
@Test
public void testCorrect() throws Exception { | GitBadCommandFilter filter = new GitBadCommandFilter(); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter; | package com.asolutions.scmsshd.commands.git;
public class GitBadCommandFilterTest {
@Test
public void testCorrect() throws Exception {
GitBadCommandFilter filter = new GitBadCommandFilter(); | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter;
package com.asolutions.scmsshd.commands.git;
public class GitBadCommandFilterTest {
@Test
public void testCorrect() throws Exception {
GitBadCommandFilter filter = new GitBadCommandFilter(); | FilteredCommand fc = filter.filterOrThrow("git-upload-pack 'bob'"); |
gaffo/scumd | src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter; | public void testNoArgs() throws Exception {
assertThrows("git-upload-pack");
}
@Test
public void test2Args() throws Exception {
assertThrows("git-upload-pack bob tom");
}
@Test
public void testUnquoted() throws Exception {
assertThrows("git-upload-pack bob");
}
@Test
public void testWithUnsafeBang() throws Exception {
assertThrows("git-upload-pack 'ev!l'");
}
@Test
public void testWithUnsafeDotDot() throws Exception {
assertThrows("git-upload-pack 'something/../evil'");
}
private void assertThrows(String toCheck) {
try{
GitBadCommandFilter filter = new GitBadCommandFilter();
filter.filterOrThrow(toCheck);
fail("didn't throw");
} | // Path: src/main/java/com/asolutions/scmsshd/commands/FilteredCommand.java
// public class FilteredCommand {
//
// private String command;
// private String argument;
//
// public FilteredCommand() {
// }
//
// public FilteredCommand(String command, String argument) {
// this.command = command;
// this.argument = argument;
// }
//
// public void setArgument(String argument) {
// this.argument = argument;
// }
//
// public void setCommand(String command) {
// this.command = command;
// }
//
// public String getCommand() {
// return this.command;
// }
//
// public String getArgument() {
// return this.argument;
// }
//
// @Override
// public String toString()
// {
// return "Filtered Command: " + getCommand() + ", " + getArgument();
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/BadCommandException.java
// public class BadCommandException extends Exception {
//
// private static final long serialVersionUID = 4904880805323643780L;
//
// public BadCommandException(String reason) {
// super(reason);
// }
//
// public BadCommandException() {
// }
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/commands/filters/git/GitBadCommandFilter.java
// public class GitBadCommandFilter implements IBadCommandFilter {
//
// // private static final Pattern commandFilter = Pattern.compile("^'/*(?P<path>[a-zA-Z0-9][a-zA-Z0-9@._-]*(/[a-zA-Z0-9][a-zA-Z0-9@._-]*)*)'$");
// private static final String commandFilter = "^'.+'$";
// private static final String[] validCommands = {"git-upload-pack", "git-receive-pack"};
// private String[] parts;
//
// public GitBadCommandFilter() {
// }
//
// public FilteredCommand filterOrThrow(String command) throws BadCommandException {
// command = new GitCommandSeamer(command).toString();
// checkForNewlines(command);
// parts = checkForOneArgument(command);
// throwIfContains(parts[1], "..");
// throwIfContains(parts[1], "!");
// checkAgainstPattern(parts[1]);
// checkValidCommands(parts[0]);
// parts[1] = parts[1].replaceAll("^'", "");
// parts[1] = parts[1].replaceAll("'$", "");
// return new FilteredCommand(parts[0], parts[1]);
// }
//
// private void checkValidCommands(String commandToCheck) throws BadCommandException {
// for (String validCommand : validCommands) {
// if (validCommand.equals(commandToCheck)){
// return;
// }
// }
// throw new BadCommandException("Unknown Command: " + commandToCheck);
// }
//
// private void checkAgainstPattern(String command) throws BadCommandException {
// if (!Pattern.matches(commandFilter, command))
// {
// throw new BadCommandException();
// }
// }
//
// private String[] checkForOneArgument(String command) throws BadCommandException {
// String[] parts = command.split(" ");
// int count = parts.length;
// if (count == 1 || count > 2)
// {
// throw new BadCommandException("Invalid Number Of Arguments (must be 1): " + count);
// }
// return parts;
// }
//
// private void checkForNewlines(String command) throws BadCommandException {
// throwIfContains(command, "\n");
// throwIfContains(command, "\r");
// }
//
// private void throwIfContains(String command, String toCheckFor) throws BadCommandException {
// if (command.contains(toCheckFor)){
// throw new BadCommandException("Cant Contain: " + toCheckFor);
// }
// }
//
// public String getCommand()
// {
// return parts[0];
// }
//
// public String getArgument()
// {
// return parts[1];
// }
//
// }
// Path: src/test/java/com/asolutions/scmsshd/commands/git/GitBadCommandFilterTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.Test;
import com.asolutions.scmsshd.commands.FilteredCommand;
import com.asolutions.scmsshd.commands.filters.BadCommandException;
import com.asolutions.scmsshd.commands.filters.git.GitBadCommandFilter;
public void testNoArgs() throws Exception {
assertThrows("git-upload-pack");
}
@Test
public void test2Args() throws Exception {
assertThrows("git-upload-pack bob tom");
}
@Test
public void testUnquoted() throws Exception {
assertThrows("git-upload-pack bob");
}
@Test
public void testWithUnsafeBang() throws Exception {
assertThrows("git-upload-pack 'ev!l'");
}
@Test
public void testWithUnsafeDotDot() throws Exception {
assertThrows("git-upload-pack 'something/../evil'");
}
private void assertThrows(String toCheck) {
try{
GitBadCommandFilter filter = new GitBadCommandFilter();
filter.filterOrThrow(toCheck);
fail("didn't throw");
} | catch (BadCommandException e){ |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/ldap/LDAPProjectAuthorizer.java | // Path: src/main/java/com/asolutions/scmsshd/authenticators/LDAPUsernameResolver.java
// public class LDAPUsernameResolver {
// LDAPBindingProvider provider;
// private String userBase;
// private String matchingElement;
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase) {
// this(provider, userBase, "cn=");
// }
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase, String matchingElement) {
// this.provider = provider;
// this.userBase = userBase;
// this.matchingElement = matchingElement;
// }
//
// public String resolveUserName(String username) throws NamingException{
// InitialDirContext InitialDirectoryContext = provider.getBinding();
// SearchControls searchCtls = new SearchControls();
// //Specify the search scope
// searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//
// //specify the LDAP search filter
// String searchFilter = "("+matchingElement+username+")";
//
// //initialize counter to total the results
//
// // Search for objects using the filter
// NamingEnumeration<SearchResult> answer = InitialDirectoryContext.search(userBase, searchFilter, searchCtls);
// SearchResult next = answer.next();
// return next.getNameInNamespace();
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authenticators.LDAPUsernameResolver;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.ldap;
public class LDAPProjectAuthorizer implements IProjectAuthorizer {
protected final Logger log = LoggerFactory.getLogger(getClass());
private String groupBaseDN;
private String groupSuffix; | // Path: src/main/java/com/asolutions/scmsshd/authenticators/LDAPUsernameResolver.java
// public class LDAPUsernameResolver {
// LDAPBindingProvider provider;
// private String userBase;
// private String matchingElement;
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase) {
// this(provider, userBase, "cn=");
// }
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase, String matchingElement) {
// this.provider = provider;
// this.userBase = userBase;
// this.matchingElement = matchingElement;
// }
//
// public String resolveUserName(String username) throws NamingException{
// InitialDirContext InitialDirectoryContext = provider.getBinding();
// SearchControls searchCtls = new SearchControls();
// //Specify the search scope
// searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//
// //specify the LDAP search filter
// String searchFilter = "("+matchingElement+username+")";
//
// //initialize counter to total the results
//
// // Search for objects using the filter
// NamingEnumeration<SearchResult> answer = InitialDirectoryContext.search(userBase, searchFilter, searchCtls);
// SearchResult next = answer.next();
// return next.getNameInNamespace();
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/ldap/LDAPProjectAuthorizer.java
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authenticators.LDAPUsernameResolver;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.ldap;
public class LDAPProjectAuthorizer implements IProjectAuthorizer {
protected final Logger log = LoggerFactory.getLogger(getClass());
private String groupBaseDN;
private String groupSuffix; | private AuthorizationLevel authorizationLevel; |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/ldap/LDAPProjectAuthorizer.java | // Path: src/main/java/com/asolutions/scmsshd/authenticators/LDAPUsernameResolver.java
// public class LDAPUsernameResolver {
// LDAPBindingProvider provider;
// private String userBase;
// private String matchingElement;
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase) {
// this(provider, userBase, "cn=");
// }
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase, String matchingElement) {
// this.provider = provider;
// this.userBase = userBase;
// this.matchingElement = matchingElement;
// }
//
// public String resolveUserName(String username) throws NamingException{
// InitialDirContext InitialDirectoryContext = provider.getBinding();
// SearchControls searchCtls = new SearchControls();
// //Specify the search scope
// searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//
// //specify the LDAP search filter
// String searchFilter = "("+matchingElement+username+")";
//
// //initialize counter to total the results
//
// // Search for objects using the filter
// NamingEnumeration<SearchResult> answer = InitialDirectoryContext.search(userBase, searchFilter, searchCtls);
// SearchResult next = answer.next();
// return next.getNameInNamespace();
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authenticators.LDAPUsernameResolver;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.ldap;
public class LDAPProjectAuthorizer implements IProjectAuthorizer {
protected final Logger log = LoggerFactory.getLogger(getClass());
private String groupBaseDN;
private String groupSuffix;
private AuthorizationLevel authorizationLevel;
private LDAPBindingProvider binding; | // Path: src/main/java/com/asolutions/scmsshd/authenticators/LDAPUsernameResolver.java
// public class LDAPUsernameResolver {
// LDAPBindingProvider provider;
// private String userBase;
// private String matchingElement;
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase) {
// this(provider, userBase, "cn=");
// }
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase, String matchingElement) {
// this.provider = provider;
// this.userBase = userBase;
// this.matchingElement = matchingElement;
// }
//
// public String resolveUserName(String username) throws NamingException{
// InitialDirContext InitialDirectoryContext = provider.getBinding();
// SearchControls searchCtls = new SearchControls();
// //Specify the search scope
// searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//
// //specify the LDAP search filter
// String searchFilter = "("+matchingElement+username+")";
//
// //initialize counter to total the results
//
// // Search for objects using the filter
// NamingEnumeration<SearchResult> answer = InitialDirectoryContext.search(userBase, searchFilter, searchCtls);
// SearchResult next = answer.next();
// return next.getNameInNamespace();
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/ldap/LDAPProjectAuthorizer.java
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authenticators.LDAPUsernameResolver;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.ldap;
public class LDAPProjectAuthorizer implements IProjectAuthorizer {
protected final Logger log = LoggerFactory.getLogger(getClass());
private String groupBaseDN;
private String groupSuffix;
private AuthorizationLevel authorizationLevel;
private LDAPBindingProvider binding; | private LDAPUsernameResolver resolver; |
gaffo/scumd | src/main/java/com/asolutions/scmsshd/ldap/LDAPProjectAuthorizer.java | // Path: src/main/java/com/asolutions/scmsshd/authenticators/LDAPUsernameResolver.java
// public class LDAPUsernameResolver {
// LDAPBindingProvider provider;
// private String userBase;
// private String matchingElement;
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase) {
// this(provider, userBase, "cn=");
// }
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase, String matchingElement) {
// this.provider = provider;
// this.userBase = userBase;
// this.matchingElement = matchingElement;
// }
//
// public String resolveUserName(String username) throws NamingException{
// InitialDirContext InitialDirectoryContext = provider.getBinding();
// SearchControls searchCtls = new SearchControls();
// //Specify the search scope
// searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//
// //specify the LDAP search filter
// String searchFilter = "("+matchingElement+username+")";
//
// //initialize counter to total the results
//
// // Search for objects using the filter
// NamingEnumeration<SearchResult> answer = InitialDirectoryContext.search(userBase, searchFilter, searchCtls);
// SearchResult next = answer.next();
// return next.getNameInNamespace();
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
| import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authenticators.LDAPUsernameResolver;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException; | package com.asolutions.scmsshd.ldap;
public class LDAPProjectAuthorizer implements IProjectAuthorizer {
protected final Logger log = LoggerFactory.getLogger(getClass());
private String groupBaseDN;
private String groupSuffix;
private AuthorizationLevel authorizationLevel;
private LDAPBindingProvider binding;
private LDAPUsernameResolver resolver;
public LDAPProjectAuthorizer(String groupBaseDN,
String groupSuffix,
AuthorizationLevel authorizationLevel,
LDAPBindingProvider binding,
LDAPUsernameResolver resolver)
throws NamingException {
this.groupBaseDN = groupBaseDN;
this.groupSuffix = groupSuffix;
this.authorizationLevel = authorizationLevel;
this.binding = binding;
this.resolver = resolver;
}
public AuthorizationLevel userIsAuthorizedForProject(String username, String group) | // Path: src/main/java/com/asolutions/scmsshd/authenticators/LDAPUsernameResolver.java
// public class LDAPUsernameResolver {
// LDAPBindingProvider provider;
// private String userBase;
// private String matchingElement;
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase) {
// this(provider, userBase, "cn=");
// }
// public LDAPUsernameResolver(LDAPBindingProvider provider, String userBase, String matchingElement) {
// this.provider = provider;
// this.userBase = userBase;
// this.matchingElement = matchingElement;
// }
//
// public String resolveUserName(String username) throws NamingException{
// InitialDirContext InitialDirectoryContext = provider.getBinding();
// SearchControls searchCtls = new SearchControls();
// //Specify the search scope
// searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//
// //specify the LDAP search filter
// String searchFilter = "("+matchingElement+username+")";
//
// //initialize counter to total the results
//
// // Search for objects using the filter
// NamingEnumeration<SearchResult> answer = InitialDirectoryContext.search(userBase, searchFilter, searchCtls);
// SearchResult next = answer.next();
// return next.getNameInNamespace();
// }
// }
//
// Path: src/main/java/com/asolutions/scmsshd/authorizors/AuthorizationLevel.java
// public enum AuthorizationLevel {
// AUTH_LEVEL_READ_ONLY,
// AUTH_LEVEL_READ_WRITE;
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/IProjectAuthorizer.java
// public interface IProjectAuthorizer {
//
// AuthorizationLevel userIsAuthorizedForProject(String username, String project) throws UnparsableProjectException;
//
// }
//
// Path: src/main/java/com/asolutions/scmsshd/sshd/UnparsableProjectException.java
// public class UnparsableProjectException extends Exception {
//
// private static final long serialVersionUID = 643951700141491862L;
//
// public UnparsableProjectException(String reason) {
// super(reason);
// }
//
// }
// Path: src/main/java/com/asolutions/scmsshd/ldap/LDAPProjectAuthorizer.java
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asolutions.scmsshd.authenticators.LDAPUsernameResolver;
import com.asolutions.scmsshd.authorizors.AuthorizationLevel;
import com.asolutions.scmsshd.sshd.IProjectAuthorizer;
import com.asolutions.scmsshd.sshd.UnparsableProjectException;
package com.asolutions.scmsshd.ldap;
public class LDAPProjectAuthorizer implements IProjectAuthorizer {
protected final Logger log = LoggerFactory.getLogger(getClass());
private String groupBaseDN;
private String groupSuffix;
private AuthorizationLevel authorizationLevel;
private LDAPBindingProvider binding;
private LDAPUsernameResolver resolver;
public LDAPProjectAuthorizer(String groupBaseDN,
String groupSuffix,
AuthorizationLevel authorizationLevel,
LDAPBindingProvider binding,
LDAPUsernameResolver resolver)
throws NamingException {
this.groupBaseDN = groupBaseDN;
this.groupSuffix = groupSuffix;
this.authorizationLevel = authorizationLevel;
this.binding = binding;
this.resolver = resolver;
}
public AuthorizationLevel userIsAuthorizedForProject(String username, String group) | throws UnparsableProjectException { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.